"What about while looping though it with while?"

for (@array) iterates over the list of values in @array. Changing that list in mid-iteration often has problems. We actually get quite a few questions like "Why doesn't my for loop work?" that are due to such a problem. So, as the doco says, "don't do that".

while (@array) involves no iteration; it's a simple condition which basically says "Enter the loop if @array has any elements". Unless there's some other method for exiting that loop, you would expect elements to be removed from @array so that the loop can eventually terminate.

"Similarly, what about modifying a hash (using delete) while looping with for/foreach or while? From a quick skim through the doc it doesn't appear to be an issue."

If you're writing for (%hash) or while (%hash), that's probably a mistake; perhaps you meant something else. You'll need to provide some code to show the scenario(s) you're considering here.

By the way, in case you didn't know, for and foreach are synonymous. Save yourself four keystrokes by writing for instead of foreach: the code will run the same whichever you choose.

-- Ken


In reply to Re^3: Iterating through an array using multiple loops and removing array elements by kcott
in thread Iterating through an array using multiple loops and removing array elements by BiochemPhD

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.