in reply to Grep - print matched line and next N lines

I think your basic logic is overkill and prone to initial bugs, or maintenance bugs, because you're reading in two places, and testing in two places, and generally saying things twice. That's always a bad sign. Just do this:
$n = 0; while (<>) { $n = 7 if /$pattern/; # start printing if ($n) { print; $n-- } # print if within $n = 0 if eof; # don't leak across file boundaries }
Plus or minus a few parameters, of course.

-- Randal L. Schwartz, Perl hacker

Replies are listed 'Best First'.
Re: &bull;Re: Grep - print matched line and next N lines
by runrig (Abbot) on Aug 13, 2002 at 17:23 UTC
    Well, I'm all for making things simpler, so I've updated it with your suggestion (and keeping all the previous parameters intact). I was a little concerned about testing for eof on every iteration, but it doesn't really make that big of a difference. And I think doing it this way makes it easier to add more options, like setting different 'after' counts for different patterns and such.