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


Perl CookbookPerl CookbookSearch this book

10.9. Returning More Than One Array or Hash

10.9.2. Solution

Return references to the hashes or arrays:

($array_ref, $hash_ref) = somefunc( );

sub somefunc {
    my @array;
    my %hash;

    # ...

    return ( \@array, \%hash );
}

10.9.3. Discussion

Just as all arguments collapse into one flat list of scalars, return values do, too. Functions that want to return multiple, distinct arrays or hashes need to return those by reference, and the caller must be prepared to receive references. If a function wants to return three separate hashes, for example, it should use one of the following:

sub fn { 
    .....
    return (\%a, \%b, \%c); # or                           
    return \(%a,  %b,  %c); # same thing
}

The caller must expect a list of hash references returned by the function. It cannot just assign to three hashes.

(%h0, %h1, %h2)  = fn( );    # WRONG!
@array_of_hashes = fn( );    # eg: $array_of_hashes[2]{"keystring"}
($r0, $r1, $r2)  = fn( );    # eg: $r2->{"keystring"}


Library Navigation Links

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