簡體   English   中英

為什么Perl`printf`改變了我的$變量的值?

[英]Why does Perl `printf` change the value of my $variable?

我試圖圍繞這個安全編碼示例中發生的事情。

我重寫了代碼以更好地支持我的問題:

#!/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 );

當我執行腳本時,輸出如下:

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

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

name: Password ok? 0
$VAR1 = 5;

很明顯, $is_ok$prompt%n消耗,這使得%d沒有匹配的參數。 但是我不希望$is_ok更改值,為什么$is_ok被printf語句設置為5

因為這就是%n作用。

perldoc -f sprintf

  %n special: *stores* the number of characters output so far into the next argument in the parameter list 

解決方案是:

printf "\n%s: Password ok? %d\n", $prompt, $is_ok;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM