Search⌘ K
AI Features

Types of References II

Explore function references in Perl, such as closures and anonymous functions, and how to create and invoke them. Understand filehandle references and their role in resource management. Learn about Perl's reference counting system and the importance of avoiding circular references. This lesson helps you write maintainable code by managing references properly and using best practices for passing references to functions.

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 closuresA closure is a function that uses lexical variables from an outer scope.. We can create a function reference by using the reference operator and the function sigil & on the name of a function:

Perl
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:

Perl
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 ...