in reply to altering array in foreach during execution?
splice @$fields, $i, 0;
Furthermore, and notwithstanding that a hash-based approach is, indeed, better for what you seem to want to do, the quoted splice statement from the OPed code also does not do what you want, removing zero elements (LENGTH == 0) beginning at an OFFSET of $i in the array, i.e., it's an expensive no-op.
>perl -wMstrict -le "my $ar = [ qw(a b c d) ]; ;; my $i = 0; for my $e (@$ar) { $e = uc $e; splice @$ar, $i, 0; ++$i; } ;; use Data::Dumper; print Dumper $ar; " $VAR1 = [ 'A', 'B', 'C', 'D' ];
(As a reinforcement to ikegami's point that you really don't want to add or delete elements in an array over which you are iterating, try changing the 0 in the splice statement in the example code of this reply to a 1.)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: altering array in foreach during execution?
by Anonymous Monk on Dec 03, 2011 at 00:27 UTC |