in reply to Manipulating Array Indexes

G'day TJ,

Welcome to the Monastery.

There are some edge cases you didn't consider (or, at least, didn't tell us about) so here's a couple of options.

I've extended your posted input to show: 5 at the start; 5 in the set of 3 returned; and, running out of elements at the end.

$ perl -E ' my @x = (5,1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1,5,9,8,5,7,5,5,5); say "|@$_|" for map [@x[$_+1 .. $_+($#x-$_ >= 3 ? 3 : $#x-$_)]], grep $x[$_] == 5, 0..$#x; ' |1 2 3| |6 7 8| |4 3 2| |9 8 5| |7 5 5| |5 5| |5| ||

If, on the other hand, you don't want sets of less than 3 returned, you can simplify the map and don't read the last 3 indices.

$ perl -E ' my @x = (5,1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1,5,9,8,5,7,5,5,5); say "|@$_|" for map [@x[$_+1 .. $_+3]], grep $x[$_] == 5, 0..$#x-3; ' |1 2 3| |6 7 8| |4 3 2| |9 8 5| |7 5 5|

Both of those solutions work with input such as (), (5), and (1,2,3,4). Although you say that you're expecting long arrays, it's always a good idea to add a sanity check for those times when your process is handed something unexpected, like one of those short lists.

— Ken