Your skill will accomplishwhat the force of many cannot PerlMonks

Re: Manipulating Array Indexes

by roboticus (Chancellor)
 on Sep 07, 2020 at 16:19 UTC Need Help??

in reply to Manipulating Array Indexes

Yes, you can access other elements in the array by doing math with the index. There are lots of ways you could do it, but I'll demonstrate with two: you can do it as a two pass operation to first find all the targets, and then loop over your target list to print your results; or you could try to do it in a single pass over the array.

```use strict;
use warnings;

my @list = (1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1);

my @indexes;

### Method 1: two passes over the list ###

# Find all the fives
for my \$idx (0 .. \$#list) {
push @indexes, \$idx if \$list[\$idx] == 5;
}

# For each five we find, show it (position and value) and
# the three following values
for my \$idx (@indexes) {
print "list[\$idx]=\$list[\$idx]: ";

for my \$t (1 .. 3) {
print \$list[\$idx + \$t], " ";
}
print "\n";
}

### Method 2: one pass over the list ###

for my \$idx (0 .. \$#list) {
# Skip printing unless we're at a five
next unless \$list[\$idx] == 5;

print "list[\$idx]=\$list[\$idx]: ",
# use a list slice to get the elements
join(", ", @list[\$idx+1 .. \$idx+3]),
"\n";
}

It looks like you're trying to use the first method, but you didn't show enough code for me to figure you what difficulty you're having. The second method can work well also, but can be a bit more confusing at first.

Other things that can make your life tricky are:

• modifying the list while you're iterating over it, and
• modifying your index variable while you're iterating.

So try not to do either of those.

...roboticus

When your only tool is a hammer, all problems look like your thumb.

Create A New User
Node Status?
node history
Node Type: note [id://11121445]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (2)
As of 2021-01-23 04:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
The STEM quote I most wish I'd made is:

Results (252 votes). Check out past polls.

Notices?