Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Intro to anonymous functions in Perl
# Intro to anonymous functions in Perl
use strict;
use warnings;
use feature qw(say);
use utf8;
binmode STDOUT, ':utf8';
# You can declare a sub without giving it a name. Hence, "anonymous" function.
sub { say 'this sub will never be called' };
# Since the above function can never be invoked, you will get the following
# warning: Useless use of reference constructor in void context
# You can create an anonymous function, also known as an anonymous subref (in
# Perl) or a lambda (more generally), and invoke it immediately:
(sub { say 'this will be used once' })->();
# Note that you get back a reference to the anonymous function, so you must
# dereference via -> This is why in perl an anonymous function can also be
# called an anonymous subref.
# You can embed an anonymous function inside of a hashref (or in other places).
my $fns = {
hi => sub { say 'hi' }
};
$fns->{hi}(); # hi
$fns->{bye} = sub { say 'bye' };
$fns->{bye}(); # bye
# You can store an anonymous function inside of a scalar variable.
my $konnichiwa = sub { say 'konnichiwa' };
$fns->{japanese} = $konnichiwa;
$fns->{japanese}(); # konnichiwa
# You can also take a reference to an existing function and stuff that in a
# hashref.
sub guten_tag { say 'guten tag' };
$fns->{german} = \&guten_tag; # Create a subref (to a named sub)
$fns->{german}(); # guten tag
# From this you can see that functions aren't necessarily a special value;
# they can be passed around like a scalar. This is called having "first class
# functions".
# Some perl builtins can take functions.
sub square { $_ * $_ };
my @squares = map &square, 1..10; # apply square to the range of 1 to 10
say foreach @squares;
# They can also take a block, which is kind of like an anonymous function :)
say foreach map { $_ * $_ } 1..10;
# One use for anonymous functions is to provide dynamic runtime behavior
# driven by a configuration hash:
my $greetings = {
german => sub { say 'guten Tag' },
japanese => sub { say '今日は' },
};
say "Do you speak German or Japanese?";
my $language = <>; chomp($language);
$greetings->{lc($language)}();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.