Control flow

SUB#

Return a reference to the currently executing subroutine.

__SUB__ is the self-reference token: inside a sub, it evaluates to a code reference pointing at that same sub, without the sub having to know its own name. Outside any sub, it is undef. The common reason to reach for it is anonymous recursion — a sub stored in a lexical or passed around as a callback needs a way to call itself that does not depend on a package-qualified name, and __SUB__ is it.

Synopsis#

__SUB__
__SUB__->(@args)
goto __SUB__

Takes no arguments and has no parentheses form — it is a compile-time token, not a function call.

What you get back#

A code reference (the same thing \&name would give you for a named sub), or undef when evaluated outside any subroutine. The reference is to the runtime sub, including any closure over lexicals captured when the sub was created, so calling it recursively sees the same captured environment.

my $fact = sub {
    my $n = shift;
    $n < 2 ? 1 : $n * __SUB__->($n - 1);
};

print $fact->(5);               # 120

The call form is an ordinary coderef invocation: __SUB__->(@args) or &{__SUB__}(@args). No arguments are passed implicitly; recursion must pass them on.

Why not just use the sub’s name#

Named subs can already recurse by name — factorial(...) inside sub factorial works. __SUB__ earns its place in three situations where a name is unavailable, unreliable, or expensive:

  • Anonymous subs. An anonymous sub assigned to a lexical has no stable package-qualified name. A common pre-5.16 workaround was capturing a reference to \&name or using Y-combinator tricks; __SUB__ replaces both.

  • Subs passed as callbacks. A sub handed to another API (sort comparator, event handler, iterator step) may be called back before it has a name visible at the recursion site.

  • Tail-call recursion via goto. goto __SUB__ reuses the current call frame and jumps to the top of the same sub with whatever @_ you set up, which matters for deep recursion that would otherwise blow the stack.

Global state it touches#

__SUB__ reads the currently executing call frame — the same frame caller inspects. It does not read or modify any special variables.

Examples#

Anonymous factorial, the textbook case:

my $fact = sub {
    my $n = shift;
    $n < 2 ? 1 : $n * __SUB__->($n - 1);
};
print $fact->(6);               # 720

Tail-recursive sum with goto __SUB__ — no stack growth per iteration, because goto reuses the current frame:

my $sum = sub {
    my ($acc, @rest) = @_;
    return $acc unless @rest;
    @_ = ($acc + shift @rest, @rest);
    goto __SUB__;
};
print $sum->(0, 1..1_000_000);  # 500000500000

Walking a nested data structure without naming the walker:

my $count_leaves = sub {
    my $node = shift;
    return 1 unless ref $node eq 'ARRAY';
    my $n = 0;
    $n += __SUB__->($_) for @$node;
    return $n;
};
print $count_leaves->([1, [2, 3], [[4], 5]]);   # 5

Outside any sub, __SUB__ is undef:

print defined(__SUB__) ? "yes" : "no";          # no

Captured, not resolved-on-call. __SUB__ is evaluated each time it runs, in the frame it runs in — so in a nested sub it refers to the inner sub:

sub outer {
    my $inner = sub { __SUB__ };    # inner's own coderef
    return $inner->();
}
my $ref = outer();
print $ref == $ref;                 # 1 — stable coderef

Edge cases#

  • Requires the current_sub feature. __SUB__ is gated behind use feature 'current_sub', enabled by default under use v5.16 or any later version bundle. Code targeting older syntax levels must opt in explicitly, or prefix the token with CORE:: as CORE::__SUB__.

  • No parentheses form. __SUB__() is a syntax error — the token is not a function, it’s a keyword that evaluates to a coderef. Call the result with __SUB__->() or &{__SUB__}().

  • Outside any sub, including at file scope and inside BEGIN, UNITCHECK, CHECK, INIT, and END blocks, __SUB__ returns undef. Calling it (__SUB__->()) in those positions dies with Can't use an undefined value as a subroutine reference.

  • Inside eval blocks, __SUB__ refers to the enclosing sub, not the eval — an eval { ... } does not create a new sub frame for this purpose. Inside eval EXPR the same rule applies: the token resolves to the outer sub.

  • Inside a regex code block (/(?{...})/ or /(??{...})/), the behaviour of __SUB__ is subject to change — upstream documents this as unstable. Do not rely on what it returns there.

  • Identity across calls. Two evaluations of __SUB__ inside the same sub yield the same coderef (== compares true). Across different closures made from the same sub { ... }, each closure sees its own coderef — one per captured environment.

  • goto __SUB__ vs __SUB__->(). The goto form reuses the current call frame and replaces @_ with whatever you assigned before the goto; it does not grow the call stack. The coderef call form makes a fresh frame every time, so it hits the recursion depth limit on deeply recursive inputs.

Differences from upstream#

Fully compatible with upstream Perl 5.42.

See also#

  • sub — defines the subroutine whose reference __SUB__ hands back; the first place to look when anonymous recursion is the tool for the job

  • goto — pairs with __SUB__ for tail-call recursion via goto __SUB__, the idiom that avoids stack growth

  • caller — inspect the same call frame from the outside (package, file, line) instead of grabbing a reference to it

  • ref — classify what __SUB__ returned; always "CODE" inside a sub, empty string outside

  • return — the usual way to exit the sub whose reference __SUB__ is; relevant when choosing between recursion and tail-call via goto __SUB__