匹配行(带正则表达式)写入两个输出文件,但它应该只写入一个输出文件..

时间:2012-07-01 13:54:59

标签: perl

我有一个带有多行的制表符分隔文本文件。我编写了一个脚本,在其中我将行分配给一个数组,然后通过正则表达式搜索数组,以找到符合特定条件的行。找到匹配项后,我将其写入Output1。在查看列出的所有if语句(正则表达式)并且仍未满足条件之后,该行将写入输出2.

在匹配条件和写入输出1时,我100%工作,但这里是我的问题所在: 匹配的行也被写入Output2,以及不匹配的行。我可能犯了一个愚蠢的错误,但我真的无法看到它。如果有人可以看看并帮助我,我真的很感激..

非常感谢! :)

Inputfile sample:
skool   school
losieshuis  pension
prys    prijs
eeu    eeuw
lys lijs
water   water
outoritêr   outoritaire


#!/usr/bin/perl-w
use strict;
use warnings;
use open ':utf8';
use autodie;

open OSWNM, "<SecondWordsNotMatched.txt";
open ONIC, ">Output1NonIdenticalCognates.txt";
open ONC, ">Output2NonCognates.txt";

while (my $line = <OSWNM>)
{
    chomp $line;        
    my @Row = $line;

    for (my $x = 0; $x <= $#Row; $x++)
    {
        my $RowWord = $Row[$x];

#Match: anything, followed by 'y' or 'lê' or 'ê', followed by anything, followed by 
a tab, followed by anything, followed by 'ij' or 'leggen' or 'e', followed by anything

      if ($RowWord =~ /(.*)(y|lê|ê)(.*)(\t)(.*)(ij|leggen|e)(.*)/)
      {
        print ONIC "$RowWord\n";
      }


#Match: anything, followed by 'eeu', followed by 'e' or 's', optional, followed by 
anyhitng, followed by a tab, followed by anything, followed by 'eeuw', followed by 'en', optional

      if ($RowWord =~ /(.*)(eeu)(e|s)?(\t)(.*)(eeuw)(en)?/)
    {
        print ONIC "$RowWord\n";
      }

      else
    {
        print ONC "$RowWord\n";
    }
}
}

1 个答案:

答案 0 :(得分:2)

在你的循环中你基本上有:

if (A) {
  output to file1
}

if (B) {
  output to file1
} else {
  output to file2
}

因此,output to file2任何不满足B的内容(无论A是否满足),并输出满足AB的内容file1两次if (A or B) { output to file1 } else { output to file2 }

如果不打算输出两次,则应将逻辑修改为:

if (A) {
  output to file1
} elsif (B) {
  output to file1
} else {
  output to file2
}

或者:

A

(第二个版本允许您对Bmy $output_to_file2 = 1; if (A) { output to file1 $output_to_file2 = 0; } if (B) { output to file1 $output_to_file2 = 0; } if ($output_to_file2) { output to file2 } 个案进行不同的处理。)

如果打算使用双倍输出,您可以执行以下操作:

{{1}}