How can I get the name of the current subroutine in Perl?

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();

I was just looking for an answer to this question as well, I found caller as well, but I was not interested in the fully qualified path, simply the literal current package name of the sub, so I used:

my $current_sub = (split(/::/,(caller(0))[3]))[-1];

Seems to work perfectly, just adding it in for if anyone else trips over this questions :)


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

Tags:

Perl