http://www.perlmonks.org?node_id=1040750


in reply to how to get a subroutine name?

For historic reasons, I would propose to define a sub called __FUNC__ that returns the name of the subroutine in which it was called, see the following example:

use strict; use warnings; sub __FUNC__ { (caller 1)[3] } sub func { print "We are now in ", __FUNC__, "\n"; } func();

UPDATE: Removed a duplicated "print".

Replies are listed 'Best First'.
Re^2: how to get a subroutine name?
by LanX (Saint) on Jun 26, 2013 at 12:04 UTC
    > For historic reasons,

    Sorry, which historic reasons?

    If you don't like caller's interface - where I sympathize - I'd rather propose something more flexible like returning a hashref:

    DB<116> sub __CALLER__ { my $level = shift; my %hash; @hash{qw/package filename line subroutine hasargs wantarray + evaltext is_require hints bitmask hinthash/} = caller($level+1); return \%hash } DB<130> sub tst { print __CALLER__->{subroutine} } DB<131> tst() main::tst
    or
    DB<136> use Data::Dump qw/dd/ DB<137> sub tst { dd __CALLER__ } DB<138> tst() { bitmask => "\0\0\0\0\0\0\0\0\0\0\0\0", evaltext => undef, filename => "(eval 108)[multi_perl5db.pl:644]", hasargs => 1, hinthash => undef, hints => 256, is_require => undef, line => 2, "package" => "main", subroutine => "main::tst", "wantarray" => 1, }
    Though not sure about using this underscore __NAMESPACE__...

    And I'm pretty sure about reinventing the wheel ...

    ... CPAN is so big and I'm so lazy ;-)

    Cheers Rolf

    ( addicted to the Perl Programming Language)

      I had to think about __LINE__ and __FILE__ etc from the good old times...

      Correction: I was thinking about good old __LINE__ and __FILE__...

Re^2: how to get a subroutine name?
by clueless newbie (Curate) on Jun 26, 2013 at 12:49 UTC

    5.16 added __SUB__ for this purpose.

    My bad! It returns a coderef.

      However, __SUB__ returns a reference to the currently running subroutine according to perlsub. Not sure how you will get its name?

        Sub::Identify?

        Still, that's rather a roundabout way to do things.

        package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name