home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


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

$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 not callable. In eval it returns "(eval)" .

$has_args

Whether the function was called with arguments.

$wantarray

The value the wantarray function would return for that stack frame; either true, false but defined, or else undefined (respectively). This tells you whether the function was called in list, scalar, or void context.

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.


Previous: 10.3. Creating Persistent Private Variables Perl Cookbook Next: 10.5. Passing Arrays and Hashes by Reference
10.3. Creating Persistent Private Variables Book Index 10.5. Passing Arrays and Hashes by Reference