Subroutines
A subroutine is declared with sub and a name. Arguments aren't named parameters the way most languages here declare them — every call's arguments arrive flattened into the special array @_, and the subroutine body unpacks whatever it needs out of @_ itself, almost always on the very first line with my (...) = @_;.
use strict;
use warnings;
sub greet {
my ($name, $greeting) = @_;
$greeting //= "Hello";
return "$greeting, $name!";
}
print greet("World"), "\n";
print greet("Perl", "Hi"), "\n";
Hello, World! Hi, Perl!
//= is the defined-or assignment operator — it assigns only if the left side is currently undef, which is exactly how greet("World") gets a default greeting of "Hello" when no second argument was passed; $greeting simply never received a value from @_, so it's undef until //= fills it in.
return can hand back a list, not just a single scalar — and, following the same context rules from the previous lesson, the caller decides how many of those values it actually wants by how it assigns the result.
use strict;
use warnings;
sub stats {
my @nums = @_;
my $sum = 0;
$sum += $_ for @nums;
my $avg = $sum / scalar(@nums);
return ($sum, $avg);
}
my ($total, $average) = stats(2, 4, 6, 8);
print "Sum: $total, Average: $average\n";
Sum: 20, Average: 5
$sum += $_ for @nums; is a postfix for loop — for each element of @nums, $_ (Perl's default variable) is set to that element for the duration of the statement. Next: regular expressions — Perl's defining strength, built directly into the language's own syntax.
Practice exercise
Write sub add { my ($a, $b) = @_; return $a + $b; }, then print add(15, 27).