Closures
Learn about closures in Perl.
We'll cover the following...
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:
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:
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;