develooper Front page | perl.beginners | Postings from April 2007

Re: How to sum up values

Thread Previous | Thread Next
From:
Rob Dixon
Date:
April 24, 2007 10:07
Subject:
Re: How to sum up values
Message ID:
462E393F.9010301@350.com
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

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About