You never used the word "closure", which makes me think you may not actually get what is happening. In most cases, a lexical is freed (and the reference count decremented if the lexical is a hard ref) at the end of a function call:
But since your new One::foo sub is created inside that lexical scope, it prevents $self from being freed (because the created sub "closes" over it, which means it is a closure that keeps the lexical alive for its own use).sub mock { my $self = shift; # ref count of the object +1 # code here } # $self goes out of scope, ref count of the object -1
So this is the reference that you want to weaken, just add weaken $self; just before *One::foo = sub { $self->{x} = 'x'; return "baz\n"; }; and you will get the expected result.sub mock { my $self = shift; # ref count ++ return sub { $self->{Thing}; }; # $self is still held by the sub, so it is not freed }
In reply to Re: Trying to DESTROY() an object
by Eily
in thread SOLVED: Trying to DESTROY() a (closure-wrapped) object
by stevieb
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |