in reply to Strangness with arrays

The problem is with the
for (@array)
bit. Under normal circumstances, the array is flattened into a list and you can then mess with @array safely. However... there's an optmization in perl such that if the only thing in the list is a plain array then perl doesn't flatten, it just whips through the array, and modifying the array has... Interesting Results.

If you want, you can throw another set of parens around @array to force it to be a list, then you can mess with it as much as you like within the loop without really messing things up.

Replies are listed 'Best First'.
Re^2: Strangness with arrays
by Aristotle (Chancellor) on Jul 10, 2002 at 20:41 UTC

    Actually, the loop variable is always aliased to the loop elements, even when you say something like for (@a1, @a2, @a3) or even for (qw(foo bar baz 1 2 3), @a1). If you really want to force flattening, you need to force a copy of the data structure: for(@{[@a1, @a2, @a3]})

    Update: point taken.

    Makeshifts last the longest.

      You misunderstood.

      Yes, the loop variable always aliases to the individual scalars. This is true. But in the case presented, with a bare, single array in for/foreach's list, perl also turns the loop into an iteration over the array itself, rather than flattening the array and iterating over the list of scalars.