typestar

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

  1. sub { ... } assigned to $double is a code reference; $double->(21) invokes it.
  2. make_counter returns an anonymous sub that closes over its own private $count.
  3. Each call through $tick bumps the captured counter — state with no global in sight.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 3 in Subroutines, step 18 of 27 in Language basics.

← Previous Next →