SPUG: Finding name for sub ref

Yitzchak Scott-Thoennes sthoenna at efn.org
Tue Jul 16 00:26:53 CDT 2002


In article <20020715090535.A2113 at timji.consultix.wa.com>,
SPUG-list-owner <tim at consultix-inc.com> wrote:
>> Is there a way to extract the name of the subroutine from the reference to the subroutine?
>
>I didn't know of any easy way to do this, so I asked "The Damian", while we were
>on a break in our Adv. OO Perl class this morning.  And he says, 1) first of all,
>if it's an anonymous sub, it won't have a name, and 2) if it is named, you'd
>have to walk through the symbol tables for each of your packages looking
>for its address, to retrieve the name.

Untrue.  ( 2), not 1) )

use B ();
sub subname { eval { B::svref_2object(shift)->GV->NAME } || "" }
sub subfullname { my $gv; eval { ($gv = B::svref_2object(shift)->GV)->STASH->NAME."::".$gv->NAME } || "" }

eval's are in lieu of verifying that a coderef was passed.
Will give name "__ANON__" for anonymous subs.

 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
     POST TO: spug-list at pm.org       PROBLEMS: owner-spug-list at pm.org
      Subscriptions; Email to majordomo at pm.org:  ACTION  LIST  EMAIL
  Replace ACTION by subscribe or unsubscribe, EMAIL by your Email-address
 For daily traffic, use spug-list for LIST ;  for weekly, spug-list-digest
     Seattle Perl Users Group (SPUG) Home Page: http://seattleperl.org




More information about the spug-list mailing list