user324 user324 - 5 months ago 20
Perl Question

Perl : Adding 2 files line by line

I am a beginner in perl, so please bear with me.

I have 2 files:

1
2
3


and

2
4
5
6


I want to create a new file that is the sum of the above 2 files:

output file:

3
6
8
6


What I am doing right now is reading the files as arrays and adding them element by element.

To add the arrays I am using the following:

$asum[@asum] = $array1[@asum] + $array2[@asum] while defined $array1[@asum] or defined $array2[@asum];


But this is giving the following error:

Argument "M-oM-;M-?3" isn't numeric in addition (+) at perl_ii.pl line 30.
Argument "M-oM-;M-?1" isn't numeric in addition (+) at perl_ii.pl line 30.
Use of uninitialized value in addition (+) at perl_ii.pl line 30.


I am using the following code to read files as arrays:

use strict;
use warnings;

my @array1;
open(my $fh, "<", "file1.txt") or die "Failed to open file1\n";
while(<$fh>) {
chomp;
push @array1, $_;
}
close $fh;

my @array2;
open(my $fh1, "<", "file2.txt") or die "Failed to open file2\n";
while(<$fh1>) {
chomp;
push @array2, $_;
}
close $fh1 ;


Anyone could tell me how to fix this, or give a better approach altogether?

Answer

You have two different problems with your script now:

  1. First error

Argument "M-oM-;M-?3" isn't numeric in addition (+) at perl_ii.pl line 30

happens because your input files are saved in Unicode and first line is read with "\xFF\xFE" BOM bytes. Too fix it simply, just resave the files as ANSI text. If Unicode is required, then remove these bytes from first string you read from file.

  1. Second error

Use of uninitialized value in addition (+) at perl_ii.pl line 30.

happens because you access 4th element in first array that doesn't exist. Remember, you select maximal input array length as index limit. To fix it just add following condition for input element:

$asum[@asum] = (@asum < @array1 ? $array1[@asum] : 0)  + (@asum < @array2 ? $array2[@asum] : 0) while defined $array1[@asum] or defined $array2[@asum];