Perl:匹配多行

Perl : match multiple lines

使用 perl 正则表达式,如果连续两行匹配则计算行数。

我想要匹配模式之前的行数

D001
0000
open ($file, "$file") || die; 
   my @lines_f = $file;
   my $total_size = $#lines_f +1;

   foreach my $line (@lines_f)
   {
       if ($line =~ /D001/) {
           $FSIZE = $k + 1;
       } else { 
           $k++;}
    }  

除了 D001,我还想检查下一行是否为 0000。如果是,$FSIZE 就是 $file 大小。 $file 看起来像这样

00001 
00002
.
.
.
D0001
00000
00000

这是一个例子。如果找不到标记线,这会将 $FSIZE 设置为 undef

use strict;
use warnings;

my $fn = 'test.txt';
open ( my $fh, '<', $fn ) or die "Could not open file '$fn': $!";
chomp (my @lines = <$fh>);
close $fh;

my $FSIZE = undef;
for my $i (0..$#lines) {
    if ($lines[$i] =~ /D0001/) {
        if ( $i < $#lines ) {
            if ( $lines[$i+1] =~ /00000/ ) {
                $FSIZE = $i + 1;
                last;
            }
        }
    }
}