Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re^3: Iterating through an array using multiple loops and removing array elements

by kcott (Archbishop)
on Apr 25, 2014 at 07:10 UTC ( [id://1083738]=note: print w/replies, xml ) Need Help??


in reply to Re^2: Iterating through an array using multiple loops and removing array elements
in thread Iterating through an array using multiple loops and removing array elements

"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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1083738]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (2)
As of 2024-04-25 19:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found