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


In reply to Re: Manipulating Array Indexes by kcott
in thread Manipulating Array Indexes by TJ777

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.