use strict; use Scope::Guard; my $x; my $code = do { my $g; sub { my $z; $g = Scope::Guard->new( sub { warn "destroyed"; $z } ); } }; use Scalar::Util (); Scalar::Util::weaken(my $code2 = $code); $code->(); printf "code2: %d\n", !!(defined $code2); undef $code; printf "code2: %d\n", !!(defined $code2); warn "end"; #### code2: 1 code2: 1 end at x.pl line 21. destroyed at x.pl line 10 during global destruction.