Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

Re: how to get a subroutine name?

by hdb (Monsignor)
on Jun 26, 2013 at 11:10 UTC ( #1040750=note: print w/replies, xml ) Need Help??

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 (Bishop) 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
    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)[]", 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 (Chaplain) 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?


        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

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1040750]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (7)
As of 2018-06-25 16:27 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (127 votes). Check out past polls.