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

I have a script that is reading in a two-column tab-delimited file. The first column of this file has what I will use as a key for my hash of arrays, and it is repeated many times in the file with different corresponding values, that will go into the arrays in this hash of arrays. Therefore the input file looks like:
A    1
A    2
B    4
B    6
and so on. I want my output to be something like <key><value><value> etc... for each key.
So I read the input file into a hash of arrays, being $index{$entry}
using the command
 push @{$index{$entry}}, "$value"
to do this, with $value being the value of the second column from the input file
What is the correct syntax to print an entrie array from the hash? I've tried
$index{$entry}
@{$index{$entry}}
amongst others, and I don't get what I'm expecting. Anybody have a good way to get this out?
thanks

Replies are listed 'Best First'.
Re: Printing hashes of arrays
by jeffa (Bishop) on Feb 13, 2004 at 21:04 UTC
    How about this?
    use strict; use warnings; use Data::Dumper;; my %hash = ( A => [1,2], B => [4,6], ); # just to see what we have print Dumper \%hash; # and this prints what you want (i think) print "$_ => @{ $hash{$_} }\n" for sort keys %hash;
    I always bring Data::Dumper along for the ride when i deal with complex data structures such as this.

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    
Re: Printing hashes of arrays
by NetWallah (Canon) on Feb 13, 2004 at 22:37 UTC
    Printing the hash values could be simplified thus:
    my %hash = ( A => [1,2], B => [4,6]); while (my ($k,$v)=each %hash){ print qq ($k: @$v\n) } -- Output--- A: 1 2 B: 4 6
    UPDATE:If you want it sorted, here is the code:
    my %hash = ( S => [1,2], B => [4,6],); print qq($_: @{$hash{$_}}\n) for sort keys %hash; --output--(Notice, it IS sorted)-- B: 4 6 S: 1 2
    "When you are faced with a dilemma, might as well make dilemmanade. "
Re: Printing hashes of arrays
by Taulmarill (Deacon) on Feb 13, 2004 at 21:11 UTC
    my %index = ( A => [1,2], B => [4,6], ); foreach my $entry ( sort keys %index ) { print $entry . ":"; foreach my $value ( @{$index{$entry}} ) { print " " . $value; } print "\n"; }
Re: Printing hashes of arrays
by Not_a_Number (Prior) on Feb 14, 2004 at 20:52 UTC

    Just to add some recommended reading:

    perldoc perlreftut
    perldoc perldsc

    dave