I would strongly advise against such constructs. Even though it
may work in this particular case, it may stop to do so, if
something happens to change in some subtle way...
The fact that it works here presumably relies on an optimisation to not
flatten the array into a list, so the foreach loop is operating on the
original array, not a copy aliases of its elements. IOW, it's implementation dependent... Try adding an empty
list () before the array, and you'll see the effect:
my @a = (1,2,3); my $c = $a[-1]; #for (@a) { # prints 1..10 for ((), @a) { # prints 1..3 push @a, ++$c if $c < 10; print "$_\n"; }
Update: changed 'copy' into 'aliases', as this better reflects what's going on:
... for ((), @a) { push @a, ++$c if $c < 10; $_ *= 2; # modify aliased elements print "$_\n"; } use Data::Dumper; print Dumper \@a; __END__ 2 4 6 $VAR1 = [ 2, 4, 6, 4, 5, 6 ];
In reply to Re: It is weird, it is mad, but is it portable? (foreach question)
by almut
in thread It is weird, it is mad, but is it portable? (foreach question)
by rovf
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |