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 much more. 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
# 0 1 2 3 4 5
$evaltext, $is_require, $hints, $bitmask
# 6 7 8 9
)= caller($i);
Here's what each of those return values means:
- $package
-
The package in which the code was compiled.
- $filename
-
The name of the file in which the code was compiled, reporting
-e if launched from that command-line switch, or
- if the script was read from standard input.
- $line
-
The line number from which that frame was called.
- $subr
-
The name of that frame's function, including its package. Closures
are indicated by names like main::_ _ANON_ _,
which are not callable. In an eval, it contains
(eval).
- $has_args
-
Whether the function had its own @_ variable set
up. It may be that there are no arguments, even if true. The only way
for this to be false is if the function was called using the
&fn notation instead of fn(
) or &fn( ).
- $wantarray
-
The value the wantarray function would return for
that stack frame; either true, false but defined, or else undefined.
This tells whether the function was called in list, scalar, or void
context (respectively).
- $evaltext
-
The text of the current eval
STRING, if any.
- $is_require
-
Whether the code is currently being loaded by a
do, require, or
use.
- $hints, $bitmask
-
These both contain pragmatic hints that the caller was compiled with.
Consider them to be for internal use only by Perl itself.