Perl closure example and dispatch table tags = #perl #programming code=yes http://stackoverflow.com/questions/4665268/perl-closures-and http://perldoc.perl.org/perlfaq7.html#What's-a-closure%3f http://www.perl.com/pub/2002/05/29/closure.html From the Date::Formatter Perl module http://search.cpan.org/dist/Date-Formatter/lib/Date/Formatter.pm my %_parser_table = ( "MM" => \&getNumericMonth, "M" => \&getMonth, "DD" => \&getDayOfMonth, "D" => \&getDayOfWeek, "YY" => \&getYear, "YYYY" => \&getFullYear, "hh" => \&getHours, "mm" => \&getMinutes, "ss" => \&getSeconds, "T" => \&isAMorPM, "O" => \&getGMTOffset ); sub createDateFormatter { my ($self, $format, $pattern) = @_; my @date_format; $pattern ||= qr/\(|\)/; my @tokens = split $pattern => $format; while (@tokens) { my $token = shift(@tokens); if (exists $_parser_table{$token}) { push @date_format, $_parser_table{$token}; } else { push @date_format, sub{ return "$token" }; } } $self->{formatter} = sub { my ($self) = @_; return join "" => map { $_->($self); } @date_format; }; return $self; } ======================= http://stackoverflow.com/questions/4665268/perl-closures-and use strict; use warnings; use 5.010; my @closures; foreach my $_ (1..3) { # create some closures push @closures, sub { say "I will remember $_"; }; } foreach (@closures) { # call the closures to see what they remember # the result is not obvious &{$_}(); }