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 refcount 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";