Search⌘ K

Closures

Explore how Perl closures work by capturing lexical variables within functions to create powerful, encapsulated behaviors. Understand their role in iterating data collections, caching results like the Fibonacci series, and customizing function behavior through partial application. Gain practical insights into writing maintainable, efficient Perl code that leverages higher-order functions for real-world programming challenges.

The computer science term higher-order functions refers to functions that manipulate other functions. Every time control flow enters a function, that function gets a new environment representing that invocation’s lexical scope. That applies equally well to anonymous functions. The implication is powerful, and closures show off this power.

Creating closures

A closure is a function that uses lexical variables from an outer scope. You’ve probably already created and used closures without realizing it:

Perl
my $filename = shift @ARGV;
sub get_filename { return $filename }

If this code seems straightforward, good! Of course the get_filename() function can see the $filename lexical. That’s how scope works!

Suppose we want to iterate over a list of items without managing the iterator ourselves. We can create a function that returns a function that, when invoked, will return the next item in the iteration:

Perl
sub make_iterator {
my @items = @_;
my $count = 0;
return sub {
return if $count == @items;
return $items[ $count++ ];
}
}
my $cousins = make_iterator(qw(
Rick Alex Kaycee Eric Corey Mandy Christine Alex
));
say $cousins->() for 1 .. 6;
...