Arguments in @_
| Unpack @_ | |
| Defaults | |
| It is an alias | |
| Named arguments |
Unpack @_
Every subroutine receives its arguments as one flat list in @_. Name them on the first line with a list assignment, which also documents the signature for the reader.
sub area {
my ($width, $height) = @_;
return $width * $height;
}
print area(3, 4), "\n"; # 12
perl demo.pl
12
Extra arguments are simply ignored, and missing ones arrive as undef. Perl does not check the count, so the subroutine has to. A guard at the top is worth more than a comment:
sub area {
my ($width, $height) = @_;
die "area needs two numbers\n" unless defined $height;
return $width * $height;
}
print area(3, 4), "\n"; # 12
print area(3), "\n"; # area needs two numbers
perl demo.pl
12
area needs two numbers
Defaults
A default value is a defined-or assignment after unpacking. Use //= rather than ||=, so a caller who passes 0 or an empty string keeps it.
sub greet {
my ($name) = @_;
$name //= "world";
return "hello, $name";
}
print greet(), "\n"; # hello, world
print greet(""), "\n"; # hello,
perl demo.pl
hello, world
hello,
It is an alias
The elements of @_ are aliases to the caller values. Changing $_[0] changes the variable that was passed, which is how some old functions return several results.
sub bump {
$_[0]++;
}
my $n = 1;
bump($n);
print "$n\n"; # 2
perl demo.pl
2
Copying into my variables, as every example above does, breaks the alias and protects the caller. Do that by default, and use the alias deliberately when you really want to modify in place.
Named arguments
Once a subroutine takes more than three arguments, positional order stops being memorable. Pass a flat list of key-value pairs instead and unpack it into a hash.
sub db_connect {
my %opt = @_;
return "$opt{host}:$opt{port}";
}
print db_connect(host => "db1", port => 5432), "\n";
perl demo.pl
db1:5432
The fat comma makes the call read like a table. Watch out for a hash argument passed unwrapped: a hash flattens into pairs, so wrap it in braces to pass a reference instead.
Next: References
Article author: Arthur Isaev