home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Perl CookbookPerl CookbookSearch this book

10.5. Passing Arrays and Hashes by Reference

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.



Library Navigation Links

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