in reply to Identify the package a subroutine is being called from

Corollary, anyone have any idea how to get the calling object instance? I've always wanted that in perl. I don't think you can get it. It's called previous_object() in pike/lpc...

-Paul

  • Comment on Re: Identify the package a subroutine is being called from

Replies are listed 'Best First'.
Re^2: Identify the package a subroutine is being called from
by pc88mxer (Vicar) on Jun 06, 2008 at 17:37 UTC
    The debugger certain can get the calling arguments, even if @_ has been modified (i.e. shifted).

    Here's a solution using Devel::StackTrace:

    use Devel::StackTrace; sub calling_object { my $t = Devel::StackTrace->new; my $f; $f = $t->next_frame for (1..4); ($f->args)[0] } sub e { my $x = shift; print "x = $x\n"; d('humma'); } sub d { print "I was called by object ", calling_object(), "\n"; } e('a', 'b', 'c');
      Holy crap. That's exactly what I wanted. I should have asked years ago.

      -Paul

Re^2: Identify the package a subroutine is being called from
by chromatic (Archbishop) on Jun 06, 2008 at 17:19 UTC

    This may work, depending on what happened to @_:

    package DB; sub get_calling_object { my @foo = caller(2); return $DB::args[0] }

    Update: This needs the package declaration.

      I do not understand what $DB::args[0] is, but I suspect this is intended to return the package name of the caller, not the instance of the caller object.

      -Paul