http://qs321.pair.com?node_id=1219206

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

So I have this code (sub refto), it seems to work fine, but I feel like I'm missing a utility function somewhere - core modules very much preferred - that does this without me having to fall back on B. I've checked Scalar::Util and Symbol. I'm probably just having a dense moment - does anyone happen to know off the top of their head?

use warnings; use strict; use B qw/svref_2object/; sub refto { my $ref = shift; my $gv = svref_2object($ref)->GV; return $gv->STASH->NAME . '::' . $gv->NAME; } sub foo {} sub Foo::Bar::blah { } print refto(\&foo), "\n"; # prints "main::foo" print refto(\&Foo::Bar::blah), "\n"; # prints "Foo::Bar::blah" print refto(sub{}), "\n"; # prints "main::__ANON__"

Background: I am storing code references in a table and want to give each one a sensible name. For __ANON__ code refs, I'll probably append the address to make them unique.

Replies are listed 'Best First'.
Re: Name for what a coderef is pointing at
by tobyink (Canon) on Jul 25, 2018 at 00:10 UTC

    There's Sub::Util which is included in core for recent releases of Perl. (And on CPAN for older releases of Perl.) Sub::Identify has a few more features, but isn't in core.

        I've heard that perldoc is having a revamp.

        In the meantime, try perldoc.pl. Or metacpan.

        -QM
        --
        Quantum Mechanics: The dreams stuff is made of