in reply to Naming an anonymous sub for svref_2object

Good question. If I understand your requirement correctly, you want to be able to name a CODE ref such that you can retrieve its name from outside the sub by reference (and possibly inside the sub as well or via Carp/caller?), but you do not appear to want to install the sub into the package's namespace. Is that about right?

First, local *__ANON__ is just that... local. It only affects the enclosing block (i.e., the sub body in its current execution), and reverts as soon as it goes out of scope when the sub exits. And of course modifying global *__ANON__ (i.e., without local) is not what you want, either.

Fortunately, there's an easy way around all of this:

use 5.012; use Sub::Name 'subname'; use B; sub get_sub_name { B::svref_2object(shift)->GV->NAME } my $ref = sub { say 'Our name is: ' . (caller(0))[3] }; $ref->(); say 'Before subname: ' . get_sub_name($ref); subname 'the_pad_test', $ref; $ref->(); say 'After subname: ' . get_sub_name($ref); print "the_pad_test(): "; eval { the_pad_test() }; print $@ =~ /^Undefined sub/ ? "fails (correct)\n" : "ERROR: $@";

Output:

Our name is: main::__ANON__ Before subname: __ANON__ Our name is: main::the_pad_test After subname: the_pad_test the_pad_test(): fails (correct)
use strict; use warnings; omitted for brevity.

Replies are listed 'Best First'.
Re^2: Naming an anonymous sub for svref_2object
by QM (Parson) on Aug 07, 2013 at 10:02 UTC
    First, local *__ANON__ is just that... local. It only affects the enclosing block (i.e., the sub body in its current execution), and reverts as soon as it goes out of scope when the sub exits.
    Yes, of course. Somehow the local aspect didn't register in my head.

    I had seen the Sub::Name, but there's a lot of resistance to install another module on multiple systems. It will be a debate about whether __ANON__ is easier to take than adding an XS module to the installation distribution.

    Since we do control the grumble code, another option is to pass in an optional name to use in case the coderef is an anonymous sub.

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