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

Hi monks,

I can't find anywhere that tells me how to print the key-value pairs of a hash with multiple values per key. Could someone please help?

This is my attempt below, it prints the keys fine but the values as array references - ARRAY(0x922dc34).

my %hash = map { ($a_v_d_D[$_] => [$isect2[$_], $a_v_b_B[$_], $a_v_c_C +[$_]]) } 0..$#a_v_d_D; while (my ($key, $value) = each (%hash)) { for (my $i=0; $i<@CD_new_a_v_d_D; $i++) { if ($key eq $CD_new_a_v_d_D[$i]) { print "$key - $value\n"; } } }

Replies are listed 'Best First'.
Re: printing hashes with multiple values
by Corion (Patriarch) on Oct 20, 2005 at 09:14 UTC
Re: printing hashes with multiple values
by blazar (Canon) on Oct 20, 2005 at 10:27 UTC
    You can print "@{$value}" or if you just want to give a peek into your data structure, you can ask Data::Dumper to help you:
    print Dumper \%hash;
Re: printing hashes with multiple values
by revdiablo (Prior) on Oct 20, 2005 at 15:00 UTC

    Other Monks have responded to your question, but I can't help but comment on this code:

    for (my $i=0; $i<@CD_new_a_v_d_D; $i++) { if ($key eq $CD_new_a_v_d_D[$i]) { print "$key - $value\n"; } }

    In Perl land, we usually avoid that type of for loop. We have alternatives that have much less visual noise. If all you need to see are the values from the array, it's as simple as:

    for (@CD_new_a_v_d_D) { if ($key eq $_) { print "$key - $value\n"; } }

    In the rare cases where you still need access to the array indexes as you are iterating, you can use the range operator:

    for (0 .. $#CD_new_a_v_d_D) { if ($key eq $CD_new_a_v_d_D[$_]) { print "$key - $value (at $_)\n"; } }
Re: printing hashes with multiple values
by zentara (Cardinal) on Oct 20, 2005 at 16:02 UTC
    In case you need an example, this snippet shows the basics, you can easily test for

    if (ref $_ eq 'ARRAY')

    #!/usr/bin/perl %CARD_DATA = ( CARDS => { AX => { name => "American Express", valid_card => "true", fee_code => "1", currency => {US=>'1',CA=>'2',GB=>'3'}, misc_data => [], }, DI => { name => "Diners Club", valid_card => "false", fee_code => "", currency => {US=>'1',CA=>'2',GB=>'3'}, misc_data => ["CVV=4"], }, DS => { name => "Discover", valid_card => "false", fee_code => "", currency => {US=>'1',CA=>'2',GB=>'3'}, misc_data => [], } } ); my $depth = 0; print_keys( \%CARD_DATA ); sub print_keys { my $href = shift; $depth++; foreach ( keys %$href ) { print ' ' x $depth, "--$_\n"; print_keys( $href->{$_} ) if ref $href->{$_} eq 'HASH'; } $depth--; }