in reply to altering array in foreach during execution?
The list of elements over which foreach iterates is on calculated before foreach starts. Changing the number of elements in the array should have no effect on the looping whatsoever.
Not what you want.
In practice, due to an optimisation and the fact that the stack isn't refcounted, changing the array over which you are iterating can cause the wrong values to be seen and fatal errors ("Use of freed value in iteration").
Not what you want.
You could use loop over the indexes (and use last as you should have been).
my @fields = REQUIRED_FIELDS; for my $e (@$a) { for my $i (0..$#fields) { if ($e eq $fields[$i]) { $href->{$e} = 0; splice @fields, $i, 1; last; } } }
But a hash would be better.
my %fields = map { $_ => 1 } REQUIRED_FIELDS; for my $e (@$a) { $href->{$e} = 0 if $fields{$e}; }
In fact, since the hash never changes, you only need to create the hash once, not every time verify is called.
Update: Fixed the OP's misuse of splice as per AnomalousMonk's post.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: altering array in foreach during execution?
by Anonymous Monk on Dec 03, 2011 at 00:19 UTC |