views:

105

answers:

3

I have a data that comes in pair like this:

A: 100
B: 3.3
A: 210
B: 4.3

What I want to do with the code below is to sum value of each pairs:

my $aval = "";
my $bval = "";

while (<DATA>) {
    chomp;
    if (/^A/) {
        $aval = (split(" ",$_))[-1];
     }
     else {
        $bval = (split(" ",$_))[-1];
        my $total = $aval + $bval;
        print "$total\n"; 
    }
}

However the code above doesn't seem to do what I hope it does. Especially inside else the value of $aval is still empty.

Final result I hope to get is:

103.3
214.3

What's the right way to do it?

+3  A: 
#!/usr/bin/perl

use strict; use warnings;

my $aval = 0;

while ( <DATA> ) {
    if ( /^A: (\S+)/ ) {
        $aval = $1;
    }
    elsif ( /^B: (\S+)/ ) {
        print $aval + $1, "\n";
        $aval = 0;
    }
}

__DATA__
A: 100
B: 3.3
A: 210
B: 4.3
Sinan Ünür
A: 

#!/usr/bin/perl -w

my $aval = "";
my $bval = "";
my $total = "";

open(DATA,"<data") ;

while (<DATA>) {
    chomp;
        $num = (split(" ",$_))[1] ;
    if (/^A/)
    {
      $aval = $num ;
    }
    elsif (/^B/)
    {
      $bval = $num;
      $total = $aval + $bval;
      print "$total\n";
    }
    else
    {
       // can handle any other input
    }
}


Although using regular expressions to group numbers(as in Sinan's code) is better than using split .
Also,i find it better to use explicit index instead of "-1" for the last element

Neeraj
+2  A: 

Your code worked on my system, so I'm not sure what problem you were having.

Here's a different way to do it:

chomp(my @data = <DATA>);
s![a-z:\s]!!ig for @data;
print shift(@data) + shift(@data), "\n" while @data;

Or, it you don't want to do it destructively:

# Create @data as above.
my @sums;
$sums[int($_ / 2)] += $data[$_] for 0 .. $#data;
print $_, "\n" for @sums;
FM