in reply to Re^4: Trying to DESTROY() an object
in thread SOLVED: Trying to DESTROY() a (closure-wrapped) object

I don't think that does what you want. The reference will never be weakened if you never call sub.
use warnings; no warnings 'redefine'; use strict; use lib '.'; #use Count; print One::foo(); { my $count = Count->new; my $bar = $count->mock; #print One::foo(); } print One::foo(); BEGIN{ package One; sub foo { return "foo\n"; } 1; package Count; sub new { return bless {}, shift; } sub unmock { my $self = shift; *One::foo = \&{ $self->{sub} }; } sub mock { my $thing = shift; my $self; if (ref($thing) eq __PACKAGE__){ $self = $thing; } else { $self = bless {}, __PACKAGE__; } $self->{sub} = \&One::foo; *One::foo = sub { use Scalar::Util 'weaken'; weaken $self; $self->{x} = 'x'; return "baz\n"; }; return $self; } sub DESTROY { my $self = shift; print "destroying...\n"; $self->unmock; } 1; }
outputs
foo destroying... baz

#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

Replies are listed 'Best First'.
Re^6: Trying to DESTROY() an object
by stevieb (Canon) on Dec 08, 2015 at 20:57 UTC

    That's good... and it's for certain what I don't want. Having a sub doing random stuff after one thinks the object is out of scope could lead to spectacularly hard to find bugs ;)