Two loops - one to build the output list, and one to output it. Things get a little more interesting if there are a very large number of lines such that the implied slurp is not feasible.

use strict; use warnings; use List::Util qw(min max); my $firstLine = 1; my $lastLine = 20; my @indexes = (1, 5, 6, 8, 15, 20); my $pad = 1; # lines of context on each side my @selLines; for my $centre (@indexes) { my $min = max ($centre - $pad, $firstLine); my $max = min ($centre + $pad, $lastLine); $_ == $centre ? $selLines[$_] = [$_, 1] : $selLines[$_] ||= $_ for $min .. $max; } defined ($_) && print "$_\n" for map {ref $_ ? "Highlight $_->[0]" : $_} @selLines;

Prints:

Highlight 1 2 4 Highlight 5 Highlight 6 7 Highlight 8 9 14 Highlight 15 16 19 Highlight 20

Note the handling for "end effects"!

Update: fixed bug


DWIM is Perl's answer to Gödel

In reply to Re: Padding search results with context by GrandFather
in thread Padding search results with context by moritz

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.