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:

So try not to do either of those.


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