sub mock { my $self = shift; # ref count of the object +1 # code here } # $self goes out of scope, ref count of the object -1 #### sub mock { my $self = shift; # ref count ++ return sub { $self->{Thing}; }; # $self is still held by the sub, so it is not freed }