Anonymous subs and closures in Perl
Code in a variable: sub { ... } with no name returns a reference you call with an arrow.
use strict;
use warnings;
my $double = sub { return $_[0] * 2 };
print $double->(21), "\n";
sub make_counter {
my $count = 0;
return sub { return ++$count };
}
my $tick = make_counter();
$tick->();
print $tick->(), " ticks so far\n";
How it works
sub { ... }assigned to$doubleis a code reference;$double->(21)invokes it.make_counterreturns an anonymous sub that closes over its own private$count.- Each call through
$tickbumps the captured counter — state with no global in sight.
Keywords and builtins used here
make_countermyprintreturnsubuse
The run, in numbers
- Lines
- 14
- Characters to type
- 236
- Tokens
- 78
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 67 seconds.
Step 3 of 3 in Subroutines, step 18 of 27 in Language basics.