Hey Monks,
I've read up on Scalar::Util::weaken(), but I can't figure out what exactly I need to do so that my object is DESTROY()ed before END. The output should read foo, baz, foo, but because the object isn't being destroyed before END, I'm getting foo, baz, baz.
I know the problem is with this statement: *One::foo = sub { $self->{x} = 'x'; return "baz\n"; };, because I'm creating a reference to $self within the reference, increasing the REFCNT. Could someone please let me know if weaken() can help here (and how to implement it), or if there's a better way to do this?
Here's my test script:
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();
...and a simplified example module (well two, included inside of a single file):
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 { $self->{x} = 'x'; return "baz\n"; }; return $self; } sub DESTROY { my $self = shift; print "destroying...\n"; $self->unmock; } 1;
I thought about using copies of the $self variables instead of directly within the sub re-def, but I don't think I can, as the real code is more like this:
my $count; *$sub = sub { @{ $self->{called_with} } = @_; $self->{called_count} = ++$called; if ($self->{side_effect}) { if (wantarray){ my @effect = $self->{side_effect}->(@_); return @effect if @effect; } else { my $effect = $self->{side_effect}->(@_); return $effect if defined $effect; } } return undef if ! $self->{return}; return ! wantarray && @{ $self->{return} } == 1 ? $self->{return}[0] : @{ $self->{return} }; };
In reply to SOLVED: Trying to DESTROY() a (closure-wrapped) object by stevieb
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |