Subroutines

Define subroutines with sub and signatures, default arguments, returning lists, the older @_ style, and anonymous subs.

Runs in Zerethon IDE · Perl 5.40 Official Perl documentation ↗
main.pl
use v5.40;

sub greet ($name, $greeting = "Hello") {
    return "$greeting, $name!";
}

sub stats (@numbers) {
    my @sorted = sort { $a <=> $b } @numbers;
    my $sum = 0;
    $sum += $_ for @numbers;
    return ($sorted[0], $sorted[-1], $sum / @numbers);
}

sub old_style {
    my ($x, $y) = @_;
    return $x * $y;
}

say greet("Ada");
say greet("Linus", "Hi");
my ($low, $high, $mean) = stats(4, 8, 6);
say "$low $high $mean";
say old_style(6, 7);
my $square = sub ($x) { $x * $x };
say $square->(9);

Output

Hello, Ada!
Hi, Linus!
4 8 6
42
81
  • With use v5.40, a signature sub greet ($name, $greeting = "Hello") names the arguments and checks how many are passed.
  • Without a signature the arguments arrive in @_; my ($x, $y) = @_; is the classic way to read them, and you will see it in older code.
  • A sub can return a list; assign it to a list of variables to unpack it.
  • sort { $a <=> $b } sorts numbers; plain sort sorts as strings, so 10 comes before 9.