← Back to Perl Course | Chapter 6: References | Lesson 5 of 7

Subroutine references

Subroutines can be stored in variables and called later, which lets you pass behaviour around.

In this page:

  1. Subroutine references

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

perl
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
Common Mistakes
  1. Calling a code reference without parentheses and the arrow
  2. Forgetting that arguments are in @_ and not named automatically
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.