Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: Manipulating Array Indexes

by perlfan (Vicar)
on Sep 07, 2020 at 16:31 UTC ( [id://11121449]=note: print w/replies, xml ) Need Help??


in reply to Manipulating Array Indexes

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:

my @fives_idx = (); my $i = 0; foreach my $e (@lines) { if (5 == $e) { push @fives_idx, $i; } ++$i; }

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.

Replies are listed 'Best First'.
Re^2: Manipulating Array Indexes
by Anonymous Monk on Sep 07, 2020 at 18:38 UTC

    Thank you all so very much...I am really blown away by both the speed and quality of the replies. You have given me a lot to work with/think about! Thanks to everyone who shared their thoughts and ideas! TJ.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (6)
As of 2024-04-25 18:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found