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

I am trying to circle around what happens in this safe coding example .

I rewrote the code to better support my question:

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

When I execute the script, the output is as follows:

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

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

name: Password ok? 0
$VAR1 = 5;

It is clear that it is $is_okconsumed %nin $prompt, which leaves %dwithout a corresponding argument. I would not expect, however, that the value $is_okwill change, why is it $is_okset in 5the printf statement?

+4
source share
1 answer

Because it does %n.

perldoc -f sprintf :

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

Decision:

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

All Articles