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
.
There special
__SUB__
exists fromperl-5.16
.Actually you can pass to
sub_fullname
any subroutine reference (even anonymous):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
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:
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)'
.