Ad space (banner)
Lesson 14 / 20

Anonymous subroutines

This lesson covers the anonymous subroutine — a closure — which you can define on the spot without giving it a name.

Writing my $var = sub { ... }; assigns a subroutine to a variable. You call it with $var->(args).

The sample code creates the anonymous subroutine my $add_tax = sub { my $price = shift; return $price + int($price / 10); }; and uses it to add sales tax to several product prices.

A common early stumble is the call syntax. Unlike an ordinary subroutine, an anonymous one held in a variable is called with the arrow: $var->(args).

In professional work, anonymous subroutines come up constantly alongside functions such as map and grep that apply logic to each element of an array.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Perl directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)