Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Manipulating Array Indexes

by kcott (Archbishop)
on Sep 08, 2020 at 03:55 UTC ( [id://11121480]=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11121480]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (3)
As of 2024-03-29 04:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found