TJ777:

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.

...roboticus

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


In reply to Re: Manipulating Array Indexes by roboticus
in thread Manipulating Array Indexes by TJ777

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.