Closures in Perl

Perl supports anonymous functions, which can form closures. Anonymous functions are useful when you want to define a function inline without having to name it.

use strict;
use warnings;

# This function intSeq returns another function, which
# we define anonymously in the body of intSeq. The
# returned function closes over the variable $i to
# form a closure.
sub intSeq {
    my $i = 0;
    return sub {
        $i++;
        return $i;
    };
}

# We call intSeq, assigning the result (a function)
# to $nextInt. This function value captures its
# own $i value, which will be updated each time
# we call $nextInt.
my $nextInt = intSeq();

# See the effect of the closure by calling $nextInt
# a few times.
print $nextInt->(), "\n";
print $nextInt->(), "\n";
print $nextInt->(), "\n";

# To confirm that the state is unique to that
# particular function, create and test a new one.
my $newInts = intSeq();
print $newInts->(), "\n";

To run the program, save it as closures.pl and use the perl command:

$ perl closures.pl
1
2
3
1

In this Perl version, we’ve implemented the same closure concept as in the original example. The intSeq function returns an anonymous subroutine that closes over the $i variable. Each time this returned function is called, it increments and returns the value of $i.

We demonstrate the use of this closure by calling $nextInt multiple times, showing how it maintains its own state. We then create a new closure with $newInts to show that it has its own independent state.

Perl’s closure implementation is very similar to many other languages, making it a powerful tool for creating functions with persistent private state.

The last feature of functions we’ll look at for now is recursion.