Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: Which module contains an imported subroutine

by john.deighan (Novice)
on Mar 26, 2013 at 20:32 UTC ( [id://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?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1025581]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (3)
As of 2024-04-25 05:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found