in reply to Messing about in Arrays of Hashes
Any time you need to want to eliminate duplicates, think "hash". The following code creates a hash of hashes where the keys are id_a, summing value_x and value_y as it goes. Then the array of hashes is updated using the data in the HoH, sorted by id_a.
my %HoH; foreach my $hashref ( @AoH ) { $HoH{ ${ $hashref }{id_a} }{id_a} = ${ $hashref }{id_a}; $HoH{ ${ $hashref }{id_a} }{id_b} = ${ $hashref }{id_b}; $HoH{ ${ $hashref }{id_a} }{value_x} += ${ $hashref }{value_x}; $HoH{ ${ $hashref }{id_a} }{value_y} += ${ $hashref }{value_y}; } @AoH = sort { ${ $a }{id_a} <=> ${ $b }{id_a} } ( values %HoH );
This has been tested using your input data. I'm sure there are much more elegant ways of doing this...
HTH
Update: Added code below to meet your new criteria, as stated in this reply. The final array is still sorted on id_a. Note: since id_a and id_b are part of the hash key, you could eliminate those individual keys in the HoH, but I left them in for simplicity.
my %HoH; foreach my $hashref ( @AoH ) { my $id_ab = ${ $hashref }{id_a} . '_' . ${ $hashref }{id_b}; $HoH{$id_ab}{id_a} = ${ $hashref }{id_a}; $HoH{$id_ab}{id_b} = ${ $hashref }{id_b}; $HoH{$id_ab}{value_x} += ${ $hashref }{value_x}; $HoH{$id_ab}{value_y} += ${ $hashref }{value_y}; } @AoH = sort { ${ $a }{id_a} <=> ${ $b }{id_a} } ( values %HoH );
|
|---|