in reply to How to print 5 lines below after a regex match

You test only for matching, but of course what you really want is lines after the match. So while you need to make note that it has matched, you need another indication to tell you when to print. And the indication needs to go away once you've printed the limited number of following lines. '$flag' gets set when we match; '$few' allows us to supply the number of lines, or just allow a default value of 2.

use strict; my $flag = 0; my $few = shift || 2; while (<DATA>) { print $_ if ($flag-- > 0); $flag = $few if (/Update certificate/); } __DATA__ Useless line before match Feb 19 15:22:21 206021 152221.684878 7219 INFO: Update certificate f +or user=(XXX) , updated by XXX First line after match Second line after match Third line after match Fourth line after match

Update: output

H:\perl> perl 1156056.pl First line after match Second line after match H:\perl>perl 1156056.pl 3 First line after match Second line after match Third line after match
But God demonstrates His own love toward us, in that while we were yet sinners, Christ died for us. Romans 5:8 (NASB)

Replies are listed 'Best First'.
Re^2: How to print 5 lines below after a regex match
by new2perl2016 (Novice) on Feb 24, 2016 at 20:01 UTC

    Thanks I see the lines posted below my match. One last thing which I should have included, how do also print the matched line as well. Many thanks

      Set the flag first then print

      use strict; my $flag = 0; my $few = shift || 3; while (<DATA>) { $flag = $few if (/Update certificate/); print $_ if ($flag-- > 0); }
      poj
        It really depends on what the OP really needs, but there is a danger of $flag being reset while it is reading the next "few" lines, if the regex matches again. Perhaps something like this:
        use strict; my $few = shift || 3; while (<DATA>) { if (/Update certificate/) { print $_; print scalar <DATA> for 1..$few; } }
        Or possibly for 1..$few-1;, depending on whether $few includes the matching line or not.