In case my other reply didn't make it clear.

The first case half-way works. On each pass through the loop you get an alias to a different element of the list. Therefore the different iterations are different variables, but they are still the same as what is in the list so this is dangerous.

The second case simply breaks since you create one variable and modify it during the loop. Think of closures as working by reference and you see the issue - you get a bunch of references to the same variable so all of them point at the same value in the end. (The last value during the loop.)

The third case works because inside the loop you explicitly create a new variable which is completely private to that iteration of the loop. This not only means that your attempted closures are different for each iteration, it means that there is nothing still out there which can mess with your private closure by reference.

Make sense?


In reply to RE (tilly) 3 (closures): for loops by tilly
in thread for loops, closures by Aighearach

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.