in reply to Re: Tricky scope problem
in thread Tricky scope problem

Wow! Learn something new every day. I'm glad I've never run into this. It would have driven me nuts.

So with that being said, do you have any idea why this is implemented in such a way? Why does it become "implicitly local to the loop", hiding the global var's value? This is completely unexpected (at least to me), and doesn't really seem like the logical thing.

Replies are listed 'Best First'.
Re^3: Tricky scope problem
by AnomalousMonk (Archbishop) on Apr 11, 2009 at 00:33 UTC
    Why does it become "implicitly local to the loop", hiding the global var's value?
    Consider the following code:
    >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
    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.
      Ah I see. That makes total sense. Thanks for the enlightenment!
Re^3: Tricky scope problem
by kennethk (Abbot) on Apr 11, 2009 at 13:19 UTC
    It's done this way to allow for the following magic:

    > perl -e '@arr = (1,2,3);$_++ foreach @arr;print @arr,"\n"' 234

    By aliasing the loop variable, we gain the power to use foreach (and grep and map...) to create simple list operations without dealing with index syntax.

      Thanks, kennethk. I understand very well the aliasing provided by the loop variable. I just hadn't understood why it became implicitly localized to the loop. AnomalousMonk explained it perfectly, though.