10.5. Passing Arrays and Hashes by Reference10.5.1. ProblemYou want to pass a function more than one array or hash and have each remain distinct. For example, you want to put the algorithm from Recipe 4.8 into a subroutine. This subroutine must then be called with two arrays that remain distinct. 10.5.2. SolutionPass arrays and hashes by reference, using the backslash operator: array_diff( \@array1, \@array2 ); 10.5.3. DiscussionSee Chapter 11 for more about manipulation of references. Here's a subroutine that expects array references, along with code to call it correctly:
A potential problem with this function is that it doesn't verify the number and types of arguments passed into it. You could check explicitly this way:
If all you plan to do is die on error (see Recipe 10.12), you can sometimes omit this check, since dereferencing the wrong kind of reference triggers an exception anyway. However, good defensive programming style encourages argument validation for all functions. 10.5.4. See AlsoThe sections on "Passing References" and on "Prototypes" in Chapter 6 of Programming Perl and on "Pass by Reference" in perlsub(1); Recipe 10.11; Chapter 11; Chapter 8 of Programming Perl
Copyright © 2003 O'Reilly & Associates. All rights reserved. |
|