In your example, here is what happens:

$g is never released until global destruction. So the Scope::Guard object is never called until that time. This is one problem in your code.

The difference between when you put $x or not is that in the first case it is a closure that keeps a reference to $x while in the second case this is just a bare anonymous sub. In the second case there is no circular reference.

You should also try to call $code->() multiple times to see when the Scope::Guard object is destroyed (because the content of $g is replaced).

You can explore more what happens to references by using Devel::Refcount:

use strict; use Scope::Guard; use Devel::Refcount 'refcount'; sub showcount ($\$) { printf "line %d: \$%s => %d\n", (caller)[2], $_[0], refcount($_[1] +)-1; } my $x; showcount(x => $x); my $code = do { my $g; showcount(g => $g); # By creating a closure that reference $g, we increase its refcoun +t to 2 sub { # Here the only reference to $g is the closure showcount(g => $g); $g = Scope::Guard->new( sub { warn "destroyed"; $x; } ); } # Here $g is out of scope, so refcount of $g decreases to 1 }; showcount(x => $x); $code->(); showcount(x => $x); #$code->(); showcount(x => $x); undef $code; # Here, I expect the refcount of $x to decrease, but it doesn't showcount(x => $x); warn "end";

In reply to Re: Reference to guard not released by dolmen
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.