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 & on the name of a function:
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:
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 ...