Hash array of arrays

cpeters5
cpeters5 used Ask the Experts™
on
I want to generate a hash array with array values from a file. Some example of rows
ATL 1 2 3
BOS 2 3 4 5
DFW 6 5 1 7 8
ATL 1 2

First field is alpha, and the rest are varied length of numeric fields.
The first field is not unique. If duplicate is found, I want to append the numeric fields to the previous values.
So the output would be, for instance

$myHash{ATL}[0] = 1
$myhash{ATL}[4] = 2.

Also, how do I access the results using foreach loop?

Thanks,
pax
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
use strict;
use warnings;
my $fil = shift or die "Usage: $0 input_file\n";
my %data;
# create the data
open IN, $fil or die "could not read $fil: $!";
while (<IN>) {
    chomp;
    my ($key, @vals) = split /\s+/;
    $data{$key} = [] unless $data{$key};
    push @{$data{$key}}, @vals;
}
close IN;
# access the data
foreach my $key (sort keys %data) {
    # could do something here with each arrayref
    foreach my $val (@{$data{$key}}) {
        # could do something here with each value
    }
}

Open in new window

Author

Commented:
Thanks

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial