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:

$ 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 }; $
Is the array used by foreach cached? I am not understanding why splice is not pruning the found values.

Thanks!


In reply to altering array in foreach during execution? by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.