How to create a reference to a subroutine in Perl?
Question
How to create a reference to a subroutine in Perl?
In Perl, a reference to a subroutine allows you to treat a piece of code as a first-class value—passing it around like any other scalar data. This technique enables higher-order programming, callbacks, and dynamic dispatch, enhancing Perl’s flexibility and expressiveness.
Creating a Reference to a Subroutine
To create a reference to a subroutine, you use the backslash operator \\ on the subroutine name (without parentheses). This returns a code reference scalar. You can then invoke the referenced subroutine using the -> dereferencing syntax.
Perl subroutine references are scalars that hold a reference to the compiled code, distinguished by the CODE type internally.
Example: Basic Subroutine Reference
use strict;
use warnings;
# Define a simple subroutine
sub greet {
my ($name) = @_;
return "Hello, $name!";
}
# Create a reference to the subroutine
my $code_ref = \&greet;
# Call the subroutine via the reference
my $message = $code_ref->("Alice");
print "$message\n"; # prints "Hello, Alice!"
This example shows:
\&greetcreates a reference to the named subroutinegreet.$code_ref->("Alice")calls the referenced subroutine with argument "Alice".
Anonymous Subroutines and References
Perl also lets you create anonymous subroutines on the fly using the sub { ... } block syntax. These are inherently references, so you can assign them directly:
my $anon_ref = sub {
my ($x) = @_;
return $x * 2;
};
print $anon_ref->(5), "\n"; # prints 10
Key Points and Gotchas
- Sigils: Use
\&subnameto get a reference to a named subroutine. Do NOT include parentheses;\&subname()calls the subroutine and then attempts to take a reference to its return value. - Invocation: Use arrow syntax
$code_ref->(@args)to call the subroutine reference. Alternatively, you can use the syntax&$code_ref(@args), but arrow syntax is preferred and clearer. - Context: The subroutine reference preserves context, so it behaves identically to calling the subroutine directly.
- Checking Reference Type: Use
ref $code_ref eq 'CODE'to confirm a variable holds a subroutine reference. - Version Notes: References and anonymous subs are core Perl features since early versions. Some shorthand like the
->()calling syntax became more idiomatic around Perl 5.6+
Summary
Creating a subroutine reference in Perl is straightforward with the \\&subname syntax for named subs or sub { ... } for anonymous subs. Holding a subroutine reference enables flexible code designs, such as callbacks and dispatch tables. Make sure not to confuse \\&subname (a reference) with subname() (a subroutine call), and use $coderef->() to invoke the code reference cleanly.
Verified Code
Executed in a sandbox to capture real output. • v5.34.1 • 6ms
Hello, Alice!
(empty)