Rob Dixon wrote:
> Andrej Kastrin wrote:
>> Dear all,
>>
>> Question about the sum function; the file structure is as follows:
>>
>> A|100
>> A|200
>> A|150
>> B|20
>> B|90
>> C|10
>> C|30
>> C|300
>>
>> The result I want to obtain is to sum values in the second column
>> (columnB) for each particular letter in the first column (ColumnA);
>> e.g.:
>>
>> A|450
>> B|100
>> C|330
>>
>> I don't want to use hash structure because the input file is very
>> large. Is there any simple way to do that step-by-step: to sum up
>> values in columnB until the letter in columnA changes and print the
>> result...
>>
>> Thanks in advance for any suggestion, Andrej
>>
>>
>> #!/usr/bin/perl
>> use strict;
>> use warnings;
>>
>> open FH1, "< test.txt" or die "Can't open file : $!";
>> while (<FH1>) {
>>    chomp;
>>    ($columnA,$columnB)=split /\|/;
>>    ... ???
>> }
>
> my ($label, $total);
>
> while (<FH1>) {
>  chomp;
>  my ($columnA,$columnB)=split /\|/;
>  
>  if ($label and $columnA ne $label) {
>    print "$label|$total\n";
>    $total = 0;
>  }
>
>  $label = $columnA;
>  $total += $columnB;
>
>  print "$label|$total\n" if eof;
> }
>
>
>
> HTH,
>
> Rob
>
It's was interesting to see some different solutions of the problem .
I was very usefull to me but i think that if data is in random order it
will not work in expected way.
Maybe I'm wrong.
Data :
A|100
B|20
A|200
A|150
B|20
B|90
C|10
C|30
C|300

Result:
A|100
B|20
A|350
B|110
C|340

Best Regards.




-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to