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.
$this_function = (caller(0));
Code can always find the current line number in the special symbol
, 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
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:
The package that the code was compiled in.
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.
The line number that frame was called from.
The name of that frame’s function, including its package.
Closures return names like
main::__ANON__, which are ...