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
greetunpacks@_into named lexicals;//=fills in a default when no greeting came.totalnever unpacks at all — it loops straight over@_, so any number of arguments works.- Call with one argument or two; the sub decides what the extras mean.
Keywords and builtins used here
forgreetmyprintreturnsubtotaluse
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.
Step 1 of 3 in Subroutines, step 16 of 27 in Language basics.