How to create anonymous subroutines in Perl?
Question
How to create anonymous subroutines in Perl?
How to Create Anonymous Subroutines in Perl
Anonymous subroutines (often called anonymous subs or coderefs) are subroutines without a name. Instead of being given a symbolic name, they are referenced via a scalar variable or passed directly as parameters. These are useful for callbacks, closures, and functional-style programming, where you want to treat subroutines as first-class values.
In Perl, you create an anonymous subroutine using the sub { ... } block without a name. This returns a reference to the subroutine, which can be stored in a scalar, passed around, or called indirectly.
Basic Syntax
my $coderef = sub {
# code here
};
Here $coderef holds a reference to the anonymous subroutine. You can call the subroutine via the reference using the arrow -> notation:
$coderef->(@args);
Example: Defining and Calling an Anonymous Subroutine
# Run with: perl -
use strict;
use warnings;
my $greet = sub {
my ($name) = @_; # Get argument(s)
print "Hello, $name!\n";
};
# Calling the anonymous subroutine through the reference
$greet->('World');
# Passing an anonymous sub directly to another subroutine
sub repeat_call {
my ($code, $times) = @_;
for (1 .. $times) {
$code->();
}
}
repeat_call(sub { print "Called anonymously\n" }, 3);
This script demonstrates two common patterns:
- Assigning an anonymous subroutine to a scalar
$greetand calling it. - Passing an anonymous subroutine directly as an argument to another routine (
repeat_call), which calls it multiple times.
Important Perl Concepts Related to Anonymous Subs
- Sigils and References: The scalar
$greetstores a reference to the sub, not the subroutine itself. Thus you always call it with->. This is different from named subs, which you call by their bareword name. - Context: Like normal subs, anonymous subs receive parameters in
@_and can return values. They can also form closures, capturing lexical variables from their surrounding scope. - TMTOWTDI: Perl gives you multiple ways to do things, so you might see alternative styles like the classic named subroutines, or anonymous subs used as callbacks with different calling conventions.
Common Pitfalls
- Forgetting
->when calling: You must use->syntax to call a coderef ($coderef->()), not just$coderef(). - Variable scope with closures: Lexical vars used inside anonymous subs will stay alive as long as the coderef exists, which can cause unexpected memory retention if not considered.
- Prototype confusion: Anonymous subs do not have prototypes, so you cannot enforce argument counts or types like you might with named subs and prototypes.
Version Notes
Anonymous subs have been part of Perl since very early versions (well before 5.10), so you don't need newer Perl versions to use them. However, since Perl 5.10, you can use features like state, subroutine signatures (experimental in 5.20+, stable in 5.36+), and other syntax sugar to improve them.
In summary, anonymous subroutines enable powerful and flexible programming in Perl by treating code blocks as data. They are fundamental to event-driven programming and functional styles within Perl.
Verified Code
Executed in a sandbox to capture real output. • v5.34.1 • 4ms
(empty)(empty)Was this helpful?
Related Questions
- How to use the return statement early in a Perl subroutine?
- How to create higher-order functions in Perl?
- How to use shift to get subroutine arguments in Perl?
- How to use caller() to get subroutine call information in Perl?
- How to call a subroutine as a method in Perl?
- How to use state variables in Perl subroutines?