Control flow · Scoping

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 an eval frame 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 for eval and require frames.

  • $wantarray — the context the frame was called in, as wantarray would have reported it: true for list, defined-but-false ("") for scalar, undef for void.

  • $evaltext — for an eval EXPR frame, the source text that was compiled. Undef for eval BLOCK and for non-eval frames.

  • $is_require — true if the frame was created by require or use (each use creates a require frame nested inside an eval EXPR frame).

  • $hints — the value of $^H at 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 %^H hash captured at compile time, or undef if 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 when caller is called with an argument from inside the DB package. 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 caller returns undef, and list-context caller returns the empty list. A common idiom for “am I being required as a module, or run as a script?” is caller() ? ... : ....

  • XS frames are skipped. caller only 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 with caller therefore do not include XS dispatchers.

  • eval frames have no args. $hasargs is false for eval and require frames, and $subroutine is the literal "(eval)" — not the package of the surrounding code.

  • eval BLOCK vs eval EXPR. Both give $subroutine eq "(eval)". Only eval EXPR fills $evaltext; eval BLOCK leaves it undef.

  • use creates two frames. A use Foo statement is compiled as BEGIN { require Foo; Foo->import; }, and require itself is implemented as an eval EXPR. Walking the stack through a use line therefore sees a require-flagged eval frame inside an ordinary eval frame. Check $is_require to 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 the caller, $subroutine reads "(unknown)".

  • Loops and try blocks are not frames. while, for, foreach, and try do not create call frames. caller only sees subroutine calls and evals.

  • Optimiser-elided frames. The optimiser may remove tail-call and similar frames before caller can observe them. For caller(N) with N > 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::args is best-effort. It is populated only when caller is called with an argument from inside package DB. 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, but pop @_, 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 caller call may still be in @DB::args if the current call didn’t trigger a refresh. Use it for backtraces and debugger display; do not rely on it for program logic.

  • $hinthash is live. The hash reference in field 10 points at the actual %^H snapshot baked into the optree. Modifying its contents mutates compiler state. Read it; don’t write it.

  • Filename and line can be rewritten. #line directives and anything else the “Plain Old Comments (Not!)” mechanism recognises (see perlsyn) change the values caller reports, 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 information caller exposes

  • eval — creates frames that caller tags with $subroutine eq "(eval)" and may fill $evaltext / $is_require

  • wantarray — reports the current frame’s calling context; the same value appears as field 5 of caller(N) for the frame N levels 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