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

Replies are listed 'Best First'.
Re: Subroutine names internally
by dws (Chancellor) on Aug 30, 2002 at 04:09 UTC
    Can a subroutine know its own name?

    It can get its name by using one of the forms of caller(). Try this:

    foo(); sub foo { my @callinfo = caller(0); print "i am $callinfo[3]\n"; }
    Details in perlfunc.

Re: Subroutine names internally
by chromatic (Archbishop) on Aug 30, 2002 at 20:31 UTC

    Not reliably. Here's code that breaks dws' example. I've never had the need for the feature you describe, however. (I could also walk the symbol tables until I found the right CV, but that's even worse. :)

    my $sub; BEGIN { $sub = sub { my ($called) = (caller(0))[3]; warn "Called as <$called>\n"; }; *{ bar } = $sub; } my $b = \&bar; $sub->(); *{ foo } = $sub; foo(); bar(); $b->(); *{ baz } = $b; baz();