Perl CookbookPerl CookbookSearch this book

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') {
    die "usage: add_vecpair ARRAYREF1 ARRAYREF2";
}

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 Also

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



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.