Skip to content
Subroutines
step 1/5

Reading — step 1 of 5

Learn

~2 min readControl Flow and Subroutines

Define a subroutine with sub. Arguments arrive in the special array @_:

use strict;
use warnings;

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

print greet("Ada"), "\n";

Multiple arguments — list-flatten into @_:

sub add {
    my ($a, $b) = @_;
    return $a + $b;
}

Variable args — leftover items stay in @_:

sub sum_all {
    my $total = 0;
    $total += $_ for @_;
    return $total;
}
print sum_all(1, 2, 3, 4);   # 10

Lists are flattened — calling sum(@a, @b) passes all elements of both:

my @a = (1, 2);
my @b = (3, 4);
sum_all(@a, @b);              # called with (1, 2, 3, 4)

To pass an array as one argument, pass a reference:

sub avg {
    my ($aref) = @_;
    my $sum = 0;
    $sum += $_ for @$aref;
    return $sum / scalar @$aref;
}
avg(\@nums);

Named arguments via hash:

sub create_user {
    my %args = @_;
    return { name => $args{name}, age => $args{age} // 0 };
}
my $u = create_user(name => "Ada", age => 36);

This is THE Perl idiom for many-argument calls. Declared (name => ..., age => ...) flattens into pairs that fill %args.

Return values:

  • return $x — returns one scalar
  • return @x — returns a list
  • return ($x, $y, $z) — multiple return values, deconstruct on caller side:
sub divmod {
    my ($a, $b) = @_;
    return (int($a / $b), $a % $b);
}
my ($quot, $rem) = divmod(17, 5);    # 3, 2

Without return — last expression's value is returned:

sub square { $_[0] ** 2 }   # implicit return

Forward declarations with sub name; — required if you use the function before defining it (rarely needed in modern code).

wantarray — detect calling context:

sub flexible {
    if (wantarray()) {
        return (1, 2, 3);     # list context
    } else {
        return 3;              # scalar context
    }
}

my @list = flexible();         # (1, 2, 3)
my $scalar = flexible();       # 3

Clever — and confusing. Most modern code avoids context-dependent returns.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…