We don't bite newbies here... much | |
PerlMonks |
Re^3: Iterating through an array using multiple loops and removing array elementsby kcott (Archbishop) |
on Apr 25, 2014 at 07:10 UTC ( [id://1083738]=note: print w/replies, xml ) | Need Help?? |
"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 Section
Seekers of Perl Wisdom
|
|