in reply to How can I find the calling object?

You can find out who is calling you via caller but that only gives you the function, that is, method name. The problem is that the object reference is stored somewhere in that sub's lexicals.. you might be able to find it using PadWalker, but I doubt that such a solution can be generalized.

Makeshifts last the longest.

Replies are listed 'Best First'.
Re: Re: How can I find the calling object?
by strider corinth (Friar) on Nov 18, 2002 at 17:57 UTC
    Perfect. Here's some proof of concept code:
    #!/usr/bin/perl package Caller; sub new { bless {}, 'Caller' } sub call { my( $self, $one ) = @_; $one->output; } sub output { "I am the Caller\n" } 1; package Called; use PadWalker 'peek_my'; sub new { bless {}, 'Called' } sub output { my $caller = peek_my( 1 )->{ '$self' }; #$h->{ '$self' }; print STDOUT $$caller->output(); } 1; package main; my $one = new Caller; my $two = new Called; $one->call( $two );
    This prints:
    I am the Caller.
    --
    Love justice; desire mercy.
      Perfect, so long as it is indeed called $self.. :)

      Makeshifts last the longest.

        Hehe. Fair 'enough. But that can be ascertained without even looking at the original code, so I don't worry about it. ;) You're right, though, in that it can't be 100% generalized. I'd say this is still a Right Way To Do It.
        --
        Love justice; desire mercy.
Re: Re: How can I find the calling object?
by John M. Dlugosz (Monsignor) on Nov 18, 2002 at 20:03 UTC
    I'm surprised that something like PadWalker is possible. I figured that the compiler would not retain the names at all at run-time.