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).
Tip
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 ...