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 );

In reply to Re: Messing about in Arrays of Hashes by bobf
in thread Messing about in Arrays of Hashes by nzgrover

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.