So what is ScopeGuard supposed to be guarding? "$x"?

You declared $x at the global level. Is that what you are protecting? That doesn't get destroyed until the program exits...

You declared an anonymous sub inside scopeguardnew... that's also unlikely to be destroyed until your program exits -- because Scope::Guard is holding a "reference" to the interior sub (likely)... and, AT THE LEAST, the 'my $x' is declared at the global level -- so it won't be destroyed until the prog exits...

But I checked, and putting braces around the dcl of $x, doesn't change the output. So I would bet scopeguard has stored a reference to the interior sub so it can be called when "$x" goes out of scope.

But you referenced "$x" in side the sub that scope guard stored...--- so $x can't go out of scope until the interior sub (that you passed to SG->new) disappears -- and it won't disappear until your prog exits...

All you did by assigning undef to $code is lose the reference to the outside sub.. SGnew still has a reference to the inner sub and $x...

The reference to $x, that is in the anonymous sub, is referred to in jargon, as a "closure".

I'd guess that's because it creates a closed "ecosystem" that holds the anon-sub and the anon-sub's copy of $x -- no one changing '$x', after that sub is defined, will affect the value that is stored (referenced, really), in that inner sub (inside the new)...

Does that make more sense?


In reply to Re^3: Reference to guard not released by perl-diddler
in thread Reference to guard not released by roman

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.