Just keep track of the last three lines you read, and match against the one before the last you read.

my $line1 = <>; chomp($line1); my $line2 = <>; chomp($line2); while (<>) { chomp($_); my $line3 = $_; if ($line2 =~/(SOMETHING)/) { my $something = $1; $line1 =~ /(DATE)/; my $date = $1; $line3 =~ /(SOMETHINGELSE)/; my $somethingElse = $1; print "$something,$date,$somethingElse\n"; } $line1 = $line2; $line2 = $line3; }

Note: this is untested code. It will fail on files shorter than three lines. And no, it's not elegant, but it's simplee.

Hope this helps, -gjb-

Update: This is a sliding buffer just as in BrowserUK's approach, but this should work for large files too.


In reply to Re: Lines above and Below a matched string by gjb
in thread Lines above and Below a matched string by Anonymous Monk

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.