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.


In reply to Re^2: how to extract certain lines by aufflick
in thread how to extract certain lines by dee00zee

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.