Types of References II
Learn about some more types of references in Perl.
Function references
Perl supports first-class functions; a function is a data type like an array or hash. In other words, Perl supports function references. This enables many advanced features like &
on the name of a function:
sub bake_cake { say 'Baking a wonderful cake!' };my $cake_ref = \&bake_cake;say $cake_ref;
Without the function sigil &
, we will take a reference to the function’s return value or values.
Creating anonymous functions
We can create anonymous functions with the bare sub
keyword:
my $pie_ref = sub { say 'Making a delicious pie!' };$pie_ref->();
The sub
built-in used without a name compiles the function but doesn’t register it with the current namespace. The only way to access this function is via the reference returned from sub
. Invoke the function reference with the dereferencing arrow:
$cake_ref->();
$pie_ref->();
Note: An alternate invocation syntax for function references uses the function sigil ...