Keep It Simple, Stupid | |
PerlMonks |
(Ovid) Scoping in for loopsby Ovid (Cardinal) |
on Aug 20, 2000 at 18:34 UTC ( [id://28727]=note: print w/replies, xml ) | Need Help?? |
Consider the for loop in the following form:
In this case, $i is not being assigned the values 1 through 8. Instead, it becomes an alias to the values being iterated over. That's why so many Perl newbies use a construction like this to iterate over an array and then wonder why their array changed at the end. As for the scoping issue, page 100 of Programming Perl states that the variable immediately after the for|foreach in these loops (or $_ if not specified) is implicitly local to the loop and will regain its former value after exiting the loop. Now look at the following snippet: Because $i is actually an alias to the variables being iterated over, the second $i in \$i == $i is pointing to the memory location where the appropriate value in the for loop is being stored. If the value at that memory location could be changed, your anonymous subroutine would print a different value. This is weird, but it works: The above will print: $i == 10 $i == 20 The C-style for ($i; $i<=8; $i++) {} does not have this benefit. Here, you've changed the value of $i, period. Unless you've exited early or done something funky with $i's value, it will be equal to 9 at the end of this loop. Consider the following snippet: There is no "implicit alias" here, so the second $i simply points to $i. Hope this helps.
Cheers, Update: While I got the point across, I have to say that this is one of the most poorly written posts I have done. Ugh. No more posting before coffee!!!
In Section
Seekers of Perl Wisdom
|
|