in reply to Padding search results with context

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