Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Is there a way to tell what package foo() is in? I'm coding in an environment where there are two packages at the top, both with foo. But one could be uncommented to use it or not to use the original.
import sourcea;
# uncomment to use soureb's foo
# import sourceb;
Is there a function to get the package name of the foo that is refered to? They have slightly (ever so slight) different behavior and I need to adjust for it.

Replies are listed 'Best First'.
Re: What package is foo() from?
by shmem (Chancellor) on Jun 25, 2007 at 18:53 UTC
Re: What package is foo() from?
by ferreira (Chaplain) on Jun 25, 2007 at 20:16 UTC

    Maybe Sub::Identify can help too.

    use Sub::Identify 'stash_name'; my $package = stash_name( $some_coderef );
Re: What package is foo() from?
by jdporter (Paladin) on Jun 25, 2007 at 18:05 UTC

    Assuming you're using Exporter or something like that, then the fact is that foo is in the current namespace, the one it was imported into. If you want to know where it came from, you'd probably have to dink with the import function to record the import action somehow.

    Another possibility (not necessarily recommended) is to add a "secret" protocol to the foo function whereby it returns its native package e.g. when passed a certain argument:

    sub foo { $_[-1] eq '__WHENCE__' and return __PACKAGE__; . . . . }

    A word spoken in Mind will reach its own level, in the objective world, by its own weight

      caller knows the package name (show below) at run-time. Is there a way (B:: modules?) to extract it without calling the function?

Re: What package is foo() from?
by Ovid (Cardinal) on Jun 26, 2007 at 13:01 UTC

    Frankly, I get tired of always trying to figure out stuff about subroutines (what's their name, if anonymous? What's their code? What package are they from? etc.). So I bundled all of that up in Sub::Information:

    use Sub::Information; print inspect(\&coderef)->package;

    Cheers,
    Ovid

    New address of my CGI Course.

Re: What package is foo() from?
by Jenda (Abbot) on Jun 26, 2007 at 09:39 UTC