TExcelTAD
Home › Perl › Code References and Closures

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 ->():

perl · try it yourself
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:

perl · try it yourself
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:

perl · try it yourself
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:

perl · try it yourself
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:

perl · try it yourself
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('
  

, 2);
my $temp = make_formatter('T=', 1);

print $usd->(1234.5), "\n";
print $temp->(21.456), "\n";

my @multipliers = map { my $n = $_; sub { $_[0] * $n } } 1 .. 3;
print join(" ", map { $_->(10) } @multipliers), "\n";
$1234.50
T=21.5
10 20 30

%.*f takes the number of decimals from the argument list. In the map, copying $_ into my $n is essential: each closure needs its own variable, while $_ is a single global that keeps changing.

Test yourself

How do you call the code reference in $cb with argument 5?

  1. $cb(5)
  2. &cb(5)
  3. $cb->(5)
  4. call $cb 5

What is a closure?

  1. A sub that ends with close
  2. An anonymous sub that keeps access to the lexical variables in scope when it was created
  3. A sub without arguments
  4. A way to close filehandles

What does \&report give you?

  1. The result of calling report
  2. A reference to the named sub report
  3. A string "report"
  4. An error