TExcelTAD
Home › Perl › Signatures and Return Values

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';.

perl · try it yourself
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 on strict, warnings, say and signatures in one line. This course spells out use strict; use warnings; so every example also works the classic way, but in your own modern code use 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:

perl · try it yourself
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:

perl · try it yourself
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):

perl · try it yourself
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:

perl · try it yourself
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:

perl · try it yourself
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)?

  1. $y is set to undef silently
  2. A run-time error: too few arguments
  3. A compile-time warning only
  4. $y becomes 1

In sub tag ($name, @rest), what is @rest?

  1. Always empty
  2. A slurpy parameter that collects the remaining arguments
  3. A syntax error
  4. A copy of @_

Why is return; preferred over return undef; for 'no result'?

  1. It is shorter
  2. In list context return undef gives a one-element list, which is true
  3. return undef is a syntax error
  4. They are always identical