in reply to "for" surprise
The difference is that the left program declares a my variable, while the right program declares an our variable.#!/usr/local/bin/perl -w #!/usr/local/bin/perl -w use strict; use strict; my $i = 45; our $i = 45; for $i (0..67) { for $i (0..67) { last if $i == 10; last if $i == 10; investigate(); investigate(); } } print $i."\n"; print $i."\n"; sub investigate { sub investigate { print "\$i=$i\n"; print "\$i=$i\n"; } }
Note that inside the for loop, the value of the top level my $i variable is not affected, while the global our $i variable gets temporarily affected. An interesting observation is made: Perl localizes the $i variable differently inside the for loop, depending on how $i is declared in the first place.45 0 45 1 45 2 45 3 45 4 45 5 45 6 45 7 45 8 45 9 $i=45 $i=45
When the top level $i variable is declared as an our variable, the for loop is equivalent to -my $i = 45; for (0..67) { my $i = $_; ... }
our $i = 45; for (0..67) { local $i = $_; ...
|
|---|