@_
was a very useful feature, since it allowed us to call a
function which operates on multiple values by either passing those values as a list,
or simply passing them individually. When you really do want to pass an array to
a function, however, this collapsing can prove very frustrating.
In the special case where you wish to pass a number of scalars and exactly one
array to a function, you can take advantage of a property we first saw in
Section 2.4. When you ``unroll'' an array into a literal list,
if a member of the literal list is an array, it will grab all the remaining elements
from the original array. By extracting the arguments from @_
into a call to
my
, we can pass exactly one array, given as the final argument, into our
function. (For the ``official'' way of passing multiple arguments, using
references, see the next section.)
Suppose we wish to write a program that will take as its arguments a tax rate and an array of prices, and which will return an array of taxes corresponding to the prices. By making the tax rate the first argument to the function, we can use the technique outlined above to catch the remaining arguments into an array.
sub do_taxes{ my($rate,@prices) = @_; my(@taxes); foreach $p (@prices){ push(@taxes,$p * $rate); } return(@taxes); }