in reply to Re^2: Trying to understand closures
in thread Trying to understand closures
A new lexical gets created on each iteration. But the subroutines live in the first iteration, it appears. That's why if you call foo() after the loop, you still get 4. Remember that my has both a compiletime and a runtime effect. When foo() and bar() are defined (as part of the compilation phase), the lexical scope in which they are created is ascertained at that time, and $x clearly lives in the same scope. It's a little shocking that a loop's block works the same as a bare block, but once you accept that, the rest fits together.
Another way to think of it, and probably a more accurate way of thinking of it is that the lexical scope in which foo() and bar() are associated with $x is masked by the 2nd and 3rd iteration of the loop, when a new lexical $x of the same name is generated, thus masking previous $x's.
Dave
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: Trying to understand closures (instances)
by tye (Sage) on Nov 23, 2006 at 08:02 UTC | |
by ikegami (Patriarch) on Nov 23, 2006 at 09:15 UTC |