如何在Perl中的两个文件中连接相应的行?

时间:2010-04-15 13:48:42

标签: perl input

FILE1.TXT

hello
tom
well

FILE2.TXT

world
jerry
done

如何将file1.txt与file2.txt合并;然后创建一个新文件 - file3.txt

hello world
tom jerry
well done

感谢您的阅读和回复。

根据答案附上完整的代码。

#!/usr/bin/perl
use strict;
use warnings;

open(F1,"<","1.txt") or die "Cannot open file1:$!\n"; 
open(F2,"<","2.txt") or die "Cannot open file2:$!\n";
open (MYFILE, '>>3.txt');

while(<F1>){ 
  chomp; 
  chomp(my $f2=<F2>); 
  print MYFILE $_ . $f2 ."\n"; 
} 

2 个答案:

答案 0 :(得分:3)

如果Perl不是必须的,你可以在* nix上使用paste。如果您使用的是Windows,则还可以使用paste。只需从GNU win32

下载
$ paste file1 file2

其他,在Perl中

open(F1,"<","file1") or die "Cannot open file1:$!\n";
open(F2,"<","file2") or die "Cannot open file2:$!\n";
while(<F1>){
  chomp;
  chomp($f2=<F2>);
  print $_ . $f2 ."\n";
}

答案 1 :(得分:1)

我认为没有人应该为此给出完整的答案。

只需打开这两个文件,然后同时遍历两个文件并写出新文件。

如果你不知道如何在perl中读写文件,这里有一个教程:

http://perl.about.com/od/perltutorials/a/readwritefiles.htm