in reply to Re^6: Hash of Hashes from file
in thread Hash of Hashes from file
If your data looks like this:
Then try something like this (untested):%hoh = ( user1 => { Website => ['website1', 'website2', 'website3'], type => ['type1','type2','type3'], }, user2 => { Website => ['website1', 'website2', 'website3'], type => ['type1','type2','type3'], }, user3 => { Website => ['website1', 'website2', 'website3'], type => ['type1','type2','type3'], }, );
for my $user (sort keys %hoh) { my @websites = @{ $hoh{$user}{'Website'} }; my @types = @{ $hoh{$user}{'type'} }; # assume we have the same number of each? unless (scalar(@websites) == scalar(@types)) { die "number of websites is different from number of types!"; } print "$user :\n"; for ( my $i=0; $i < scalar(@websites); ++$i) { print " $websites[$i]\n"; print " $types[$i]\n"; } print "\n"; }
However, if you go with data like this:
Then your code becomes (untested):%hoh = ( # actually now a hash of arrays of hashes (HoAoH) user1 => [ { Website => 'website1', type => 'type1',}, { Website => 'website2', type => 'type2',}, { Website => 'website3', type => 'type3',}, ], user2 => [ { Website => 'website1', type => 'type1',}, { Website => 'website2', type => 'type2',}, { Website => 'website3', type => 'type3',}, ], user3 => [ { Website => 'website1', type => 'type1',}, { Website => 'website2', type => 'type2',}, { Website => 'website3', type => 'type3',}, ], );
for my $user (sort keys %hoh) { print "$user :\n"; # each element of this array is a hash ref for my $data ( @{ %hoh{$user} } ) { print " $data->{'Website'}\n"; print " $data->{'type'}\n"; } print "\n"; }
So, depending on what you need to do, pick the data structure that makes your life easier.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^8: Hash of Hashes from file
by cipher (Acolyte) on Apr 05, 2012 at 00:53 UTC |
In Section
Seekers of Perl Wisdom