On 5/18/07, Greg London <[EMAIL PROTECTED]> wrote:
>
> >sub replace_sub_for_instance {
> >    my ($object, $subroutine_name, $new_subroutine) = @_;
> >    no strict 'refs';
> >    my $old_subroutine = \&$subroutine_name
>  >        or die "Subroutine $subroutine_name not found";
> >    my $object_name = refaddr($object);
> >    *$subroutine_name = sub {
> >        my $self = $_[0];
> >        if (refaddr($self) eq $object_name) {
> >            goto $new_subroutine;
> >        }
> >        else {
> >            goto $old_subroutine;
> >        }
> >    };
> >}
> >
> >Note that I was careful not to capture the object of interest in the
> >subroutine because I didn't want to mess up a DESTROY.
>
> I'm just a tad confused about that last bit.
> There may be advantages to using goto over recalling the method,
> but I'm not sure how shifting the object off @_ will mess up a DESTROY call.

You're looking at the wrong part of the code.  I'm referring to how I
made sure to capture refaddr before creating the anonymous sub so that
the anonymous sub did not have $object in it anywhere.  That keeps
$object from being in the closure, which means that $object won't be
kept alive by a reference from the subroutine.

There is, admittedly, a small risk that the object will be freed and
another object will wind up at the same address.  But I consider that
better than the probable problem with DESTROY.

The purpose of using goto there is in case some code uses caller() and
could get confused about the extra subroutine.  (For instance Carp
would be likely to warn at the enclosing subroutine that you defined.)

> If the original call was $inst->method2(...);
> then $inst will point to the object during the entire method2 call,
> which means if I keep a copy during the call, it shouldnt' be a problem.

During the call I don't care about.  But capturing a reference in the
subroutine that I assign would not be good.

> The reference count cant reach zero until sometime after method2
> returns and $inst gets a new value, and the instance gets garbage
> collected.
>
> Either that, or I haven't had enough caffeine today.

Additional caffeine generally helps. :-(

Cheers,
Ben
 
_______________________________________________
Boston-pm mailing list
Boston-pm@mail.pm.org
http://mail.pm.org/mailman/listinfo/boston-pm

Reply via email to