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: 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:

$package

The package that the code was compiled in.

$filename

The name of the file the code was compiled in, reporting -e if launched from the command-line switch of the same name, or - if the script was read from STDIN.

$line

The line number that frame was called from.

$subr

The name of that frame’s function, including its package. Closures return names like main::__ANON__, which are ...

Get Perl Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.