sub mock { my $thing = shift; my $self; if (ref($thing) eq __PACKAGE__){ $self = $thing; } else { $self = bless {}, __PACKAGE__; } my $closure_self = $self; use Scalar::Util 'weaken'; weaken $closure_self; $self->{sub} = \&One::foo; *One::foo = sub { $closure_self->{x} = 'x'; return "baz\n"; }; return $self; } #### foo baz destroying... foo #### print One::foo(); { #my $count = Count->new; my $bar = Count->mock; print One::foo(); } print One::foo(); #### foo Use of uninitialized value in subroutine dereference at script.pl line 31. destroying... baz baz (in cleanup) Unable to create sub named "" at script.pl line 31.