I have a Perl question which should be fairly easy but can’t quite seem to get it correct I have a file that contains 2 columns of numbers, what I need to is to take the second column and add the first value in this column to the second, the second to the third the third to the fourth etc. I don’t know how many numbers will be in column 2 so I need to do this until the end of the file, I also want to be able to use these values further on in my program. I will give a dummy example below along with the code I have tried so far.
Example file tab delimited file data.txt
1 29
2 26
3 24
4 28
Example of desired out put
55
50
52
Code as is:
#!/usr/bin/perl -w
# use and library files
use strict;
use warnings;
my $line;
my $Val;
my $sum;
open(FH, "data.txt") or die $!;
while (my $line = <FH>){
my @val = split("\t", $line);
my $Val = $val[1];
my $sum = $Val+$Val;
print "$sum\n";
}
close FH;
The line $sum = $Val+$Val; needs to have some sort of loop so the correct values are being added but not sure how to get it right, and then I need to somehow assign the summed values variable names to use later.
Any help would be greatly appreciated
Thanks in advance
Sinead
You got it almost in your example.
$Valis your previous value. So you must not overwrite it before you used it in the $sum. This means swap these two lines and add the previous and the current value.One advice, try to give distinct names to variables. Differences in case only easily lead to confusion.
Here’s my version
and call it with