Not sure if it's better or just different, but you could do something like this:

my @nums = (1, 5, 6, 8, 15, 20); my $max_idx = 21; my $pad = 1; my @hilite = @nums; my $hilite = shift @hilite; my $i = -1; for my $n (@nums) { for my $c ($n-$pad .. $n+$pad) { if ($c > $i) { last if $c > $max_idx; $i = $c; if ($i == $hilite) { print "I=$i\n"; $hilite = shift @hilite; } else { print " i=$i\n"; } } } }

Output:

i=0 I=1 i=2 i=4 I=5 I=6 i=7 I=8 i=9 i=14 I=15 i=16 i=19 I=20 i=21

Update: changed context to $pad = 1 to keep the example output in line with the other replies (Apparently it was asking too much to figure out that I had originally set $pad = 2 ... — Or why the downvotes?)


In reply to Re: Padding search results with context by almut
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.