my $groupby = 'id'; # field to group by my @outerfields = ('maker'); # outer loop fields my @innerfields = ('make'); # inner loop fields my $cars = &normalize(\@res, $groupby, \@outerfields, \@innerfields); $template->param(cars => $cars); # print it all print "Content-Type: text/html\n\n", $template->output; sub normalize($aref, $groupby, $outerfields, $innerfields) { my ($aref, $groupby, $outerfields, $innerfields) = @_; my @res = @$aref; my @outerfields = @$outerfields; my @innerfields = @$innerfields; my $seen = 0; # a flag to remember seen records my @temp; # a temp array to store outer loop fields my %makes; # a hash to store all the makes keyed by the groupby field # loop over the denormalized results foreach (@res) { # using the groupby field, test if the record has been seen... if ($_->{$groupby} != $seen) { # create a hash to store the outer loop fields, the car maker my %q; $q{$groupby} = $_->{$groupby}; foreach my $of (@outerfields) { $q{$of} = $_->{$of}; } # stuff the outer loop fields hash into the temp array push(@temp, \%q); # create a hash to store the inner loop fields, the car makes my %make; foreach my $if (@innerfields) { $make{$if} = $_->{$if}; } # add the inner loop fields hash to the makes hash keyed by the groupby field push(@{$makes{$_->{$groupby}}}, \%make); # update the flag $seen = $_->{$groupby}; # since the record has already been seen... } else { # create a hash to store the inner loop fields, the car makes my %make; foreach my $if (@innerfields) { $make{$if} = $_->{$if}; } # add the inner loop fields hash to the makes hash keyed by the groupby field push(@{$makes{$_->{$groupby}}}, \%make); } } my @cars; # an array to hold it all in its final form # loop over the temp array created above foreach (@temp) { # grab the makes for this maker using the groupby field and # add it to this row as an array of hashrefs $_->{'makes'} = $makes{$_->{$groupby}}; # add the entire row, a hashref, to the final array push(@cars, $_); } return \@cars; # return back to the code } #### .