Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

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

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?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://413799]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (4)
As of 2017-08-24 02:10 GMT
Find Nodes?
    Voting Booth?
    Who is your favorite scientist and why?

    Results (363 votes). Check out past polls.