Anonymous Functions
Learn about anonymous functions in Perl.
We'll cover the following...
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:
Press + to interact
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 ...