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.


In reply to Re: altering array in foreach during execution? by ikegami
in thread 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.