Hack 58. Find a Subroutine s Source


Hack 58. Find a Subroutine's Source

Find out where subroutines come from.

There are few things more annoying than finding a misbehaving subroutine and not being able to figure out where it came from. Some modules export subroutines automatically. Sometimes someone will have imported absolutely everything by using the :all tag in the use line.

Whatever the cause, the first step in fixing an errant subroutine is locating it.

The Hack

You could muck around in your symbol table [Hack #72] and use introspection to find the CV and check its STASH information [Hack #78], but Rafael Garcia-Suarez's Sub::Identify does this for you (using the invaluable B backend module internally).

The B module is uncommon, but very handy when necessary. It effectively allows you to explore Perl's inner workings. In this example, svref_2object( ) takes a code reference and returns an object blessed into the B::CV class. You won't actually find this class declared anywhere, but it's part of the B module internally.


Running the Hack

Just use the stash_name( ) function:

package My::Package; use Sub::Identify ':all'; use HTML::Entities 'encode_entities'; print stash_name( \\&encode_entities );

Run this code; it will print HTML::Entities. Even if another module has re-exported &encode_entities into your namespace, Sub::Identify will still report HTML::Entities as the source of the subroutine.

For descriptions of the class hierarchy of these objects and the methods that you can call on them, see OVERVIEW OF CLASSES and SV-RELATED CLASSES in perldoc B. Unfortunately, much of the documentation is rather sparse and reading the source code of this module and the header files of the various Perl data structures, as well as pestering P5P with questions, is often the best way to figure out what you're doing. See also Chapter 8.



Perl Hacks
Perl Hacks: Tips & Tools for Programming, Debugging, and Surviving
ISBN: 0596526741
EAN: 2147483647
Year: 2004
Pages: 141

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net