Subroutine references
Subroutines can be stored in variables and called later, which lets you pass behaviour around.
In this page:
Subroutine references
You define a named subroutine with sub name { ... } and call it with its name; arguments arrive in the array @_. An anonymous subroutine, written sub { ... }, can be stored in a scalar and called with $code->(args) or &$code(args). Storing code references in hashes or arrays gives you simple dispatch tables.
Note:
Use return to send a value back, otherwise a subroutine returns the value of its last evaluated expression.
Example: Subroutine references
use strict;
use warnings;
sub add { my ($x, $y) = @_; return $x + $y; }
my $adder = \&add;
print "add via ref: ", $adder->(2, 3), "\n";
my $square = sub { my $n = shift; return $n * $n; };
print "square: ", $square->(7), "\n";
my %ops = (
plus => sub { $_[0] + $_[1] },
minus => sub { $_[0] - $_[1] },
times => sub { $_[0] * $_[1] },
);
for my $name (sort keys %ops) {
print "$name: ", $ops{$name}->(6, 3), "\n";
}
# Output:
# add via ref: 5
# square: 49
# minus: 3
# plus: 9
# times: 18
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Calling a code reference without parentheses and the arrow
- Forgetting that arguments are in @_ and not named automatically
- Writing \&name() with parentheses and calling the function instead of referencing it
Chapter Summary
- sub { } creates an anonymous subroutine
- \&name references a named one
- $code->(args) calls it
- Hashes of code refs make dispatch tables
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: