use strict;
use warnings;
use 5.020;
use autodie;
use Data::Dumper;
open my $FILE1, "<", "file1.txt";
open my $FILE2, "<", "file2.txt";
open my $OUTFILE, ">", "results.txt";
my $first_line = <$FILE1>;
close $FILE1;
my @line_prefixes = split /\s*:\s*/, $first_line;
while (my $line = <$FILE2>) {
print {$OUTFILE} "$line_prefixes[$. - 1]: $line";
}
close $FILE2;
close $OUTFILE;
$. is the current line number in the file ($. equals 1 for the first line).
A sample run:
/pperl_programs$ cat file1.txt
Total X : Total y : Total z : Total t :
~/pperl_programs$ cat file2.txt
4790351 4786929 3422 0
84860 84860 0 0
206626 206626 0 0
93902 93823 79 0
~/pperl_programs$ cat results.txt
~/pperl_programs$ perl myprog.pl
~/pperl_programs$ cat results.txt
Total X: 4790351 4786929 3422 0
Total y: 84860 84860 0 0
Total z: 206626 206626 0 0
Total t: 93902 93823 79 0
~/pperl_programs$
For your altered files:
use strict;
use warnings;
use 5.020;
use autodie;
use Data::Dumper;
open my $FILE1, "<", "file1.txt";
open my $FILE2, "<", "file2.txt";
open my $OUTFILE, ">", "results.txt";
chomp(my @line_prefixes = <$FILE1>);
close $FILE1;
while (my $line = <$FILE2>) {
print {$OUTFILE} "$line_prefixes[$.-1] $line";
}
close $FILE2;
close $OUTFILE;
Sample output:
~/pperl_programs$ cat file1.txt
Total X :
Total y :
Total z :
Total t :
~/pperl_programs$ cat file2.txt
4790351 4786929 3422 0
84860 84860 0 0
206626 206626 0 0
93902 93823 79 0
~/pperl_programs$ cat results.txt
~/pperl_programs$ perl 1.pl
~/pperl_programs$ cat results.txt
Total X : 4790351 4786929 3422 0
Total y : 84860 84860 0 0
Total z : 206626 206626 0 0
Total t : 93902 93823 79 0
If your files are big, you probably don't want to read the whole first file into memory. If that's the case, you can read each file line by line:
use strict;
use warnings;
use 5.020;
use autodie;
use Data::Dumper;
open my $FILE1, "<", "file1.txt";
open my $FILE2, "<", "file2.txt";
open my $OUTFILE, ">", "results.txt";
while (!eof($FILE1) and !eof($FILE2) ) {
my $line_prefix = <$FILE1>;
chomp $line_prefix;
my $numbers_line = <$FILE2>;
chomp $numbers_line;
my @numbers = split /\s+/, $numbers_line;
my $fifth_column = $numbers[1] / $numbers[0];
say {$OUTFILE} "$line_prefix $numbers_line $fifth_column";
}
close $FILE1;
close $FILE2;
close $OUTFILE;