Reputation: 1392
I noticed that when creating a loop in Perl, the loop variable seem to always be local to the loop, even when when declared in the scope outside the loop. Why is this?
E.g. when running the following script. (Notice that there is no my
between foreach
and $x
!)
#!/usr/bin/perl
use strict;
use warnings;
my $x = 42;
foreach $x (0, 1) {
print "inside: $x\n";
}
print "outside: $x\n"
I would have expected the following output:
inside: 0
inside: 1
outside: 1
But instead I'm getting:
inside: 0
inside: 1
outside: 42
Is this intentional? Or is it a bug in Perl?
(Tested on Perl 5.10.1 and 5.18.2.)
Upvotes: 1
Views: 358
Reputation: 14955
Clear Explanation in the perldocs:
The foreach loop iterates over a normal list value and sets the scalar variable VAR to be each element of the list in turn. If the variable is preceded with the keyword my, then it is lexically scoped, and is therefore visible only within the loop. 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. This implicit localization occurs only in a foreach loop.
Upvotes: 11