I am trying to use the range operator while parsing a portion of a file. Basically, my code consists of:
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
My problem is that this code uses the implicit $_
variable.
My actual code uses a variable to store the current line because I am making some changes to $line
before testing it with the range operator. I have not found a way to use the ..
operator with an explicit variable. I have found a workaround by assigning $_
right before the test but that looks like an ugly hack to me:
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
Is there a cleaner way to do this?
You could do:
while (my $line = <DATA>) {
if ($line =~ /start/ .. $line =~ /stop/) {
print $line;
}
}