Reputation: 141
I have a txt file that looks like this:
The number of lines
on the upper part of
this file can
vary in size
. : . : . : . : . : . : .
lineA
lineB
lineC
_____________________________________________________________
The number of lines
on the lower part of
this file can
also vary in size
I would like to grab all the lines between
. : . : . : . : . : . : .
and
_____________________________________________________________
The other lines above and below I would like to ignore. I've tried "next if", "until" and "last" without any success. Any ideas on how this can be done? This is what I have so far.
open (IN, "$file") || die "Cannot open file $file";
while(my $line=<IN>)
{
chomp $line;
last if ($line =~ m/:/);
#do something with these lines
}
Upvotes: 1
Views: 55
Reputation: 50637
use strict;
use warnings;
open (my $IN, "<", $file) || die $!;
while (my $line = <$IN>)
{
chomp $line;
# force 0 instead of empty string
# so it can be used to numerically compare under warnings
my $switch = ($line =~ /:/ .. $line =~ /__/) ||0;
next if $switch <=1;
last if $switch =~ /E/;
#do something with these lines
}
$switch
values are
1 # starting with /:/ line
2 # lineA
3 # lineB
4 # lineC
5E0 # ending with /__/ line
so we want all lines after 1
, and end the while loop when it matches /E/
Upvotes: 2
Reputation: 15121
You could use ..
or ...
operator to filter out lines by giving a start and an end conditions.
For example:
#!/usr/bin/perl
use strict;
use warnings;
while (<DATA>) {
if (m/^\./ ... m/^_/) {
# You may want to do more filtering at here
print;
}
}
__DATA__
The number of lines
on the upper part of
this file can
vary in size
. : . : . : . : . : . : .
lineA
lineB
lineC
_____________________________________________________________
The number of lines
on the lower part of
this file can
also vary in size
Output:
$ perl t.pl
. : . : . : . : . : . : .
lineA
lineB
lineC
_____________________________________________________________
Upvotes: 2