caller#
Return information about the subroutine, eval, or require that
called the currently executing code.
caller walks the call stack. With no argument it returns a short
three-element record identifying who called us. With a numeric
argument EXPR it walks EXPR frames further back and returns a
longer eleven-element record — the form the debugger, stack-trace
modules, and warn/die machinery use to decorate diagnostics with
file-and-line context. XS frames are invisible to caller; the next
pure-Perl frame surfaces in their place.
Synopsis#
caller
caller EXPR
What you get back#
In scalar context, the caller’s package name, or undef if there is
no caller (i.e. we are at the top level of the file, not inside a
sub, eval, or require):
my $pkg = caller;
In list context with no argument, three elements — the immediate caller’s package, file, and line number:
# 0 1 2
my ($package, $filename, $line) = caller;
In list context with a numeric argument, eleven elements describing
the frame EXPR levels up. 0 is the immediate caller, 1 is its
caller, and so on:
# 0 1 2 3 4
my ($package, $filename, $line, $subroutine, $hasargs,
# 5 6 7 8 9 10
$wantarray, $evaltext, $is_require, $hints, $bitmask, $hinthash)
= caller($i);
The eleven fields, in order:
$package,$filename,$line— location of the call site inside that frame’s caller. Same three values the short form returns.$subroutine— fully qualified name of the sub the frame belongs to, e.g."Foo::bar". For anevalframe it is the literal string"(eval)". If the sub has been removed from the symbol table since the call, it is"(unknown)".$hasargs— true if a fresh@_was set up for the frame. False forevalandrequireframes.$wantarray— the context the frame was called in, aswantarraywould have reported it: true for list, defined-but-false ("") for scalar,undeffor void.$evaltext— for aneval EXPRframe, the source text that was compiled. Undef foreval BLOCKand for non-evalframes.$is_require— true if the frame was created byrequireoruse(eachusecreates arequireframe nested inside aneval EXPRframe).$hints— the value of$^Hat the point the frame’s code was compiled. Internal; layout is not stable across Perl versions.$bitmask— the value of${^WARNING_BITS}at the same point. Also internal.$hinthash— a reference to the%^Hhash captured at compile time, orundefif it was empty. Do not modify it — the reference points at the live optree.
Global state it touches#
@DB::args— set as a side effect whencalleris called with an argument from inside theDBpackage. The caller’s argument list is aliased into this array for debugger use. See Edge cases below — this is best-effort and has sharp corners.$^H,${^WARNING_BITS},%^H— read out of the target frame’s compiled state to populate$hints,$bitmask,$hinthash.
Examples#
Find the immediate caller’s package and report to the right log:
sub log_for_caller {
my $pkg = caller;
warn "[$pkg] @_\n";
}
Produce a warn-style location tag. caller returns filename and
line of the call site one frame up, which is almost always the
information you actually want in a diagnostic:
sub note {
my (undef, $file, $line) = caller;
print STDERR "note at $file line $line: @_\n";
}
Walk the full stack. Iterate caller($i) until it returns an empty
list:
sub stacktrace {
my @frames;
for (my $i = 0; my @f = caller($i); $i++) {
push @frames, \@f;
}
return @frames;
}
Detect whether the current sub was called in list, scalar, or void
context. This is wantarray at the current level, but for somebody
else’s frame you reach through caller:
sub describe_parent_context {
my $wa = (caller(1))[5];
return !defined $wa ? "void"
: $wa ? "list"
: "scalar";
}
Tell a require/use frame apart from an ordinary eval:
sub called_from_require {
my @f = caller(1);
return @f && $f[7]; # field 7 is $is_require
}
Render a single frame the way the default die / Carp formatter
does — "at FILE line LINE":
sub location_tag {
my $depth = shift // 0;
my (undef, $file, $line) = caller($depth);
return defined $file ? "at $file line $line" : "at top level";
}
Edge cases#
Scalar context, no caller: at the top level of a script,
scalar callerreturnsundef, and list-contextcallerreturns the empty list. A common idiom for “am I beingrequired as a module, or run as a script?” iscaller() ? ... : ....XS frames are skipped.
calleronly reports pure-Perl frames. If a pure-Perl sub was invoked by an XS sub which was invoked by another pure-Perl sub,caller(0)from the inner sub reports the outer pure-Perl sub — the XS layer is invisible. Stack depths measured withcallertherefore do not include XS dispatchers.evalframes have no args.$hasargsis false forevalandrequireframes, and$subroutineis the literal"(eval)"— not the package of the surrounding code.eval BLOCKvseval EXPR. Both give$subroutine eq "(eval)". Onlyeval EXPRfills$evaltext;eval BLOCKleaves itundef.usecreates two frames. Ause Foostatement is compiled asBEGIN { require Foo; Foo->import; }, andrequireitself is implemented as aneval EXPR. Walking the stack through auseline therefore sees arequire-flaggedevalframe inside an ordinaryevalframe. Check$is_requireto distinguish.(unknown)subroutines. If the sub named in a frame has been deleted from the symbol table (symbol-table surgery,delete $Foo::{bar}) between the call and thecaller,$subroutinereads"(unknown)".Loops and
tryblocks are not frames.while,for,foreach, andtrydo not create call frames.calleronly sees subroutine calls andevals.Optimiser-elided frames. The optimiser may remove tail-call and similar frames before
callercan observe them. Forcaller(N)withN > 1, the frame you get is not guaranteed to be the frame you expected. Do not encode stack depth as a load-bearing contract.@DB::argsis best-effort. It is populated only whencalleris called with an argument from inside packageDB. The values are aliases into the target frame’s@_, not copies — so:Mutations the frame has already made to
@_are visible; original call-time values are not preserved.shift @_inside the frame is usually undone in@DB::args, butpop @_, splices, or having taken a reference to@_all break that.Elements may have been freed and reused for other values by the time you read them.
Stale state from a previous
callercall may still be in@DB::argsif the current call didn’t trigger a refresh. Use it for backtraces and debugger display; do not rely on it for program logic.
$hinthashis live. The hash reference in field 10 points at the actual%^Hsnapshot baked into the optree. Modifying its contents mutates compiler state. Read it; don’t write it.Filename and line can be rewritten.
#linedirectives and anything else the “Plain Old Comments (Not!)” mechanism recognises (seeperlsyn) change the valuescallerreports, just as they change__FILE__and__LINE__.
Differences from upstream#
Fully compatible with upstream Perl 5.42.
See also#
die— raises an exception; its default message uses the same file-and-line informationcallerexposeseval— creates frames thatcallertags with$subroutine eq "(eval)"and may fill$evaltext/$is_requirewantarray— reports the current frame’s calling context; the same value appears as field 5 ofcaller(N)for the frameNlevels up$^H— compile-time hint bits; surfaced as field 8%^H— compile-time hint hash; surfaced as field 10${^WARNING_BITS}— warnings bitmask; surfaced as field 9