Perl – How to get the name of the current subroutine in Perl

perl

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.

Best Answer

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)'.

Related Topic