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

Hi monks

How do we access hash of array in a subroutine sent as reference. Is it something like this

sub foo (){ my $hash_ref = shift; foreach my $key (keys %$hash_ref){ foreach my $val(@${$$hash_ref{$key}}){ print $val . "\n"; } } }
Regards
Sid

Janitored by Arunbear - added code tags, as per Monastery guidelines

Replies are listed 'Best First'.
Re: Hashes of arrays problem
by reneeb (Chaplain) on Apr 13, 2005 at 15:26 UTC
    sub foo{ my $hashref = shift; foreach my $key(%$hashref){ foreach my $val(@{$hashref->{$key}}){ print $val,"\n"; } } }
Re: Hashes of arrays problem
by osunderdog (Deacon) on Apr 13, 2005 at 19:44 UTC

    Having parenthesis after the sub name:

    sub foo() { ... }

    Tells perl that you want to prototype the parameters that the subroutine will expect. In this case empty parens indicate that the funciton should not take any parameters.

    For example, the following code:

    use strict; sub foo() { my $param = shift; print "Param: [$param]\n"; } foo; foo(1);

    Will result in the following error:

    $perl proto.pl Too many arguments for main::foo at proto.pl line 11, near "1)" Execution of proto.pl aborted due to compilation errors.

    Line 11 is the function call foo(1);. It is an error because the prototype indicates that the function should not accept any parameters.

    This is discussed in:

    perldoc perlsub

    It's a pretty common mistake for those of us that came from the C/C++ world.


    "Look, Shiny Things!" is not a better business strategy than compatibility and reuse.

Re: Hashes of arrays problem
by sh1tn (Priest) on Apr 13, 2005 at 15:59 UTC
Re: Hashes of arrays problem
by tlm (Prior) on Apr 13, 2005 at 15:42 UTC

    You can simplify your code without sacrificing clarity like this:

    sub foo { my $hash_ref = shift; print "$_\n" for values %$hash_ref; }
    If you want to use both keys and values, you still can do it with a single loop:
    sub foo { my $hash_ref = shift; while ( my ( $key, $val ) = each %$hash_ref ) { # do something with $key and $val } }

    the lowliest monk