Luckily, Perl has subroutine arguments. To pass an argument list to
the subroutine, simply place the list expression, in parentheses,
after the subroutine invocation, like this:
$n = &max(10, 15); # This sub call has two parameters
So, that means that the first subroutine parameter is stored in
$_[0], the second one is stored in
$_[1], and so on. But -- and here's an
important note -- these variables have nothing whatsoever to do
with the $_ variable, any more than
$dino[3] (an element of the
@dino array) has to do with
$dino (a completely distinct scalar variable).
It's just that the parameter list must be stored into some
array variable for the subroutine to use it, and Perl uses the array
@_ for this purpose.
Now, you could write the subroutine
&max to look a little like the subroutine
&larger_of_fred_or_barney, but instead of
using $a you could use the
first subroutine parameter ($_[0]), and instead of
using $b, you could use the
second subroutine parameter ($_[1]). And so you
could end up with code something like this:
sub max {
# Compare this to &larger_of_fred_or_barney
if ($_[0] > $_[1]) {
$_[0];
} else {
$_[1];
}
}
Well, as we said, you could do that. But
it's pretty ugly with all of those subscripts, and hard to
read, write, check, and debug, too. We'll see a better way in a
moment.
$n = &max(10, 15, 27); # Oops!
Excess parameters are ignored -- since the subroutine never looks
at $_[2], Perl doesn't care whether
there's something in there or not. And insufficient parameters
are also ignored -- you simply get undef if you
look beyond the end of the @_ array, as with any
other array. We'll see how to make a better
&max, which works with any number of
parameters, later in this chapter.