Determining Current Function Name

Problem

You want to determine the name of the currently running function. This is useful for creating error messages that don't need to be changed if you copy and paste the subroutine code.

Solution

Use the caller function:

$this_function = (caller(0))[3];

Discussion

Code can always find the current line number in the special symbol __LINE__ , the current file in __FILE__ , and the current package in __PACKAGE__ . But there's no such symbol for the current subroutine name, let alone the name of the one that called this subroutine.

The built-in function caller handles all of these. In scalar context it returns the calling function's package name. But in list context, it returns a wealth of information. You can also pass it a number indicating how many frames (nested subroutine calls) back you'd like information about: 0 is your own function, 1 is your caller, and so on.

Here's the full syntax, where $i is how far back you're interested in:

($package, $filename, $line, $subr, $has_args, $wantarray )= caller($i); # 0 1 2 3 4 5

Here's what each of those return values means:

Rather than using caller directly as in the solution, you might want to write functions instead:

$me = whoami(); $him = whowasi(); sub whoami {
 (caller(1))[3]
}
sub whowasi {
 (caller(2))[3] }

These use arguments 1 and 2 for parent and grandparent functions because the call to whoami or whowasi would be number 0.

See Also

The wantarray and caller functions in of Perl Developing and in perlfunc (1);