From perldoc perlsyn on the topic of Foreach Loops:
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.
But consider this example:
use Devel::Peek;
my $x = 1;
Dump $x;
for $x ( 1 ) { Dump $x }
SV = IV(0x8117990) at 0x8100bd4
REFCNT = 1
FLAGS = (PADBUSY,PADMY,IOK,pIOK)
IV = 1
SV = IV(0x8117988) at 0x8100bf8
REFCNT = 2
FLAGS = (IOK,READONLY,pIOK)
IV = 1
It seems like these are not the same variables. Is it an error in docs, or am I missing anything?
Every rule needs its exception, and this is one. In a for loop, if the loop variable is a lexical (declared with
my), Perl will create a new lexical aliased to the current item in the loop. The OP code could be written as follows:Edit: previous example was in Perl pseudocode, answer revised for clarity.