Search⌘ K

Anonymous Functions

Explore the concept of anonymous functions in Perl, how to declare them, pass them as arguments, and safely manage their scope using dispatch tables. Understand the use of CPAN modules to name anonymous functions and the nuances of Perl's syntax for delayed execution.

An anonymous function is a function without a name. It behaves exactly like a named function—we can invoke it, pass it arguments, return values from it, and take references to it. Yet, we can access an anonymous function only by reference, not by name.

A Perl idiom known as a dispatch table uses hashes to associate input with behavior:

Perl
my %dispatch = (
plus => \&add_two_numbers,
minus => \&subtract_two_numbers,
times => \&multiply_two_numbers,
);
sub add_two_numbers { $_[0] + $_[1] }
sub subtract_two_numbers { $_[0] - $_[1] }
sub multiply_two_numbers { $_[0] * $_[1] }
sub dispatch {
my ($left, $op, $right) = @_;
return unless exists $dispatch{ $op };
return $dispatch{ $op }->( $left, $right );
}
say dispatch(3,'times',2);
say dispatch(3,'plus',2);
say dispatch(3,'minus',2);

The dispatch() function takes arguments of the form (2, 'times', 2), evaluates the operation, and returns the result. A trivial calculator application could use dispatch to figure out which calculation to perform based on user input.

Declaring anonymous functions

The sub built-in used without a name creates and returns an anonymous function. We should use this function ...