Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: how to get a subroutine name?

by hdb (Prior)
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".


Comment on Re: how to get a subroutine name?
Select or Download Code
Re^2: how to get a subroutine name?
by LanX (Canon) 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 (Hermit) 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

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1040750]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (6)
As of 2014-12-25 14:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (160 votes), past polls