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
In reply to Re^3: Trying to understand closures
by davido
in thread Trying to understand closures
by shine22vn
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |