10.1. Accessing Subroutine ArgumentsProblemYou have written a function and want to use the arguments supplied by its caller. Solution
All values passed as arguments to a function are in the special array For example: sub hypotenuse { return sqrt( ($_[0] ** 2) + ($_[1] ** 2) ); } $diag = hypotenuse(3,4); # $diag is 5 Your subroutines will almost always start by copying arguments into named private variables for safer and more convenient access: sub hypotenuse { my ($side1, $side2) = @_; return sqrt( ($side1 ** 2) + ($side2 ** 2) ); } Discussion
It's been said that programming has only three nice numbers: zero, one, and however many you please. Perl's subroutine mechanism was designed to facilitate writing functions with as many - or as few - elements in the parameter and return lists as you wish. All incoming parameters appear as separate scalar values in the special array
Here are some sample calls to the print hypotenuse(3, 4), "\n"; # prints 5 @a = (3, 4); print hypotenuse(@a), "\n"; # prints 5
If you look at the arguments used in the second call to @both = (@men, @women);
The scalars in So, we can write functions that leave their arguments intact, by copying the arguments to private variables like this: @nums = (1.4, 3.5, 6.7); @ints = int_all(@nums); # @nums unchanged sub int_all { my @retlist = @_; # make safe copy for return for my $n (@retlist) { $n = int($n) } return @retlist; } We can also write functions that change their caller's variables: @nums = (1.4, 3.5, 6.7); trunc_em(@nums); # @nums now (1,3,6) sub trunc_em { for (@_) { $_ = int($_) } # truncate each argument }
Don't pass constants to this kind of function, as in
The built-in functions $line = chomp(<>); # WRONG
until they get the hang of how it works. Given this vast potential for confusion, you might want to think twice before modifying See AlsoThe section on "Subroutines" in Chapter 2 of Programming Perl and perlsub (1) Copyright © 2002 O'Reilly & Associates. All rights reserved. |
|