-1

I have two files with the same number of lines, each containing columns of numeric values.

Example of file A

1 2 3 4
2 3 4 5

Example of file B

7 8 9 0
6 7 8 9

I want to sum the value of corresponding lines from both of these files, and write the results to an output file.

The expected output:

8 10 12 4
8 10 12 14
ali_m
  • 71,714
  • 23
  • 223
  • 298
lolibility
  • 2,187
  • 6
  • 25
  • 45
  • For reading from two files at once, see http://stackoverflow.com/questions/2498937/how-can-i-walk-through-two-files-simultaneously-in-perl, http://stackoverflow.com/questions/11455627/in-perl-how-can-i-read-from-multiple-filehandles-in-one-loop, http://www.perlmonks.org/?node_id=762634, http://stackoverflow.com/questions/14670005/read-multiple-files-using-one-loop-perl?rq=1 – ThisSuitIsBlackNot Aug 08 '13 at 15:24

2 Answers2

5

You could easily do something like..

while ( not eof $fh1 and not eof $fh2 ) {
   my @vals1 = split /\s+/, <$fh1>;
   my @vals2 = split /\s+/, <$fh2>;

   my @sums = join ' ', map {$vals1[$_] + $vals2[$_]} 0 .. $#vals1;

   print $out $_ for @sums, "\n";
}

Output:

8 10 12 4
8 10 12 14
hwnd
  • 69,796
  • 4
  • 95
  • 132
  • 1
    I like your version more than mine :) I edited my answer to point to yours in case of future reference. – mamod Aug 09 '13 at 23:56
2

considering 2 files has the same number of lines and fields

use strict;
use warnings;
use Data::Dumper;

#first data file
open my $fh1, '<', '1.txt' or die $!;

#seecond data file
open my $fh2, '<', '2.txt' or die $!;

#output file
open my $out, '>', 'out.txt' or die $!;

while (!eof($fh1) and !eof($fh2)) {
    my $line1 = <$fh1>;
    my $line2 = <$fh2>;

    my @l1 = split /\s+/, $line1;
    my @l2 = split /\s+/, $line2;

    my @newvalues;

    my $i = 0;
    for (@l1){
        push @newvalues, $_ + $l2[$i];
        $i++;
    }

    print Dumper \@newvalues;

    my $new = join ' ', @newvalues;
    print $out $new."\n";
}

## EDIT ##

see @hwnd version below for a cleaner and more compact code on how to solve this problem

mamod
  • 504
  • 3
  • 6