bronson has asked for the wisdom of the Perl Monks concerning the following question:

Is there any reasonable code that, given a reference to a subroutine (\&func), will produce its name ("func" or "package::func")? Behavior with closures doesn't matter to me.

why do I want this?

My RPC::XML module has a dispatch table of methods and their associated signatures:

RPC::XML::LoadModPod::register_methods({ \&identity => ['string'] \&listMethods => ['array', 'array string'], ... etc.);
I'd like to have the server know the name of the function without requiring a separate lookup table. Is there any reasonably easy way of doing this?

Thanks!

Replies are listed 'Best First'.
Re: Good way of getting subroutine name from ref?
by diotalevi (Canon) on Dec 05, 2003 at 18:48 UTC

    Trickery.

    use B; sub cv2name { # Updated to use scalar eval { ... } to trap errors and still use +the proper context return scalar eval { my $obj = B::svref_2object( shift ); my $package = $obj->STASH->NAME; '&' . ( $package eq 'main' ? '' : "${package}::" ) . $obj->GV- +>NAME; } }
      When using B this way, I like to guard against bad input. For instance, if you pass an array ref, with the above you'll croak with: Can't locate object method "STASH" via package "B::AV". Rather than check with ref or reftype or can or check what type of object svref_2object returns, I just wrap it in an eval and return undef if something goes wrong:
      use B; sub cv2name { eval { my $obj = B::svref_2object( shift() ); $obj->STASH->NAME . "::" . $obj->GV->NAME; } || undef; }
        Oh that's a good point. I like it. One clarification though - eval returns undef when it fails so your `|| undef` is pure obfuscation. You disguise that eval already has the || undef behaviour automatically.
Re: Good way of getting subroutine name from ref?
by CombatSquirrel (Hermit) on Dec 05, 2003 at 21:14 UTC
      But I want to get the name of the ref without actually calling it. Caller only works if the function you're inquiring about is in the stack frame somewhere.

      diotalevi's technique looks like it will work, but wow, that's some deep magic. :)

        Oops, seems that I haven't read the important part of the question. Sorry.
        CombatSquirrel.
        Entropy is the tendency of everything going to hell.
Re: Good way of getting subroutine name from ref?
by bronson (Initiate) on Dec 05, 2003 at 18:42 UTC
    Sorry folks. I'm not quite sure how I managed to post that anonymously.