in reply to Using an array element as a loop iterator

The question is a bit ambiguous, so for a wild guess on a mental (side?) track distinct from the prior answers I ask "Are you by any chance trying to do this?"

C:\>perl -e "@a=(1,2,3);@b=(2,4,6,7);for (@a) {print $b[$_];}" 467

Elements of @a used to print portions of @b; namely, $b[1]...$b[3]

Others have noted the problem with instantiating @a by using square brackets. Quotes revised for Windows.

Replies are listed 'Best First'.
Re^2: Using an array element as a loop iterator
by GotToBTru (Prior) on Nov 07, 2013 at 20:18 UTC
    How is "Can we use an array element as a loop iterator for another array?" ambiguous?

      The question's ambiguous because it's not well formed (with all due respect to the OP). Consider the following:

      use strict; use warnings; my @a = (2, 4, 6);

      The array elements in the above array are 2, 4 and 6. Can 2 be used as a loop iterator? $a[1] is not an array element. One assumes that $a[1] is the referent of the phrase "array element," but that assumption requires disambiguating the OP's use of that phrase.

      1. For lack of a sample of desired output and the existence of such limited sample data that -- depending on one's reading of the question -- the question can be parsed in at least two, mutually-exclusive ways.
      2. Because of the presence of a fundamental error, noted by others, in declaring the variable @a.
      3. Because here at the Monastery, the possibility always exists that precision in English is NOT a strong suit for an OP.

        What he is trying to accomplish in his examples is vague indeed; the foreach loop and the C-style for loop are not functionally equivalent, even if the first was valid syntax. I suspect these are off-the-cuff examples to illustrate his question.

        If you don't mind helping me understand, what are the two ways to parse his question? My own post shows how I parsed it. If that is one of the two, no need to rehash it.

        (update added first paragraph for clarity)

      How is "Can we use an array element as a loop iterator for another array?" ambiguous?

      Granted, the question itself seems to be fairly clear, but the code presented to do that is so far from that and so buggy that I just can't make sense of what the OP really wants to do (which is the reason I asked for clarifications). Add to that that the C-style loop (that supposedly works) does something completely different that it just obfuscate further the OP's real intent.