I am wanting to verify the existence of various strings within a text file, & the order of these strings is not mandated.
I have implemented a loop which looks for each successive string. However, there is no need to look for strings already encountered, so I would like to remove strings from the search list as they encountered.
splice() seemed to be the obvious choice to delete elements within the array, or so I thought. The following simplified code executed under Perl 5.8.8 doesn't seem to delete any elements within the search list:
#!/bin/env perl use strict; use Data::Dumper; use constant REQUIRED_FIELDS => qw/zero one two three four five six se +ven/; my $a = [qw/three one two/]; print Data::Dumper->Dump([$a], ['a']); verify($a); exit; sub verify { my $a = shift; my $fields = [REQUIRED_FIELDS]; my $href = {}; foreach my $e (@$a) { my $i; foreach my $field (@$fields) { if ($e eq $field) { $href->{$field} = 0; splice @$fields, $i, 0; print Data::Dumper->Dump([$i, $fields], [qw/i fields/] +); } ++$i; } } print Data::Dumper->Dump([$href], [qw/href/]); }
Execution yields the following output:
Is the array used by foreach cached? I am not understanding why splice is not pruning the found values.$ perl test.pl $a = [ 'three', 'one', 'two' ]; $i = 3; $fields = [ 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven' ]; $i = 1; $fields = [ 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven' ]; $i = 2; $fields = [ 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven' ]; $href = { 'three' => 0, 'one' => 0, 'two' => 0 }; $
Thanks!
In reply to altering array in foreach during execution? by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |