my %details_for = (); for (... [your loop beginning here] ...){ my $trans_details = $details_for{$comp_ident}; unless ($trans_details){ $trans_details = []; # first time for this company. # create its array of details. $details_for{$comp_ident} = $trans_details; } # Add to array of trans details for this company push @$trans_details, { company_ident => $comp_ident, company => $company, ... etc., debits => $debits, credits => $credits }; } # Ok, now you've accumulated the data print STDERR Dumper(\%details_for); # just for debugging. # Print the results: foreach my $comp_ident (keys %details_for){ my @trans_details = @{$details_for{$comp_ident}}; my $comp = $trans_details[0]->{'company'}; my $sumcredits += $_->{'credits'} for (@trans_details); # Show the total credits print $comp, "\t", $sumcredits, "\n"; foreach my $trans(@trans_details){ print " " x 3; # indent a little print "effective: ", $trans->{'effective_date'}; print ". created: ", $trans->{'date_created'}; # etc. print "\n"; } }