in reply to Lines above and Below a matched string

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.