当要匹配的文本不在 $_ 中时,如何将范围运算符与正则表达式一起使用?

How can I use the range operator with regexes when the text to match is not in $_?

我在解析文件的一部分时尝试使用范围运算符。基本上,我的代码包括:

use strict;
use warnings;

while (<DATA>){
    if (/start/ .. /stop/){
        print; #print only lines between the two markers
    }
}
__DATA__
ignored 1
ignored 2
start
taken 1
taken 2
stop
ignored 3

我的问题是这段代码使用了隐式 $_ 变量。

我的实际代码使用一个变量来存储当前行,因为我在使用范围运算符测试它之前对 $line 进行了一些更改。我还没有找到将 .. 运算符与显式变量一起使用的方法。我通过在测试之前分配 $_ 找到了一个解决方法,但对我来说这看起来像一个丑陋的 hack:

use strict;
use warnings;

while (defined (my $line = <DATA>)){
    $_ = $line;
    if (/start/ .. /stop/){
        print $line;
    }
}
__DATA__
ignored 1
ignored 2
start
taken 1
taken 2
stop
ignored 3

有更简洁的方法吗?

你可以这样做:

while (my $line = <DATA>) {
    if ($line =~ /start/ .. $line =~ /stop/) {
        print $line;
    }
}