Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 43 ยท Subroutines

Subroutines

Write reusable Perl subroutines: how sub, @_ and return work, why arguments are aliases, modern signatures with default values, and wantarray.

A subroutine (often just called a "sub") is a named block of code you can run from anywhere in your program. Subroutines remove repetition, give ideas names, and let you test small pieces on their own. In other languages these are called functions or methods; in Perl the keyword is sub.

Perl subroutines have a distinctive way of taking arguments: everything you pass arrives in one special array called @_. Once you understand that array, and the modern signatures feature that tidies it up, writing subroutines becomes simple.

Perl is not installed on this site, so the Perl code below is read-only, and its output comes from a real Perl 5.42 run. The interactive examples are Python stand-ins that show the same ideas.

Anatomy of a call

Arguments Everything passed in lands in @_.
Body Your code reads and uses @_.
Return The last value, or an explicit return.

A sub can return one value or a whole list.

1 / 2

Defining and calling a subroutine

Define a subroutine with sub, a name and a block. Call it by writing its name with parentheses:

PERL
use v5.36;

sub greet {
    my ($name) = @_;
    return "Hello, $name!";
}

say greet("Ada");
TEXT
Hello, Ada!

Inside the sub, @_ holds the arguments. The line my ($name) = @_; copies the first argument into a new lexical variable. The parentheses around $name are important: they put the assignment in list context, so the first element of @_ goes into $name. Without them, you would store the number of arguments instead. This is the context idea from Context: Scalar vs List at work.

A sub can be defined before or after the code that calls it. Perl compiles the whole file first, so greet("Ada") works even if the sub greet block appears lower down, as long as you use parentheses on the call.

Returning values

return ends the sub and hands back a value. If you leave out return, the sub returns the value of the last expression it evaluated. Many Perl programmers use that for very short subs:

PERL
sub add {
    my ($x, $y) = @_;
    $x + $y            # the last expression is the result
}
say add(2, 3);
TEXT
5

Use an explicit return when the sub is more than a line or two, or when you leave early. It states your intent and avoids surprises when the last statement is something other than the value you wanted, such as an if block.

A sub can return a list too:

PERL
sub minmax {
    my @sorted = sort { $a <=> $b } @_;
    return ($sorted[0], $sorted[-1]);
}

my ($lo, $hi) = minmax(5, 2, 9, 1);
say "$lo $hi";
TEXT
1 9

Assigning the result to a list of variables takes the values apart. Returning a list is Perl's natural answer to "I need two results".

Arguments are aliases

The elements of @_ are aliases of the variables you passed, not copies. If you change $_[0] or loop over @_ and modify it, the caller's variables change too.

PERL
sub double_all {
    $_ *= 2 for @_;      # modifies the caller's values!
}

my @nums = (1, 2, 3);
double_all(@nums);
say "@nums";
TEXT
2 4 6

This can be a feature (it is how some built-ins work) but it is usually a source of bugs. The safe habit is to copy first with my (...) = @_;. The copy below leaves the caller untouched:

PERL
sub doubled {
    my @copy = @_;
    $_ *= 2 for @copy;
    return @copy;
}

my @in = (1, 2, 3);
my @out = doubled(@in);
say "@in | @out";
TEXT
1 2 3 | 2 4 6

Also note that all arguments are flattened into one list. Passing two arrays gives one longer list, and the sub cannot tell where the first ended. To pass structures intact, send references, which you will meet in References.

The Python stand-in below shows the same difference between changing the caller's data in place and working on a copy. Python passes a list by reference, so it behaves much like Perl's aliasing.

Python Stand-in: change in place or work on a copy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Signatures: named parameters

Modern Perl lets you declare parameters in the sub line. They are enabled by use v5.36 (or newer), or by use feature 'signatures'.

PERL
use v5.36;

sub describe ($name, $age) {
    return "$name is $age";
}

say describe("Ada", 36);
TEXT
Ada is 36

Signatures give you three real benefits: the variables are named in one clear place, no copy line is needed, and Perl checks the number of arguments. A wrong count dies with a clear message:

PERL
sub two ($a2, $b2) { return 1 }
two(1, 2, 3);
TEXT
Too many arguments for subroutine 'main::two' (got 3; expected 2)

Calling with too few arguments gives a similar Too few arguments message. Because the variables are copies, signatures also remove the aliasing surprise.

Default values and slurpy parameters

A parameter can have a default, which is used when the caller leaves it out. A final array or hash parameter, called slurpy, takes all the remaining arguments:

PERL
sub options ($x, $y = 10, @rest) {
    return "$x $y [@rest]";
}

say options(1);
say options(1, 2);
say options(1, 2, 3, 4);
TEXT
1 10 []
1 2 []
1 2 [3 4]

For named options, a slurpy hash works well:

PERL
sub named ($name, %opts) {
    my $greeting = $opts{greeting} // "Hello";
    return "$greeting, $name";
}

say named("Bob", greeting => "Hi");
TEXT
Hi, Bob

A default can also apply when the argument is undef, with //=, as in sub f ($x, $y //= 5). The older, signature-free way to build defaults is my $y = shift // 5;, and you will see it in a lot of existing code.

Python Stand-in: defaults, extra arguments and options

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Context-aware subs with wantarray

A sub can find out how its result will be used. The built-in wantarray returns true in list context, false in scalar context, and undef when the result is thrown away (void context).

PERL
sub context {
    return wantarray ? "list" : defined(wantarray) ? "scalar" : "void";
}

my @l = context();
my $s = context();
say "$l[0] $s";
TEXT
list scalar

Many built-in functions work this way: localtime returns a list or a string depending on context (see Dates and Times). Use wantarray for your own subs sparingly, because behavior that changes with context can be hard to predict.

Other ways to take arguments

You will meet two older styles in existing code:

  • my $first = shift; removes and returns the first element of @_. Inside a sub, shift defaults to @_.
  • my %args = @_; treats the arguments as key and value pairs, which is how many older modules take named options.
PERL
sub join_pairs {
    my %opts = @_;
    return join ",", map { "$_=$opts{$_}" } sort keys %opts;
}
say join_pairs(b => 2, a => 1);
TEXT
a=1,b=2

You may also see calls written as &add(1, 1). The ampersand form is old-fashioned, it skips prototype checks, and &add; without parentheses even reuses the caller's @_, so avoid it in new code.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does my ($x) = @_; do?

    The parentheses give list context, so the first element of @_ is copied into $x. Without parentheses you would get the count.
  2. 2. What does a sub return if it has no explicit return?

    Perl returns the value of the last evaluated expression. An explicit return is clearer for longer subs.
  3. 3. Why can $_ *= 2 for @_; surprise the caller?

    @_ aliases the original arguments. Copy them with my (...) = @_ if you do not want to change the caller's data.
  4. 4. Which line enables signatures along with other modern features?

    use v5.36 (or later) turns on signatures, say and strict. use feature 'signatures' enables only that one feature.
  5. 5. What happens with sub two ($a, $b) {...} when you call two(1, 2, 3)?

    Signatures check the argument count, so extra arguments cause a fatal error.

Summary

  • Define subs with sub name { ... }; all arguments arrive in the array @_.
  • my ($a, $b) = @_; copies the arguments; the elements of @_ themselves are aliases of the caller's variables.
  • A sub returns the value of its last expression, or whatever return gives, including a list.
  • Signatures (sub f ($x, $y = 10, @rest)) name the parameters, check the count and support defaults.
  • wantarray tells a sub whether it is called in list, scalar or void context.

Next, learn how variables live and die in Scope, Closures and Recursion.