I agree with LanX's explanation here, but here's something I put together that may provide a different viewpoint.

In the C-style for-loop and in its while-loop equivalent in LanX's examples here, a closure is formed (if that's the correct term) over two variables, $i and $x. The $i variable is created anew in each iteration through each loop (there's a  my $i = ...; within the scope of the loop), but the $x variable is created only once (in each example). Therefore, the closures are over three different versions of a variable named $i, each of which can have a different value, but only over a single version of a variable named $x, which has the value it ends up with at the end of each of the loops.

In the Perl-style loop example here, the for-loop iterator variable $i is successively aliased to three individual values, each of which individually has a closure formed over it and so can reflect those three values independently; you're seeing the alias of $i in each case and not the value of $i.

Or so I think...

Update: And no, the way the C-style for-loop works in Perl is not a bug; it's the way closures work.


Give a man a fish:  <%-{-{-{-<


In reply to Re^4: Closure confusion in Tkx (declarations in loops - inner vs outer) by AnomalousMonk
in thread Closure confusion in Tkx by lbrandewie

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.