Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

Re: Which module contains an imported subroutine

by john.deighan (Novice)
on Mar 26, 2013 at 20:32 UTC ( #1025581=note: print w/replies, xml ) Need Help??

in reply to Which module contains an imported subroutine

Thanks to ysth and his response to the question "How to de-reference a coderef? (B tricks)", I came up with the following function:

sub SourcePackage { my($funcname, $package) = @_; $package = caller() if !$package; return if ! $package->can($funcname); my $coderef; { no strict 'refs'; $coderef = \&{"$package\:\:$funcname"}; } return B::svref_2object($coderef)->GV->STASH->NAME; } # SourcePackage()

So, in the situation I described, where a script imports from multiple Perl modules, e.g. "use X; use Y; use Z;", and you want to know which module a function $funcname was imported from, you call find out with:

my $srcPkg = SourcePackage($funcname, __PACKAGE__);

which will return the name of the package that $funcname was imported from (and into package __PACKAGE__ - i.e. the current package), or undef if no function by that name is in the symbol table of package __PACKAGE__ (which in the case of a script without a package declaration, will be 'main').

FYI, the { and } around "no strict 'refs';" was to restrict the "no strict" to the smallest code possible. The function SourcePackage() can be put into an external library of utilities, which is why I created it so that the package name must be passed in - however, by default, if you don't pass in a package name, it will use the package that the SourcePackage() subroutine was called from, which I'm sure would be the most common use case. So, the above call can be abbreviated to:

my $srcPkg = SourcePackage($funcname);

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1025581]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (8)
As of 2017-10-20 21:03 GMT
Find Nodes?
    Voting Booth?
    My fridge is mostly full of:

    Results (267 votes). Check out past polls.