in reply to Re^2: Tricky scope problem
in thread Tricky scope problem
Why does it become "implicitly local to the loop", hiding the global var's value?Consider the following code:
In the for loop in the subroutine, a temporary list is generated and $scalar is aliased to each element of the list in turn. Then the subroutine exits. What happens to the temporary list upon exit from the subroutine (or probably upon exit from the loop, actually)? To what element of the list should $scalar remain aliased after exit from the subroutine (or the loop)? The answer to this question seems to be 'None', since the list no longer exists. Hence, implicit loop locality.>perl -wMstrict -le "my $scalar = 42; print qq{scalar before subroutine: $scalar}; S(); print qq{scalar after subroutine: $scalar}; sub S { for $scalar (1 .. 3) { print qq{scalar in subroutine for-loop: $scalar}; } } " scalar before subroutine: 42 scalar in subroutine for-loop: 1 scalar in subroutine for-loop: 2 scalar in subroutine for-loop: 3 scalar after subroutine: 42
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: Tricky scope problem
by lostjimmy (Chaplain) on Apr 11, 2009 at 15:42 UTC |