尝试在两个文件上匹配相同的字符串时不打印模式

时间:2017-01-04 08:24:08

标签: perl loops

我试图从两个不同的文件中找到模式,然后需要将两个文件的最后一个值相加,然后在xls中打印第一个,第二个和第三个字段(总和)的总和...这是我写的到目前为止但是它是打印的第一个如果循环不确定为什么不打印第二个。如果有比下面更好的逻辑做同样的操作......

file1.txt 
L01B,"ABC",832048921.62
L01E,"DDD",70675364.68
L02A,"ZZZ",19747732853.37

file2.txt
L01B,"AAA",832048921.62
L01E,"DDD",70675364.68
L02A,"ZZZ",19747732853.37
#!/usr/bin/perl

use warnings;
use strict ;
  use Date::Simple qw(d8);

  my $firstdate = $ARGV[0];
  my $d1 = d8($firstdate);
 my $seconddate = $ARGV[1];
  my $d2 = d8($seconddate);
  my $f1=$d1-> format ('%d_%m_%Y');
  my $f2=$d2-> format ('%d_%m_%Y');
  print  " $f1 \t";
  print "$f2\n";
  open(my $fh1, '<', $f1) or die "Could not open file '$f1' $!";
  open(my $fh2, '<', $f2) or die "Could not open file '$f2' $!";

  while ( my $line1 = <$fh1>) {
           chomp $line1;
           if ($line1 =~/L01B/){
               my @array = split /[,]+/,$line1;
               {
               while (my $line2 = <$fh2>)
               {
               if ($line2 =~/L01B/){

               my @array1  = split /[,]+/,$line2;
               print " match found sec $array1[0]\n";
              print " match found sec $array1[1]\n";
              print " match found sec $array1[2]\n";
              print " match found first $array[0]\n";
              print " match found first $array[1]\n";
              print " match found first $array[2]\n";
              }

              }
              }
             }
             if ($line1 =~/L01B/){
               my @array2 = split /[,]+/,$line1;
               {
               while (my $line2 = <$fh2>)
               {
               if ($line2 =~/L01A/){

               my @array3  = split /[,]+/,$line2;
               print " match found sec $array2[0]\n";
              print " match found sec $array2[1]\n";
              print " match found sec $array2[2]\n";
              print " match found first $array3[0]\n";
              print " match found first $array3[1]\n";
              print " match found first $array3[2]\n";
              }

              }
              }

             }

             }
    close($fh1);
    close($fh2);        

2 个答案:

答案 0 :(得分:1)

在内循环中,你耗尽$fh2。在外循环的下一次迭代中,<$fh2>返回undef,因为文件句柄已经读取了整个文件。

目前还不清楚你想要实现什么,但是如果文件是同步的(即file <1的 th 行总是对应于file2中的n th 行) ,你可以从每个句柄中读取一个文件;否则,通常的做法是散列一个文件,然后逐行处理第二个文件,检查散列中的有趣值。

答案 1 :(得分:1)

要快速修复,请按如下方式将文件内容加载到数组中

open(fh1, '<', $f1) or die "Could not open file '$f1' $!";
my @file1= <fh1>;
close(fh1);

open(fh2, '<', $f2) or die "Could not open file '$f2' $!";
my @file2= <fh2>;
close(fh2);

open(fh1, '<', $f1) or die "Could not open file '$f1' $!"; my @file1= <fh1>; close(fh1); open(fh2, '<', $f2) or die "Could not open file '$f2' $!"; my @file2= <fh2>; close(fh2);

现在代替while循环尝试使用foreach循环,如下所示

@volverin:我没有测试过这些代码,只是做了一些改动供你参考。

praveenzx〜