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)
In reply to Re: Naming an anonymous sub for svref_2object
by rjt
in thread Naming an anonymous sub for svref_2object
by QM
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |