in reply to Group by from array
use strict; use warnings; use Data::Dump qw(pp); use constant { "AcctName" => 0, "EntityName" => 1, "UnitName" => 2}; my @array = ( ['Account01', 'Entity01', 'Unit01', 1, 2, +3], ['Account01', 'Entity01', 'Unit01', 4, 5, +6], ['Account02', 'Entity02', 'Unit02', 10, 11, + 12], ['Account01', 'Entity01', 'Unit01', 7, 8, +9] ); @array = sort {$a->[AcctName] cmp $b->[AcctName] or $a->[EntityName] cmp $b->[EntityName] or $a->[UnitName] cmp $b->[UnitName] }@array; pp \@array; die "input array too small!!" unless @array>=2; my $firstRowRef = shift @array; my @startRow = @$firstRowRef; foreach my $row_ref (@array) { my @curRow = @$row_ref; if ($curRow[0] ne $startRow[0] or $curRow[1] ne $startRow[1] or $curRow[2] ne $startRow[2] ) { print "@startRow\n"; # new grouping @startRow = @curRow; } else # group continuation { # add current month #'s to totals $startRow[3]+=$curRow[3]; $startRow[4]+=$curRow[4]; $startRow[5]+=$curRow[5]; } } print "@startRow\n"; # This is for the last row of array __END__ sorted array is: [ ["Account01", "Entity01", "Unit01", 1, 2, 3], ["Account01", "Entity01", "Unit01", 4, 5, 6], ["Account01", "Entity01", "Unit01", 7, 8, 9], ["Account02", "Entity02", "Unit02", 10, 11, 12], ] Account01 Entity01 Unit01 12 15 18 Account02 Entity02 Unit02 10 11 12
|
|---|