blackjudas has asked for the wisdom of the Perl Monks concerning the following question:

Ok I've searched, Oreilly this site, the net etc. Maybe I haven't looked hard enough. I'm feeling quite idiotic asking this, but how do you successfully return a full array AND a hash at the same time froma sub-routine? Here's code.
sub get_stuff { # Chopped for brevity: return (@array, %hash); }
Now if I ask in the scalar context as such:

(@newarray, %newhash) = &get_stuff($filename)

@newarray contains both the array and hash I've passed from the original sub and %newhash is empty I understand what's wrong, I just don't understand where my syntax is flawed. Any help would be lovely.

Replies are listed 'Best First'.
Re: Returning Hashes
by lachoy (Parson) on Mar 31, 2001 at 03:25 UTC

    References are your friend:

    my ( $array, $hash ) = get_stuff(); foreach my $item ( @{ $array } ) { print "$item!\n"; } foreach my $key ( keys %{ $hash } ) { print "$key: $hash->{ $key }\n"; } ... sub get_stuff { ... return ( \@array, \%hash ); }

    Check out perldoc perlref for the straight dope.

    Chris
    M-x auto-bs-mode

Re: Returning Hashes
by stephen (Priest) on Mar 31, 2001 at 03:28 UTC
    You're going to need to use references.
    ## Note-- do not copy and paste! Read perlman:perlref. sub get_stuff { return (\@array, \%hash); } ($array_ref, $hash_ref) = get_stuff; @newarray = @$array_ref; %hash = %$hash;

    Or instead of doing the second copy, use the references as-is:

    ($array_ref, $hash_ref) = get_stuff; my $first_element = $array_ref->[0]; my $thingy = $hash_ref->{'thingy'};

    Read perlman:perlref.

    stephen

Re: Returning Hashes
by Anonymous Monk on Mar 31, 2001 at 04:04 UTC

    You can always do this in the subroutine as well as returning references.

    my @foo = (); my %bar = (); modify(\@foo, \%bar); print join(':', @foo),"\n"; print join(':', %bar),"\n"; sub modify { my($aref, $href) = @_; push @$aref, (1..10); @{$href}{(1..10)} = reverse (1..10); }