in reply to Looping and Grouping: there must be a better way!

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.