Tricks with Parameter Lists
Perl does not yet have named formal parameters, but in practice all you do is
copy the values of @_ to a
my list, which serves nicely for
a list of formal parameters. (Not coincidentally, copying the values
changes the pass-by-reference semantics into pass by value, which is
how people usually expect parameters to work anyway, even if they
don’t know the fancy computer science terms for it.) Here’s a
typical example:
sub maysetenv {
my($key, $value) = @_;
$ENV{$key} = $value unless $ENV{$key};
}But you aren’t required to name your parameters, which is the
whole point of the @_ array. For
example, to calculate a maximum, you can just iterate over @_ directly:
sub max {
my $max = shift(@_);
for my $item (@_) {
$max = $item if $max < $item;
}
return $max;
}
$bestday = max($mon,$tue,$wed,$thu,$fri);Positional parameters work well for functions with short argument lists, but as the number of parameters increases, it becomes awkward to remember which argument does what, make some of them optional, or have default values. A more flexible approach that addresses all these issues has the caller supply arguments using pairs of parameter names and values. The first element of each pair is the argument name; the second, its value. This makes for self-documenting code because you can see the parameters’ intended meanings without having to read the full function definition. Even better, programmers using your function no longer have to remember the argument order, and ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access