In addition to putting the complicated code blocks into subroutines, as suggested by hawtin (and as you said you would probably do -- yes you should do that), you might also consider using a more appropriate data structure -- perhaps a hash of arrays, where the "grouping ID" is the hash key, and each element of the hash is an array of records in that group.

That way, you don't need to keep track of when the grouping ID changes from one record to the next -- just determine what that ID is, use it as a hash key, and push the record (after doing all the complicated manipulations) onto the hash element:

my %complete_list; my @groupID_order; for my $rec ( @records ) { # do prep-work on $rec as needed to create returnable rec, then: my $groupID = $rec->{ID} push @groupID_order, $groupID unless exists( $complete_list{$group +ID} ); push @{$complete_list{$groupID}}, $usable_rec; } my @return_array; for my $groupID ( @groupID_order ) { # maybe you want to work on creating header stuff here for each gr +oup, then: push @return_array, $header_rec, @{$complete_list{$groupID}}; } return \@return_array;
That's just untested pseudo-code, of course, but in theory it should produce the same result as your original approach.

In reply to Re: Looping and Grouping: there must be a better way! by graff
in thread Looping and Grouping: there must be a better way! by edan

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.