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

Re: How to de-reference a coderef? (B tricks)

by ysth (Canon)
on Dec 10, 2004 at 10:35 UTC ( #413799=note: print w/ replies, xml ) Need Help??


in reply to How to de-reference a coderef?

Unlike e.g. array refs, every code ref has a backreference to its glob (so that when you call it, caller can know the sub name). This is fairly easily accessible with the B module (which provides introspection facilities for perl thingies):

use B; sub coderef2name { eval { my $obj = B::svref_2object( shift() ); $obj->GV->STASH->NAME . "::" . $obj->GV->NAME; } || undef; }
Returns something like pkgname::__ANON__ for anonymous subs, or undef if something goes wrong (like being passed an array ref instead of a code ref).

Updated to use GV->STASH->NAME, not STASH->NAME. Thanks, betterworld


Comment on Re: How to de-reference a coderef? (B tricks)
Download Code
Replies are listed 'Best First'.
Re^2: How to de-reference a coderef? (B tricks)
by Anonymous Monk on Aug 24, 2011 at 01:14 UTC
    How do you do this in XS? Given a CV how do you get the name for the corresponding named sub?
      use strict; use warnings; use feature qw( say ); use Inline C => <<'__EOI__'; SV* coderef2name(CV* cv) { const GV * const gv = CvGV(cv); const HV * const stash = GvSTASH(gv); const char * const pkg_name = HvNAME(stash); const char * const func_name = GvNAME(gv); SV * const fqn = newSVpvn("", 0); sv_catpv(fqn, pkg_name); sv_catpv(fqn, "::"); sv_catpv(fqn, func_name); return fqn; // Mortalised by Inline } __EOI__ sub f {} say coderef2name(\&f);
      You call coderef2name from XS, that is how you do it

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (10)
As of 2015-07-28 09:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (254 votes), past polls