Re: Sum problem



Hey

problem with your for loop

#!/usr/bin/perl -w
while (<>) {
chomp;
($name,$value)=split(/\t/);
$ha{$name}+=$value;
}
foreach $i(sort keys %ha)
{
print$i." ".$ha{$i}."\n";
}

- Chandru

Andrej Kastrin wrote:
Dear Perl users,

I have 2 columns, tab separated file which looks like

A 4
B 3
C 1
A 3
B 3

First column refers to name and second to value. I have to calculate total score on each 'name'; in my case:
A 7
B 6
C 1

Here is the code; but it doesn't work.
#####################################
while (<>) {
chomp;
($name,$value)=split(/\t/);
$values{$name}+=$value;
}

foreach $w (sort by_number keys %values) {
print "$w\t$value{$w}\n"
}
#####################################

Thanks in advance for any suggestions or notes.

Andrej

.



Relevant Pages

  • chomp hash keys?
    ... According to perldoc -f chomp: ... The keys, of course, have linefeeds on the end, which I do not want. ... What is the best way to populate my hash with linefeed-ed data? ...
    (comp.lang.perl.misc)
  • Re: Problem with foreach
    ... Andrej Kastrin wrote: ... > Hello dears, ... how to modify my code; so if there are multiple same words ... chomp() is not really needed. ...
    (perl.beginners)