TExcelTAD
Home › Perl › Subroutines and @_

Subroutines and @_

A subroutine (a "sub", Perl's word for a function) packages code under a name so you can reuse it. Define one with sub NAME { ... } and call it with NAME(...).

perl · try it yourself
use strict;
use warnings;

sub greet {
    print "Hello from a subroutine!\n";
}

greet();
greet();
Hello from a subroutine!
Hello from a subroutine!

Subs can be defined anywhere in the file, before or after the calls. Calling with parentheses always works; that is the modern style.

Arguments arrive in @_

Classic Perl subs have no parameter list. All arguments are passed in the special array @_, and the sub copies them into named variables, usually on the first line:

perl · try it yourself
use strict;
use warnings;

sub describe_pet {
    my ($name, $species, $age) = @_;
    return "$name is a $age-year-old $species";
}

sub area {
    my $width  = shift;     # shift with no array uses @_ inside a sub
    my $height = shift;
    return $width * $height;
}

print describe_pet("Rex", "dog", 4), "\n";
print "Area: ", area(3, 7), "\n";
Rex is a 4-year-old dog
Area: 21

Both styles are common: my (...) = @_; for several arguments, my $x = shift; for one or two. The next lesson shows signatures, the modern alternative.

Return values

return gives back a value (or a list) and ends the sub. Without return, a sub returns the value of the last expression it evaluated:

perl · try it yourself
use strict;
use warnings;

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

sub square { $_[0] ** 2 }               # implicit return of the last expression

my ($lo, $hi) = min_max(42, 7, 19, 88, 3);
print "min=$lo max=$hi\n";
print "square(9) = ", square(9), "\n";
min=3 max=88
square(9) = 81

$_[0] is the first element of @_ (nothing to do with $_).

Lists flatten into @_

All arguments are flattened into one list. If you pass two arrays, the sub cannot tell where the first one ends:

perl · try it yourself
use strict;
use warnings;

sub count_args { return scalar @_ }

my @front = (1, 2, 3);
my @back  = (4, 5);
print "Arguments received: ", count_args(@front, @back), "\n";

sub total {
    my $sum = 0;
    $sum += $_ for @_;
    return $sum;
}
print "Total: ", total(@front, @back, 10), "\n";
Arguments received: 5
Total: 25

Flattening is great for subs like total that take "a list of numbers". To pass two separate arrays, pass references to them (see the references lesson).

@_ is aliased

The elements of @_ are aliases to the caller's variables. Modifying $_[0] changes the caller's value, which is why subs copy their arguments into my variables first:

perl · try it yourself
use strict;
use warnings;

sub shout_in_place { $_[0] = uc $_[0] }
sub shout_copy     { my ($s) = @_; $s = uc $s; return $s }

my $word = "quiet";
my $loud = shout_copy($word);
print "copy:     $word -> $loud\n";

shout_in_place($word);
print "in place: $word\n";
copy:     quiet -> QUIET
in place: QUIET

Named arguments with a hash

For subs with many options, pass key/value pairs and collect them into a hash. Callers can then give the options in any order, and defaults are easy:

perl · try it yourself
use strict;
use warnings;

sub make_button {
    my %opt = (color => "grey", size => "medium", @_);   # defaults first
    return "[$opt{label}: $opt{color}, $opt{size}]";
}

print make_button(label => "OK"), "\n";
print make_button(label => "Delete", color => "red"), "\n";
print make_button(size => "small", label => "Help"), "\n";
[OK: grey, medium]
[Delete: red, medium]
[Help: grey, small]

The defaults come first in the list, so any keys the caller passes override them.

Recursion

A sub can call itself. Each call has its own my variables:

perl · try it yourself
use strict;
use warnings;

sub factorial {
    my ($n) = @_;
    return $n <= 1 ? 1 : $n * factorial($n - 1);
}

print "$_! = ", factorial($_), "\n" for 1 .. 6;
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720

Test yourself

Where does a classic Perl sub find its arguments?

  1. In $_
  2. In @ARGV
  3. In @_
  4. In %ENV

What does a sub return if it has no return statement?

  1. Always undef
  2. The value of the last evaluated expression
  3. 0
  4. It is a compile error

Why do subs usually start with my ($x, $y) = @_;?

  1. It is required syntax
  2. To get named, independent copies instead of aliases to the caller's variables
  3. To make the sub faster
  4. To declare the return type