为什么Perl`printf`改变了我的$变量的值?

jip*_*pie 4 security perl

我试图围绕这个安全编码示例中发生的事情.

我重写了代码以更好地支持我的问题:

#!/usr/bin/perl

use warnings;
use strict;

use Data::Dumper;

my $prompt = 'name%n';     # The bad coding practice from the exercise.
my $password = 'badpass';

my $is_ok = ($password eq "goodpass");
print Dumper( $is_ok );

print "\n$prompt: Password ok? $is_ok\n";
print Dumper( $is_ok );

$is_ok = ($password eq "goodpass");
printf "\n$prompt: Password ok? %d\n" , $is_ok;
print Dumper( $is_ok );
Run Code Online (Sandbox Code Playgroud)

当我执行脚本时,输出如下:

$ ./authenticate.pl
$VAR1 = '';

name%n: Password ok?
$VAR1 = '';
Missing argument in printf at ./authenticate.pl line 19.

name: Password ok? 0
$VAR1 = 5;
Run Code Online (Sandbox Code Playgroud)

显然,$is_ok通过消耗%n$prompt其离开%d没有匹配的参数.我不希望$is_ok改变值,为什么$is_ok设置为5printf语句?

yst*_*sth 6

因为那是什么%n.

perldoc -f sprintf:

           %n    special: *stores* the number of characters output so far
                 into the next argument in the parameter list
Run Code Online (Sandbox Code Playgroud)

解决方案是:

printf "\n%s: Password ok? %d\n", $prompt, $is_ok;
Run Code Online (Sandbox Code Playgroud)

  • @jippe,那不是真的.有趣的是,在我展示之后你应该提到我展示了如何正确地做到这一点.当然,您不应该信任用户提供格式字符串(尽管它不像C中那样不安全),但格式字符串在解决方案中是硬编码的. (2认同)