2017-02-15 57 views
0
#!/usr/bin/perl 
use warnings; 
use strict; 
use feature qw{ say }; 

my $kw1 = 'Session Initiation Protocol (REGISTER)'; 
my $kw2 = 'CSeq: 3 REGISTER'; 

my $instance_counter; 
my @first; 
my @next; 
my $myfile = "Input.txt"; 
open my $out_file1, '>', 'hello1.txt' or die "$!"; 
open my $out_file2, '>', 'hello2.txt' or die "$!"; 
open my $out_file3, '>', 'hello3.txt' or die "$!"; 

open DATA, $myfile or die "Can't open file: $!"; 

while (<DATA>) { 
    if (my $match = (/\Q$kw1/ .. /\Q$kw2/)) { 
     ++$instance_counter if 1 == $match; 

     if (1 == $instance_counter) { 
      print $out_file1 $_; 
     } 
     elsif (2 == $instance_counter){ 
     print $out_file2 $_; 
     } 
     else { 
      print $out_file3 $_; 
     } 


    } 

} 

我上面的程序将$ kw1和$ kw2之间的每个模式输出到单独的文本文件。是否有任何想法可以自动概括我对这些实例的搜索(即没有匹配模式)并相应地生成输出文本文件?如何在Perl中使用范围运算符概括模式匹配搜索

回答

3

这很容易。在输入实例时打开文件,使用计数器作为名称的一部分。

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

my $kw1 = 'Session Initiation Protocol (REGISTER)'; 
my $kw2 = 'CSeq: 3 REGISTER'; 

my $instance_counter; 
my $out; 
while (<DATA>) { 
    if (my $match = (/\Q$kw1/ .. /\Q$kw2/)) { 
     if (1 == $match) { 
      ++$instance_counter; 
      undef $out; 
      open $out, '>', "output_$instance_counter" or die $!; 
     } 

     print {$out} $_; 
    } 
} 
undef $out; 

__DATA__ 
... 
Session Initiation Protocol (REGISTER) 
1 
2 
CSeq: 3 REGISTER 
... 
Session Initiation Protocol (REGISTER) 
a 
b 
c 
d 
CSeq: 3 REGISTER 
... 
Session Initiation Protocol (REGISTER) 
X 
Y 
Z 
CSeq: 3 REGISTER 
... 
+0

是的..工作正常。谢谢 – rocky