Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

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

by ysth (Canon)
on Dec 10, 2004 at 10:35 UTC ( [id://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?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (6)
As of 2024-04-23 21:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found