The way to do this is to define an END{} block.

With the -n or -p switch, there's another solution - Abigail's trick, the 'eskimo greeting':

perl -ne '}{ print $.' # count lines

My solution made into a one-liner

perl -ne 'BEGIN{$_=shift for$B,$A,$p}/$p/and@l=(),do{<>for 1..$A},next +;push@l,$_;print shift@l if$B<@l}{print@l' 3 5 pattern test.txt

where 3 is lines before, 5 is lines after the pattern.

Sample data:
keep 1 keep 2 keep 3 keep 4 delete 1 delete 2 delete 3 pattern delete 1 delete 2 delete 3 delete 4 delete 5 keep 5 keep 6 keep 7 keep 8 keep 9 keep 10 keep 11 delete 1 delete 2 delete 3 pattern delete 1 delete 2 delete 3 delete 4 delete 5 keep 12 keep 13 keep 14 keep 15 delete 1 delete 2 delete 3 pattern delete 1 delete 2 delete 3 delete 4 delete 5 keep 16 keep 17 keep 18 keep 19 delete 1 delete 2 delete 3 pattern delete 1 delete 2 delete 3 delete 4 delete 5 keep 20 keep 21
Output:
keep 1 keep 2 keep 3 keep 4 keep 5 keep 6 keep 7 keep 8 keep 9 keep 10 keep 11 keep 12 keep 13 keep 14 keep 15 keep 16 keep 17 keep 18 keep 19 keep 20 keep 21

In reply to Re^2: Regex question by shmem
in thread Regex question by jamsda

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.