itzy
itzy

Reputation: 11765

Transfer array of hashes to hash of hashes in Perl

I have an array of hashes. I need to collect all hashes that meet some criterion into groups that can be processed one at a time. I thought a good way would be to look at each hash, determine which group it belongs to, and then add the hash to a new array.

I'm having some trouble figuring out what sort of data structure to use for this. An array of array of hashes? (So each group has an element of the parent array, and the child array holds the hashes.) Is there a more elegant way to do this with references?

My starting point is something like this:

foreach (@AoH) {
  my $group = int( $_->{'ID'} / 10 );

 ... need to collect the hash $_ with other hashes that have the same $group ...
}

Upvotes: 1

Views: 245

Answers (1)

Toto
Toto

Reputation: 91518

I'd use a hash of array of hash where the key is the group.

my %HoAoH;
foreach (@AoH) {
    my $group = int( $_->{'ID'} / 10 );
    push @{$HoAoH{$group}}, $_;
}

Upvotes: 3

Related Questions