Arguments
That subroutine called larger_of_fred_or_barney would be much more
useful if it didn’t force you to use the global variables $fred and $barney. If you wanted to get the larger value
from $wilma and $betty, you currently have to copy those into
$fred and $barney before you can use larger_of_fred_or_barney. And if you had
something useful in those variables, you’d have to first copy those to
other variables, say $save_fred and
$save_barney. And then, when you’re
done with the subroutine, you’d have to copy those back to $fred and $barney again.
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
The list is passed to the subroutine; that
is, it’s made available for the subroutine to use however it needs to.
Of course, you have to store this list somewhere, so Perl automatically
stores the parameter list (another name for the argument list) in the
special array variable named @_ for the duration of
the subroutine. The subroutine can access this variable to determine
both the number of arguments and the value of those arguments.
This 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 ...