typestar

Subroutines and @_ in Perl

The classic calling convention: every argument arrives in one flat array named @_.

use strict;
use warnings;

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

sub total {
    my $sum = 0;
    $sum += $_ for @_;
    return $sum;
}

print greet("Ada"), "\n";
print greet("Grace", "Welcome"), "\n";
print total(2, 3, 5), "\n";

How it works

  1. greet unpacks @_ into named lexicals; //= fills in a default when no greeting came.
  2. total never unpacks at all — it loops straight over @_, so any number of arguments works.
  3. Call with one argument or two; the sub decides what the extras mean.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
273
Tokens
84
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 67 seconds.

Type this snippet

Step 1 of 3 in Subroutines, step 16 of 27 in Language basics.

← Previous Next →