new2perl2 has asked for the wisdom of the Perl Monks concerning the following question:
If i have data of format
name, amount
john, 100
john, 200
barry, 300
barry 200
how would i represent this data so i could iterate over the names and add the values so i would get output
john, 300
barry, 500
I have written code which will see if the names occur more than once but i can't work out how to sum the values for the names that appear more than once. I am very new to perl and know that a hash is required but hashes seem incompatible with my brain. I would appreciate it if someone could help with a simple explanation.
my %seen ; open(DATA, "<", "names.txt") or die "cannot open names.txt" ; while (<DATA>) { $line = $_ ; @array = split(/,/ , $line ) ; $name = $array[0] ; $amount = $array[1]; $seen{$name}++; if ( $seen{$name} > 1 ) { print "$name occurs more than onc +e" ; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: adding values of element
by NetWallah (Canon) on Jan 22, 2015 at 01:49 UTC | |
|
Re: adding values of element
by Anonymous Monk on Jan 21, 2015 at 22:51 UTC | |
by new2perl2 (Initiate) on Jan 21, 2015 at 23:09 UTC | |
by johngg (Canon) on Jan 21, 2015 at 23:58 UTC | |
by Anonymous Monk on Jan 22, 2015 at 00:35 UTC | |
by new2perl2 (Initiate) on Jan 22, 2015 at 00:16 UTC | |
by Anonymous Monk on Jan 22, 2015 at 00:42 UTC |