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

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.

Replies are listed 'Best First'.
Re^3: Identify the package a subroutine is being called from
by jettero (Monsignor) on Jun 06, 2008 at 17:47 UTC
    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

        Why yes, in fact I did try it. I got undef every time, for many variations of your code... It seems you're 100% right, but I couldn't get it to work without copying D::ST directly like this:
        sub calling_object { my @a = do { package DB; @DB::args = (); caller(2); }; $DB::args[0]; }

        It definitely doesn't work for me the way you had it.

        Oh, I got it. After much fiddling, it's the scalar context. The trick does not work when you $foo=caller(2); Must be ($foo) = caller(2); or caller() doesn't populate args. I can't tell if you changed it to @foo or if I transcribed it wrong, but my original cut and paste had $foo = caller(2).

        Also, in my previous post, I had assumed $DB::args was pure black magic. I had no idea it was documented grey magic.

        -Paul