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

hello wise ones, I'm having a problem with hashes. I want to assing a array as the value of a hash. I can get the array in no problem but I'm having trouble with the syntax of how to loop through it and get the values back out. I pretty new to perl so I'm sure it's just some curly brace out of place or something equally simple. here's a snip of the code.
while ((my $key, my $value) = each %db_stru) { print "$key contains tables:\n"; foreach my $tbl ($db_stru{$key}) { print "\t$tbl:"; } print "\n"; }
earlier in the program I'm connecting to 'n' number of databases and listing the tables contained in each. I assign the result to an array and put it in a hash with the key being the db name. TIA, chrisj0

Replies are listed 'Best First'.
Re: help with a hash of arrays.
by kvale (Monsignor) on Mar 26, 2004 at 23:12 UTC
    You are close:
    while (my ($key, $value) = each %db_stru) { print "$key contains tables:\n"; foreach my $tbl (@$value) { print "\t$tbl:"; } print "\n"; }

    -Mark

Re: help with a hash of arrays.
by davido (Cardinal) on Mar 27, 2004 at 06:07 UTC
    Here's yet another way to do it...

    while( my( $key, $value ) = each %db_stru ) { print "$key contains tables:\n"; print "\t$_:" foreach @{$value}; }

    Then there's always the philosophy of 'print seldom, and print late.'

    while( my( $key, $value ) = each %db_stru ) { my $out = "$key contains tables:\n"; $out .= "\t$_:" foreach @{$value}; print "$out\n"; }

    And for those who like to use special variables instead of explicit loops:

    { local $" = ":\t"; while( my( $key, $value ) = each %db_stru ) { print "$key contains tables:\n\t@{$value}\n" } }

    Enjoy!


    Dave

Re: help with a hash of arrays.
by optimist (Beadle) on Mar 27, 2004 at 23:41 UTC
    Just to be sure, since you say you're new to perl...

    When you're putting the array values in, are you putting in a reference to the array? I.e., are you doing something like $db_stru{$db_name} = \@db_tables? If you aren't, it wouldn't break on the way in, but you'd find that the solutions given wouldn't appear to work.

    HTH,
    optimist