No, no optimization was involved. Don't confuse my $x with undef $x. my $x does NOT change the value of $x. Aside from returning $x's value, all my $x does is set a flag to clear $x at the end of the current scope (i.e. at the end of the loop pass).

Can you guess what the following snippet prints?

for (1..4) { my $x; print ++$x; } print "\n"; for (1..4) { goto SKIP if $_ == 2; my $y; SKIP: print ++$y; } print "\n"; for (1..4) { my $z if $_ != 2; print ++$z; }

At the end of every pass of the first loop, $x gets cleared, so the output of that loop is 1111.

At the end of every pass *except the second* of the second loop, $y gets cleared, so the output of that loop is 1121.

The third loop is identical to the second one. It also outputs 1121.

Updated: Reworded for clarity. No new content.
Updated: Added code.


In reply to Re^2: Trying to understand closures by ikegami
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.