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
\&nameor usingY-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_subfeature.__SUB__is gated behinduse feature 'current_sub', enabled by default underuse v5.16or any later version bundle. Code targeting older syntax levels must opt in explicitly, or prefix the token withCORE::asCORE::__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, andENDblocks,__SUB__returnsundef. Calling it (__SUB__->()) in those positions dies withCan't use an undefined value as a subroutine reference.Inside
evalblocks,__SUB__refers to the enclosing sub, not theeval— aneval { ... }does not create a new sub frame for this purpose. Insideeval EXPRthe 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 samesub { ... }, each closure sees its own coderef — one per captured environment.goto __SUB__vs__SUB__->(). Thegotoform reuses the current call frame and replaces@_with whatever you assigned before thegoto; 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 jobgoto— pairs with__SUB__for tail-call recursion viagoto __SUB__, the idiom that avoids stack growthcaller— inspect the same call frame from the outside (package, file, line) instead of grabbing a reference to itref— classify what__SUB__returned; always"CODE"inside a sub, empty string outsidereturn— the usual way to exit the sub whose reference__SUB__is; relevant when choosing between recursion and tail-call viagoto __SUB__