DavidSzczesniak
12/15/2017 - 3:58 PM

Anonymous Functions

This refers to a function without a name. It behaves exactly like a regular, named function. However, the major difference is that you can only access anon functions by reference, and not by name.

# This is a dispatch table, it uses hashes to associate input with behaviour:
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);
}