Code References and Closures
Subroutines are data too. A code reference is a scalar that points to a sub, so you can store subs in variables, put them in hashes, pass them to other subs and return them. This is the basis of callbacks, dispatch tables and closures.
Anonymous subs
sub { ... } without a name creates an anonymous subroutine and returns a reference to it. Call it with ->():
use strict;
use warnings;
my $double = sub { return $_[0] * 2 };
my $greet = sub {
my ($name) = @_;
return "Hi, $name";
};
print $double->(21), "\n";
print $greet->("Sam"), "\n";
print "Type: ", ref($double), "\n";
sub shout { uc $_[0] }
my $named_ref = \&shout; # reference to a named sub
print $named_ref->("loud"), "\n";42
Hi, Sam
Type: CODE
LOUD
Passing subs to subs (callbacks)
A sub that receives a code reference can call it whenever it needs to. Here one apply_discount function can use any pricing rule:
use strict;
use warnings;
use feature 'signatures';
sub apply_to_prices ($rule, @prices) {
return map { $rule->($_) } @prices;
}
my $ten_percent_off = sub ($p) { $p * 0.9 };
my $flat_five_off = sub ($p) { $p > 5 ? $p - 5 : 0 };
my @prices = (20, 50, 4);
print "10% off: ", join(", ", apply_to_prices($ten_percent_off, @prices)), "\n";
print "\$5 off: ", join(", ", apply_to_prices($flat_five_off, @prices)), "\n";10% off: 18, 45, 3.6
$5 off: 15, 45, 0
This is exactly how sort, map and grep work: they take a block of code and call it for you.
Dispatch tables
A hash of code references replaces a long if/elsif chain. The key selects the action:
use strict;
use warnings;
my %calculator = (
add => sub { $_[0] + $_[1] },
sub => sub { $_[0] - $_[1] },
mul => sub { $_[0] * $_[1] },
div => sub { $_[1] == 0 ? "division by zero" : $_[0] / $_[1] },
);
for my $cmd (["add", 7, 3], ["mul", 4, 5], ["div", 9, 0], ["pow", 2, 8]) {
my ($op, $x, $y) = @$cmd;
my $action = $calculator{$op};
my $result = $action ? $action->($x, $y) : "unknown operation";
print "$op($x, $y) = $result\n";
}add(7, 3) = 10
mul(4, 5) = 20
div(9, 0) = division by zero
pow(2, 8) = unknown operation
Adding a new command now means adding one line to the hash.
Closures
An anonymous sub remembers the lexical (my) variables that were in scope when it was created, even after that scope has ended. Such a sub is called a closure:
use strict;
use warnings;
sub make_counter {
my $count = 0; # each call creates a fresh $count
return sub { return ++$count };
}
my $clicks = make_counter();
my $views = make_counter();
$clicks->() for 1 .. 3;
$views->();
print "clicks: ", $clicks->(), "\n";
print "views: ", $views->(), "\n";clicks: 4
views: 2
Each counter has its own private $count. Nobody outside can change it except by calling the closure, so closures are a lightweight way to keep state.
Function factories
Closures make it easy to generate families of related functions:
use strict;
use warnings;
use feature 'signatures';
sub make_formatter ($prefix, $decimals) {
return sub ($value) { sprintf "%s%.*f", $prefix, $decimals, $value };
}
my $usd = make_formatter('