Or perhaps the "create a new instance" actually happens when the scope is left rather than when it is re-entered.

That's what a monk told me. He even told me the name of the macro, but it escapes me. Unfortunately, I lost the notes I took.

( Update: I did some digging in the Perl sources. Opcode pp_padsv (called to fetch an SV from the pad) adds a SAVEt_CLEARSV "directive" on the stack (if I understand correctly). When the scope is exited, leave_scope is called. When leave_scope encounters the SAVEt_CLEARSV "directive", it either reinitializes the SV (using SvOK_off) or it creates a new SV to replace the still-referenced one on the pad. Similar events occur for AVs and HVs. )

The following snippet demonstrates it's the refcount at end of the loop that matters, thus demonstrating the initialization happens at the end of the loop:

my @a; for my $i (1..8) { foreach ('once') { my $x; push @a, \$x if $i >= 4; print(\$x, "\n"); } pop @a if $i >= 7; }

Output:

SCALAR(0x226024) SCALAR(0x226024) SCALAR(0x226024) SCALAR(0x226024) SCALAR(0x2252e0) SCALAR(0x2252f8) SCALAR(0x225334) <-- different SCALAR(0x22513c) <-- different

If it was the ref count on entering the loop that mattered, the output would be:

SCALAR(0x226024) SCALAR(0x226024) SCALAR(0x226024) SCALAR(0x226024) SCALAR(0x2252e0) SCALAR(0x2252f8) SCALAR(0x2252f8) <-- same as prev SCALAR(0x2252f8) <-- same as prev

Unfortunately, PadWalker can't examine the loop's pad from outside of the loop (although it can examine a sub's pad from outside the sub).


In reply to Re^5: Trying to understand closures (instances) 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.