【问题标题】:How to join two file with single columns values separated by comma in perl如何在perl中使用逗号分隔的单列值连接两个文件
【发布时间】:2023-04-02 03:28:02
【问题描述】:

我有两个文件。

file1 包含

abc
def
ghi 

在单列中(3 个单独的行)

file2 包含

123
456
789 

(在单列中(3 个单独的行)

我正在尝试将这两个文件中的值加入到一个新的逗号分隔文件中。我希望将一个文件中的所有值捕获到两个不同的数组中,并使用“join”命令来“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 的简单“加入”命令来做到这一点。但我想学习如何在 perl 中做到这一点。

【问题讨论】:

    标签: perl join


    【解决方案1】:

    我假设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;
    

    【讨论】:

      【解决方案2】:

      只是为了确保你想要输出

      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;
      

      【讨论】:

        【解决方案3】:

        在 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 会抛出异常;其他变体有其他行为。)

        【讨论】:

        • 对不起,我还不够先进,无法使用模块。我还在用 Perl 弄湿我的脚。但是我会把你提到的这些模块放在我的笔记中,这样当我进入模块时,我可以特别注意那些。
        • 当你把脚弄湿的时候是最好的时间。 perl 就是使用模块。
        猜你喜欢
        • 1970-01-01
        • 2021-10-13
        • 2013-10-06
        • 2011-10-15
        • 2019-05-04
        • 2020-03-05
        • 1970-01-01
        • 2010-12-09
        相关资源
        最近更新 更多