outputsuse 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; }
foo destroying... baz
#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.
In reply to Re^5: Trying to DESTROY() an object
by kennethk
in thread SOLVED: Trying to DESTROY() a (closure-wrapped) object
by stevieb
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |