# Recipe 10.5 Passing Arrays and Hashes by Reference

#### 10.5.1 Problem

You 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 Solution

Pass arrays and hashes by reference, using the backslash operator:

`array_diff( \@array1, \@array2 );`

#### 10.5.3 Discussion

See Chapter 11 for more about manipulation of references. Here's a subroutine that expects array references, along with code to call it correctly:

```@a = (1, 2);
@b = (5, 8);
@c = add_vecpair( \@a, \@b );
print "@c\n";
6 10

sub add_vecpair {                      # assumes both vectors the same length
my (\$x, \$y) = @_;                  # copy in the array references
my @result;

for (my \$i=0; \$i < @\$x; \$i++) {
\$result[\$i] = \$x->[\$i] + \$y->[\$i];
}

return @result;
}```

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:

```unless (@_ =  = 2 && ref(\$x) eq 'ARRAY' && ref(\$y) eq 'ARRAY') {
}```

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.

The 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

 Chapter 1. Strings
 Chapter 2. Numbers
 Chapter 3. Dates and Times
 Chapter 4. Arrays
 Chapter 5. Hashes
 Chapter 6. Pattern Matching
 Chapter 7. File Access
 Chapter 8. File Contents
 Chapter 9. Directories
 Chapter 11. References and Records
 Chapter 12. Packages, Libraries, and Modules
 Chapter 13. Classes, Objects, and Ties
 Chapter 14. Database Access
 Chapter 15. Interactivity
 Chapter 16. Process Management and Communication
 Chapter 17. Sockets
 Chapter 18. Internet Services
 Chapter 19. CGI Programming
 Chapter 20. Web Automation
 Chapter 21. mod_perl
 Chapter 22. XML