in reply to foreach with array elements problem

I want to use an array element for storing the value of each loop iteration. Just like doing foreach $scalar (1..5) I want to be able to do foreach $array[0] (1..5), is it really that confusing? And obivously this isn't code I wan't to use but example code used to demonstrate the error.
The actual code is quadruple nested foreach loops so I use an array for holding each loop value and then do a join(".", @array); at the end. I could just do my ($iter1, $iter2, $iter3, $iter4); and "$iter1.$iter2.$iter3.$iter4" but right now I'm interested in why this causes an error.

Replies are listed 'Best First'.
Re^2: foreach with array elements problem
by pg (Canon) on Oct 22, 2005 at 03:34 UTC

    You are out of luck with the syntax you wanted. Syntax is syntax, which you have to strictly follow. Logically, You might have a point to use an array element as the loop variable (as long as it is a scalar, however you must realize the difficulty that this schema introduced, as it is not possible to determine the type of an array element statically, thus it is wise not to introduce what you wanted into a language.), but that's not how the language is defined.

    You still can do what you wanted to do, inside each level of your quadruple loop, just push the loop variable into an array.

    for my $i (...) { push @iter, $i; ... for my $j (...) { push @iter, $j; ... for my $k (...) { push @iter, $k; ... for my $l (...) { push @iter, $l; ... } } } }

    On the other hand, I trust that, you realize, the inner loops have access to outter loop variables. The reason to push them into an array is not for gaining access of their values, but rather other convenience that you are seeking.

      as long as it is a scalar, however you must realize the difficulty that this schema introduced, as it is not possible to determine the type of an array element statically, thus it is wise not to introduce what you wanted into a language.
      As a matter of fact, array elements can only be scalars. perldata is quite clear about this, but what probably leaves no doubt is perldsc:
      The most important thing to understand about all data structures in Perl -- including multidimensional arrays--is that even though they might appear otherwise, Perl @ARRAYs and %HASHes are all internally one-dimensional. They can hold only scalar values (meaning a string, number, or a reference). They cannot directly contain other arrays or hashes, but instead contain references to other arrays or hashes.

      Flavio
      perl -ple'$_=reverse' <<<ti.xittelop@oivalf

      Don't fool yourself.
Re^2: foreach with array elements problem
by Anonymous Monk on Oct 22, 2005 at 03:27 UTC
    "is it really that confusing?"

    No, it is NOT confusing at all, but obviously you did confuse some people a hell lot. Next time try to ask something more easier ;-)