Otherwise, the variable is
implicitly local to the loop and regains its former value upon exiting
the loop. If the variable was previously declared with "my", it uses
that variable instead of the global one, but it’s still localized to
the loop.
If you also check the references you will see that the '$i' are pointing to different locations.
OUTPUTuse strict; use warnings; $,=","; $\="\n"; my $i = 6; sub my_print { print $i,\$i; } ; for $i (qw|x y|) { my_print(); print " (Perl Style:\$i==$i)",\$i,"\n"; }
6, SCALAR(0x8fa4e38) (Perl Style:$i==x), SCALAR(0x8f86760), 6, SCALAR(0x8fa4e38) (Perl Style:$i==y), SCALAR(0x8fa4da8),
That's why PBP says to always use lexical loop vars in foreach!
Cheers Rolf
In reply to Re^3: foreach-loop-local var in sub
by LanX
in thread foreach-loop-local var in sub
by warshall
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |