Hello usertest,
As I understand it, you want to retain all lines that do not come between START and END, and also those that do whenever def doesn’t appear in the same block; but when def does occur between START and END, you want to exclude that entire block of data.
If this is correct, then you need to store all the lines in each START ... END block (e.g., in an array), and print them if and only if it turns out that the block doesn’t contain def. For keeping track of whether you’re currently in a block, the range operator in scalar context is the most appropriate tool:
#! perl
use strict;
use warnings;
my ($found, @lines);
while (<DATA>)
{
if (my $flag = /START/ .. /END/)
{
$found = /def/ unless $found;
push @lines, $_;
if ($flag =~ /E0$/)
{
if ($found)
{
$found = 0;
}
else
{
print for @lines;
}
@lines = ();
}
}
else
{
print;
}
}
__DATA__
Source Data
START
abc
def
ghi
END
START
xyz
abc
END
Output:
14:22 >perl 1646_SoPW.pl
Source Data
START
xyz
abc
END
14:22 >
For the range operator, see perlop#Range-Operators.
Update: Fixed logic error in code by moving the @lines = (); statement to below the inner if ... else block; also improved wording slightly.
Hope that helps,
|