Walt Mankowski on 23 Nov 2003 23:04:53 -0500


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Why can't an array element be used as the index var in foreach?


Last night I was working on a little script that entailed my writing 6
nested for loops.  At the innermost loop I needed to know what all 6
indices were, so instead of using $a, $b, $c, etc., I decided it would
make the code cleaner if I used an array instead.

So I wrote something like this:

  my @c;

  foreach $c[0] (0..5) {
    foreach $c[1] ($c[0]..5) {
      foreach $c[2] ($c[1]..5) {
        ...

I was surprised to learn that this is invalid Perl, and that the index
variable needs to be a normal scalar.  But I can't find anything in
either the Camel or the Perl man pages where this is documented.
perlsyn just says it's supposed to be a "variable", but it doesn't
define was a "variable" is.

In nearly every other case I can think of in Perl, array elements work
just like scalars.  You can, for instance, take references to them and
use local on them.  In fact, a reference to an array element says that
it's a scalar reference.

So what's so special about foreach loops that array elements aren't
permitted?  And if they are explicitly forbidden, where is that
documented?

Thanks.

Walt

Attachment: pgpWr0rV6EPac.pgp
Description: PGP signature