It sounds like you only want to match lines starting with PLACED if the "immediately preceding" line is "HERE IS THE DATA".
This is not really a perl problem - it's a logic problem. I don't want to sound harsh, but if you were my student I wouldn't answer this question...
There would be any number of possible solutions, but think about it this way:
at any given time, you are asking two questions:
q1) does the current line start with PLACED
q2) does the previous line match "HERE IS THE DATA"
so you basically want to look at the current line and the previous line at the same time.
...
my $previous_line;
while (my $current_line = <DATA>) {
if ( $current_line =~ /^PLACED/
&& $previous_line =~ /^HERE IS THE DATA$/ ) {
print $current_line;
}
$previous_line = $current_line;
}
This can be optimised.
If all you care about is seeing "HERE IS THE DATA" once, and then you want all lines starting with "PLACED" after it - just try thinking about your question another way around:
q) have we ever seen a line that says "HERE IS THE DATA"?
q) if we have, does the line start with PLACED?
eg:
...
my $seen_here_is_the_data;
while (my $line = <DATA>) {
$seen_here_is_the_data = 1 if $line =~ /^HERE IS THE DATA$/;
if ( $seen_here_is_the_data
&& $previous_line =~ /^HERE IS THE DATA$/ ) {
print $line;
}
}
This can also be optimised.
Update: FYI, the solution by neilh for the second case is simpler and the one I would use (and reccomend using) - I made mine as verbose as possible to try to help the seeker understand how to solve similar problems himself in the future. |