use Modern::Perl; use Data::Dump qw/dump/; my %seen; my %accounts; my $g_total; while (<DATA>) { next if $seen{$_}++; my ( $account_number, $amount ) = ( split /,/ )[ 2, 7 ]; @{ $accounts{$account_number} }[0] += $amount; @{ $accounts{$account_number} }[1]++; $g_total += $amount; } say dump( \%accounts ); say "Grand Total = $g_total"; __DATA__ Joe Smith,12345678,44552,02/11/2011,no email, MA,USA,900.00,updated Joe Smith,12345678,44552,02/11/2011,no email, MA,USA,900.00,updated Joe Smith,12345678,44552,02/11/2011,no email, MA,USA,900.00,updated Cindy Abbot,122233678,01122,08/09/2012,test@tok.com, CA,EUR,-120.00,up +dated Mary Lou,33456678,44552,01/11/2011,no email, MA,USA,400.00,updated SMith Doo,12345678,44592,02/11/2012,test@test.com, MA,USA,100.00,updat +ed Mario Att,00056789,022345,03/10/2010,no email, MA,USA,40.00,outdated Mario Att,00056789,022345,03/10/2010,no email, MA,USA,40.00,outdated Mario Att,00056789,022345,03/10/2010,ok@ok.com, MA,USA,40.00,outdated Maria Smither,12345678,00051,02/11/2011,no email, MA,USA,750.00,outdat +ed Dan Smither,12345678,00051,02/11/2011,no email, MA,USA,250.00,outdated
Output:
{ "00051" => [1000, 2], "01122" => [-120, 1], "022345" => [80, 2], "44552" => [1300, 2], "44592" => [100, 1], } Grand Total = 2360
The hash %accounts hold the accountnumber as key and each value is a reference to an array containing the total for that account and the number of times the accountnumber was found in the data.
CountZero
A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James
My blog: Imperial DeltronicsIn reply to Re: Counting how many times item is occurring and adding the total from array help!
by CountZero
in thread Counting how many times item is occurring and adding the total from array help!
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |