in reply to Re: Reference to guard not released
in thread Reference to guard not released

I don't understand. Which sub I don't call? The sub which creates the guard? Of course it is called! It is stored in $code and it is called immediately after do. Your example is something very different.

The only purpose of do is to create a variable which is referenced only from the anonymous sub.

my $x; my $code = do { my $g; sub { $g = Scope::Guard->new( sub { warn "destroyed"; $x ; } ) }; }; $code->(); undef $code; warn "end";

I also don't understand the rest of your comment. The problem is not that $g references something, but that it is referenced from somewhere. But what keeps the reference to $g?

My example is the very simplification of real scenario I came across in asynchronous programming. I have two callbacks sharing a resource (handle). The resource is stored in lexical variable visible only in these two subs. First callback is called, creates the resource ($code->()) and goes out of scope. Second callback is scheduled to run. Than the process is cancelled and the second callback is cancelled from queue and goes out of scope (undef $code - here I simplified to one callback only). I expect the resource to be released then.