Signatures and Return Values
Unpacking @_ by hand works, but modern Perl has a better way: subroutine signatures, which declare the parameters right after the sub name. Signatures became stable in Perl 5.36 and are enabled by use v5.36; (or later) or by use feature 'signatures';.
use strict;
use warnings;
use feature 'signatures';
sub rectangle_area ($width, $height) {
return $width * $height;
}
print "Area: ", rectangle_area(4, 5), "\n";Area: 20
Tip:
use v5.36;(or any later version) turns onstrict,warnings,sayand signatures in one line. This course spells outuse strict; use warnings;so every example also works the classic way, but in your own modern codeuse v5.36;is a fine choice.
Arity is checked
With a signature, calling a sub with the wrong number of arguments is a run-time error, which catches many bugs early:
use strict;
use warnings;
use feature 'signatures';
sub full_name ($first, $last) { "$first $last" }
print full_name("Grace", "Hopper"), "\n";
print full_name("Grace"), "\n";Grace Hopper
Too few arguments for subroutine 'main::full_name' (got 1; expected 2) at /app/output.s line 8.
Default values
A parameter can have a default, used when the caller does not supply that argument. Since Perl 5.38, //= and ||= defaults also replace an undef or false argument:
use strict;
use warnings;
use feature 'signatures';
sub greet ($name, $greeting = "Hello") {
return "$greeting, $name!";
}
sub connect_to ($host, $port //= 443) {
return "connecting to $host:$port";
}
print greet("Lin"), "\n";
print greet("Lin", "Welcome"), "\n";
print connect_to("example.org"), "\n";
print connect_to("example.org", undef), "\n";
print connect_to("example.org", 8443), "\n";Hello, Lin!
Welcome, Lin!
connecting to example.org:443
connecting to example.org:443
connecting to example.org:8443
Slurpy parameters
A final array or hash parameter collects all remaining arguments ("slurps" them):
use strict;
use warnings;
use feature 'signatures';
sub log_message ($level, @parts) {
return uc($level) . ": " . join(" ", @parts);
}
sub configure ($name, %options) {
my @pairs = map { "$_=$options{$_}" } sort keys %options;
return "$name {" . join(", ", @pairs) . "}";
}
print log_message("warn", "disk", "almost", "full"), "\n";
print configure("server", port => 80, tls => "off"), "\n";WARN: disk almost full
server {port=80, tls=off}
A sigil with no name ($, @) accepts an argument and ignores it, which is useful for callbacks that receive more arguments than they need.
Returning lists and hashes
A sub can return any list. The caller decides how to receive it:
use strict;
use warnings;
use feature 'signatures';
sub stats (@values) {
my $n = @values;
my $sum = 0;
$sum += $_ for @values;
return (count => $n, sum => $sum, mean => $sum / $n);
}
my %s = stats(4, 8, 15, 16, 23, 42);
print "$_: $s{$_}\n" for sort keys %s;
my ($first_key) = stats(1, 2); # just the first returned item
print "First item returned: $first_key\n";count: 6
mean: 18
sum: 108
First item returned: count
Returning nothing and failure
A bare return; returns an empty list in list context and undef in scalar context. That is the safest way to say "no result", because return undef; would give a one-element list (which is true) in list context:
use strict;
use warnings;
use feature 'signatures';
sub find_user ($id) {
my %users = (1 => "root", 7 => "maya");
return $users{$id} if exists $users{$id};
return; # not found
}
for my $id (7, 3) {
my $name = find_user($id);
print "User $id: ", ($name // "not found"), "\n";
}
my @found = find_user(3);
print "List result has ", scalar(@found), " items\n";User 7: maya
User 3: not found
List result has 0 items
Test yourself
What happens when you call sub f ($x, $y) {...} as f(1)?
$yis set to undef silently- A run-time error: too few arguments
- A compile-time warning only
$ybecomes 1
In sub tag ($name, @rest), what is @rest?
- Always empty
- A slurpy parameter that collects the remaining arguments
- A syntax error
- A copy of
@_
Why is return; preferred over return undef; for 'no result'?
- It is shorter
- In list context
return undefgives a one-element list, which is true return undefis a syntax error- They are always identical