我在解析文件的一部分时尝试使用范围运算符。基本上,我的代码包括:
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
使用范围运算符对其进行测试之前对其进行了一些更改。我还没有找到将..
运算符与显式变量一起使用的方法。我通过$_
在测试前分配找到了一种解决方法,但这对我来说看起来像一个丑陋的黑客:
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
有没有更清洁的方法来做到这一点?