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{$groupID} ); 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 group, then: push @return_array, $header_rec, @{$complete_list{$groupID}}; } return \@return_array;