Thanks for writing this - I found it interesting. I recently needed to write something that ended up including the first practical use of a closure that I've ever done - I needed to be able to look up a value from a hash table many times, in several different subroutines, but I didn't want to either (a) make the hash global, or (b) have the hash reloaded in each sub.
It was the first time I realized that, hey, closures could be quite useful (my example below).
my $monthConverter = monthConverterFactory();
...
my $moNum = &$monthConverter($mo);
if ($moNum > $currentDate[1]) {
$y = $currentDate[2] - 1;
}
...
# Use a closure here, so we don't have to load this private
# data more than once.
sub monthConverterFactory {
my %months = ( Jan => 0,
Feb => 1,
Mar => 2,
Apr => 3,
May => 4,
Jun => 5,
Jul => 6,
Aug => 7,
Sep => 8,
Oct => 9,
Nov => 10,
Dec => 11
);
return sub {
my $val = shift;
return $months{$val};
}
}