[OT] What's my name?
Paul LeoNerd Evans
leonerd at leonerd.org.uk
Tue Oct 7 18:52:57 BST 2008
On Tue, 7 Oct 2008 17:27:37 +0100
Nicholas Clark <nick at ccl4.org> wrote:
> In this code:
>
> *beer = *buffy = *pie = *kittens = sub {
> ...
> };
>
> is there an easy way for the subroutine to know what name it was called as.
> If it makes it easier, the subroutine is actually going to be a method.
Looking at
http://search.cpan.org/perldoc?Sub::Identify
It has sub_name() though I suspect that will give __ANON__ here.
Perhaps you could hunt it down.
package Some::Pkg;
*foo = *bar = *splot = sub { 'wibble' };
package main;
use Sub::Identify qw( stash_name );
my $coderef = \&Some::Pkg::foo;
my @names;
{
no strict 'refs';
my $pkg = stash_name( $coderef );
@names = map { $pkg."::$_" }
grep { $coderef == \&{$pkg."::$_"} }
keys %{$pkg."::"};
}
print "The sub is called: " . join( " ", @names ) . "\n";
Gives
The sub is called: Some::Pkg::bar Some::Pkg::foo Some::Pkg::splot
> caller gives __ANON__, because, after all, that was the name the subroutine
> had when it was compiled.
If you want to set one, see
http://search.cpan.org/perldoc?Sub::Name
--
Paul "LeoNerd" Evans
leonerd at leonerd.org.uk
ICQ# 4135350 | Registered Linux# 179460
http://www.leonerd.org.uk/
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 189 bytes
Desc: not available
Url : http://london.pm.org/pipermail/london.pm/attachments/20081007/1c6630f8/signature.pgp
More information about the london.pm
mailing list