If I told you, I would be the one earning the grade on your quiz, not you. ;)
Oh what the heck, who can resist?
$x exists within a lexical scope accessible by the subroutines foo() and bar(). When foo() is called, it pre-increments $x (so it becomes 1) and prints that.
Next, bar() is called on the same $x, pre-incrementing it and printing 2.
Next, the loop begins. Ignore the subroutine declarations for now, they've already taken place. We've now entered the lexical scope in which foo() and bar() already pre-incremented $x when we called them earlier. On the first iteration of the loop we'll pre-increment it again, and print 3. That's probably the most counterintuitive step.
Now, the loop iterates for the second time. This time we get a new lexical $x; one that hasn't been pre-incremented. And thus, 1 gets printed.
Then we iterate one more time, and get a new lexical $x again, and thus 1 gets printed.
What's cool is that the first lexical $x, the one that foo() and bar() incremented, and that got incremented on the first iteration of the loop still exists. If you call foo() after the loop, you'll get 4, indicating that foo() is still aware of and acting on the first lexical $x
As the title of your post indicates, you're playing with closures here. I know closures are discussed in the Camel book. Probably the best discussion of closures in the POD is contained in perlref, I think I recall that the first time through it I found the Camel book's discussion clearer.
Dave
In reply to Re: Trying to understand closures
by davido
in thread Trying to understand closures
by shine22vn
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |