I am trying to take an array of hashes and based on certain values within the hash add elements of the array together and then shrink the array. Here is what I have so far:
sub fold { my $self = shift; return if ! @{$self->{data}}; my $array = $self->{data}; my $date_grouped = 0; my $campaign_grouped = 0; foreach(@{$self->{groups}}) { $date_grouped = 1 if $_ eq 'date'; $campaign_grouped = 1 if $_ eq 'campaign'; } my $merge_index = 0; my $points_needed = $campaign_grouped + $date_grouped; @$array = sort {fold_sort($campaign_grouped,$date_grouped)} @$arra +y; for(my $current_index=0; $current_index<@$array; $current_index++) + { my $el = $array->[$current_index]; if($merge_index == $current_index) { next; } #compare current element to merge element my $match = 0; my $merge = $array->[$merge_index]; $match++ if $date_grouped && $el->{date} eq $merge->{date}; $match++ if $campaign_grouped && $el->{campaign_id} == $merge->{campaign_id}; #if we can fold the array elements then do so and remove the #current element if($match == $points_needed) { $merge->{views} += $el->{views}; $merge->{clicks} += $el->{clicks}; my $del = splice(@$array,$current_index,1); $current_index--; } else { $merge_index++; } } }
Anyone have a better way of doing this? The fold_sort function just orders the array based on how were are grouping the elements. Thanks, Kenny

PS - I was not sure of what to call this so I figured "Array Folding" was a good enough term...if there is another term that people use let me know please :-)


In reply to Array Folding by BarMeister

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.