Clearly the code snippet you gave is incomplete. The problem here is probably that you have entries that span multiple lines. If the data is (and always will be) relatively small, the easiest way is probably to just load everything into an array. When the line starts with whitespace you would add it to the end of the previous entry, and otherwise you would start a new entry. Then you can go through the array with grep or foreach to find what you want. This is especially useful if you need to do multiple searches, as file operations are slower than in-memory ones. Something like this:
my @stuff; while (<>) { if (/^\s/) { $stuff[-1] .= $_; } else { push @stuff, $_; } } print grep { /keyword/ } @stuff;
If the data are large though, that would gobble up too much memory. In that case I'd go for something more like this, especially if you just need to do the search once:
my $last_entry; while (<>) { if (/^\s/) { $last_entry .= $_; } else { print $last_entry if $last_entry =~ /keyword/; $last_entry = $_; } print $last_entry if $last_entry =~ /keyword/ && eof(IN); }

In reply to Re: matching keyword in multi-line records by billward
in thread matching keyword in multi-line records by arthur99

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.