如何在perl中用逗号分隔的单个列连接两个文件

时间:2013-09-29 23:22:53

标签: perl join

我有两个文件。

file1包含

abc
def
ghi 

在一列(3个单独的行)

file2包含

123
456
789 

(单列(3个单独的行)

我正在尝试将这两个文件中的值连接到一个新的逗号分隔文件中。我希望将一个文件中的所有值捕获到两个不同的数组中,并使用'join'命令来“加入”它们。但是在尝试将值捕获到数组中时遇到了几个错误。我尝试了几个while循环。但是他们所有人都遇到了一个错误或另一个错误。这是我最新的while循环

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

my $filename1 = "file1";
open ( my $fh , "<", $filename1) or die "Could not open '$filename1'\n";
while (1) {my $line = <$fh>} ;
my @name = $line ;
print @name;

我知道我应该可以使用bash使用简单的'join'命令来完成此操作。但我想学习如何在perl中执行此操作。

3 个答案:

答案 0 :(得分:0)

我假设file1的行数与file2相同。

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

open (my $IN1,'<','file1.txt') or die "$!"; #open 1st file
open (my $IN2,'<','file2.txt') or die "$!"; #open 2nd file
open (my $OUT,'>','out.txt') or die "$!";   #create new file
while (<$IN1>) {
    chomp;                                  #remove newline from each row of the 1st file
    my $x=readline $IN2;                    #read line from 2nd file
    print $OUT join(',',$_,$x);             #print the desired output
}
close $IN1;
close $IN2;
close $OUT;

答案 1 :(得分:0)

只是为了确保,你想要输出

abc,123
def,456
ghi,789

你举的例子,对吧? 如果是这样,以下代码应该做的事情。

#!/usr/bin/perl

use strict;
use warnings;

open F1, "file1.in" or die "$!";
open F2, "file2.in" or die "$!";
open OUTPUT_FILE, ">output.out" or die "$!";

while (defined(my $f1 = <F1>) and defined(my $f2 = <F2>)) {
    chomp $f1;
    chomp $f2;
    print OUTPUT_FILE "$f1,$f2\n";
}

close OUTPUT_FILE;
close F1;
close F2;

答案 2 :(得分:0)

加入bash做的事情不同于加入Perl。在Perl中,您需要使用循环,或类似List :: MoreUtils :: pairwise或Algorithms :: Loops :: MapCar。

use File::Slurp 'read_file';
my @file1_lines = read_file('file1', 'chomp' => 1);
my @file2_lines = read_file('file2');

然后:

use List::MoreUtils 'pairwise'; use vars qw/$a $b/;
print pairwise { "$a,$b" } @file1_lines, @file2_lines;

或:

use Algorithm::Loops 'MapCarE';
print MapCarE { "$_[0],$_[1]" } \@file1_lines, \@file2_lines;

(如果文件具有不同的行数,MapCarE会抛出异常;其他变体具有其他行为。)