How can I get the name of the current subroutine i

2020-02-23 05:28发布

In Perl we can get the name of the current package and current line number Using the predefined variables like __PACKAGE__ and __LINE__.

Like this I want to get the name of the current subroutine:

use strict;
use warnings;

print __PACKAGE__;
sub test()
{
    print __LINE__;
}
&test();

In the above code I want to get the name of the subroutine inside the function test.

标签: perl
3条回答
劫难
2楼-- · 2020-02-23 06:03

There special __SUB__ exists from perl-5.16.

use v5.16;
use Sub::Identify qw/sub_fullname/;
sub foo {
    print sub_fullname( __SUB__ );  # main::foo
}

foo();

Actually you can pass to sub_fullname any subroutine reference (even anonymous):

use Sub::Identify qw/sub_fullname/;
sub foo {
    print sub_fullname( \&foo );  # main::foo
    print sub_fullname( sub{} );  # main::__ANON__
}

foo();
查看更多
贪生不怕死
3楼-- · 2020-02-23 06:04

caller is the right way to do at @eugene pointed out if you want to do this inside the subroutine.

If you want another piece of your program to be able to identify the package and name information for a coderef, use Sub::Identify.

Incidentally, looking at

sub test()
{
    print __LINE__;
}
&test();

there are a few important points to mention: First, don't use prototypes unless you are trying to mimic builtins. Second, don't use & when invoking a subroutine unless you specifically need the effects it provides.

Therefore, that snippet is better written as:

sub test
{
    print __LINE__;
}
test();
查看更多
够拽才男人
4楼-- · 2020-02-23 06:14

Use the caller() function:

my $sub_name = (caller(0))[3];

This will give you the name of the current subroutine, including its package (e.g. 'main::test'). Closures return names like 'main::__ANON__'and in eval it will be '(eval)'.

查看更多
登录 后发表回答