Yet another approach that would work for the kind of data you posted:
{ local $/ = '***END***'; while (<>) { print if ( /mykeyword2|mykeyword4/ ); } }
That sets perl's "input record separator" to be the end-of-record string, instead of the default end-of-line string ("\n" or "\r\n", depending on your OS). In the version shown above, the line-termination character(s) following each "***END***" will be included at the beginning of the next record. If you prefer (and if you know for sure that your input data will always use the same style of line-termination), you can set $/ like this:
local $/ = "***END***\n"; # or "***END***\r\n"
UPDATE:

Having seen AM's riz's reply below, I have to assume that s/he didn't understand what I said, so here's a full, tested version of the approach I described:

#!/usr/bin/perl use strict; my @keepers; { local $/ = '***END***'; while ( <DATA> ) { next unless ( /^\s*mykeyword[24]/ ); chomp; push @keepers, $_; } } print join '', @keepers; __DATA__ mykeyword1 several data lines containing junk ***END*** mykeyword2 several lines containing target data ***END*** mykeyword3 several lines containing junk ***END*** mykeyword4 again several lines containing target data ***END*** mykeyword1 several data lines containing junk ***END*** mykeyword2 several lines containing target data ***END*** mykeyword3 several lines containing junk ***END*** mykeyword4 again several lines containing target data ***END***
Note that when $/ is set to some non-default value, the "chomp" function uses that value to remove the record delimiter string from the end its operand ($_ in this case).

In reply to Re: searching data lines between keywords by graff
in thread searching data lines between keywords by riz

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.