in reply to Trying to understand closures
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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Trying to understand closures
by crashtest (Curate) on Nov 23, 2006 at 06:52 UTC | |
by davido (Cardinal) on Nov 23, 2006 at 07:13 UTC | |
by tye (Sage) on Nov 23, 2006 at 08:02 UTC | |
by ikegami (Patriarch) on Nov 23, 2006 at 09:15 UTC |