Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
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
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?
      You call coderef2name from XS, that is how you do it
      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);

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 avoiding work at the Monastery: (8)
As of 2014-10-23 01:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (123 votes), past polls