Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Group by from array

by Marshall (Canon)
on Sep 02, 2022 at 09:33 UTC ( [id://11146630]=note: print w/replies, xml ) Need Help??


in reply to Group by from array

This is one way to do it without a hash table. Your grouping constraints can be enforced by sorting the table. then roll through the table doing sums and printing every time the grouping changes.

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11146630]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (1)
As of 2024-04-25 03:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found