No such thing as a small change | |
PerlMonks |
Re: Manipulating Array Indexesby perlfan (Vicar) |
on Sep 07, 2020 at 16:31 UTC ( [id://11121449]=note: print w/replies, xml ) | Need Help?? |
This is easy enough if you work it out without the complication of getting fancy with a one-liner. And I am not sure a "look ahead*" is useful or just complicates what you wish to do.Algorithmically, there are 2 ways to approach this.
1. scan array to the end and mark all indexes where there is a 5; then easily calculate the "range" - don't forget these arrays are 0 indexed To show what I mean, just scan and collect the indexes where the value is 5:
Once you have the indexes that contain 5, you can apply the concept of array slices to extract the values you're wanting. Note, this is not the same as splice, which can be destructive on your arrays (but potentially useful here nonetheless). 2. scan and store previous elements along the way - there are various ways to do this I can think of that don't require book keeping variables - no example here, but you could use a hash of array references to "scoop" up elementes leading up to each 5, for example. * Update: I think I know why you want to "look ahead". As it was pointed out by Corion, don't use pop. Not only is this destructive to the array, but it also screws up your view of the list. pop takes the last element of the array, so there is no looking ahead - only behind. If you wish to destroy the array as you process it, use shift. But be warned, while pop doesn't re-index elements (but affects greatest index), shift will cause all elements' indexes to decrease by 1. So, don't use a destructive operation (pop, shift. splice) to iterate or partition your array until you have it working non-destructively and understand why it is working.
In Section
Seekers of Perl Wisdom
|
|