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. Then, when you’re done with the subroutine, you’d have to copy those back to $fred and $barney.
Luckily, Perl has subroutine arguments. To pass an argument list to the subroutine, 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 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 to do with the $_ variable, any more than $dino[3] (an element of the @dino array) has to do with $dino (a completely distinct ...
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