The following requires an additional hash and an additional array, but both contain only pointers, so overhead should be extremely low. Enjoy...
$var = [ { 'id_a' => '1', 'id_b' => '5', 'value_x' => '10', 'value_y' => '5' }, { 'id_a' => '2', 'id_b' => '3', 'value_x' => '20', 'value_y' => '10' }, { 'id_a' => '2', 'id_b' => '3', 'value_x' => '30', 'value_y' => '20' }, { 'id_a' => '3', 'id_b' => '7', 'value_x' => '15', 'value_y' => '15' }]; my ($id, %ids, @var2); for (my $i = 0; $i <= $#$var; $i++) { $id = @$var[$i]->{'id_a'} . ' ' . @$var[$i]->{'id_b'}; if (!$ids{$id}) { push(@var2, @$var[$i]); $ids{$id} = @$var[$i]; } else { $ids{$id}->{'value_x'} += @$var[$i]->{'value_x'}; $ids{$id}->{'value_y'} += @$var[$i]->{'value_y'}; } } $var = \@var2; foreach (@$var) { print '[' . $line++ . ']' . ' id_a -> ' . $_->{'id_a'} . ' id_b -> ' . $_->{'id_b'} . ' value_x -> ' . $_->{'value_x'} . ' value_y -> ' . $_->{'value_y'} . "\n"; }
You can cut the last part if you want - that's only to demonstrate that the code works.

In reply to Re: Messing about in Arrays of Hashes by TedPride
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.