Anonymous Subroutines
Anonymous subroutines do everything that ordinary subroutines do. They can declare a formal parameter list with optional and required parameters, take positional and named arguments, and do variadic slurping. The only difference is that they don’t define a name. But since you can’t call a subroutine if you have no way to refer to it, they have to get the equivalent of a name somewhere, whether they’re assigned to a variable, passed as a parameter, or aliased to another subroutine.
$make_tea = sub ($tealeaves, ?$sugar, ?$milk) { . . . }The
arrow
operator used with for and
given is just another way of defining anonymous
subroutines. The arrow doesn’t require parentheses
around its parameter list. It can’t declare named
subs, and can’t declare a return type.
$make_tea = -> $tealeaves, ?$sugar, ?$milk { . . . }A bare block can also define an anonymous subroutine, but it can’t define a formal parameter list on the sub and can’t define a named sub:
$make_tea = {
my $tea = boil 'tealeaves';
combine $tea, 'sugar', 'milk';
}You can’t use the return
statement within an arrow sub or bare block sub to return from an
anonymous sub. Blocks and arrow subs are commonly used for ordinary
control flow, so return ignores them and only
returns from subroutines defined with sub keyword
or methods.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access