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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.