Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: Clean out da hash...

by calin (Deacon)
on Feb 12, 2004 at 12:08 UTC ( [id://328538]=note: print w/replies, xml ) Need Help??


in reply to Clean out da hash...

Be aware that each keeps state, so adding or deleting elements in an each loop is not the greatest of ideas. However, your pattern of usage seems to be supported, though I wouldn't recommend it.

Quote from perldoc -f each

If you add or delete elements of a hash while you're iterating over it, you may get entries skipped or duplicated, so don't. Exception: It is always safe to delete the item most recently returned by "each()", which means that the following code will work:

while (($key, $value) = each %hash) { print $key, "\n"; delete $hash{$key}; # This is safe }

Replies are listed 'Best First'.
Re: Re: Clean out da hash...
by davido (Cardinal) on Feb 12, 2004 at 17:02 UTC
    "...is not the greatest of ideas."

    Why is it not the greatest of ideas when the docs specifically make it a point to say that it is "always safe to delete the item most recently returned by each()"? The OP's delete example is almost word for word the same as the one provided in the docs that you quoted.

    His problem lies elsewhere.

    He should be looking at scoping issues. He should also ween himself from passing variables into subs implicitly (as if they were globals) rather than explicitly as parameters to the subs. In this case, it would probably be wise to pass the hash into his delete sub by reference rather than global osmosis. But the act of deleting a hash's elements is so trivial that it hardly warrants its own subroutine.


    Dave

      Big thanks to everyone. I finally got the problem figured out. A colleague across the ocean had some time on his hands and looked at it. It was a careless mistake on my side

      Early on in the script (before I changed strategies), I had two counters, to remind me what line I was on. I was assigning the wrong counter as the line number (I was off by one line) and it was pure coincidence that the text file was laid out in a manner where I was snagging a value that represented the sum of both sets of data. Chalk that one up to bad luck and carelessnes.

      I did learn a bit more about hashes though from the thread, so it was definitely not a lost cause. Also learned that if you change the idea of your script, it's not a bad idea to wipe the slate clean.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (7)
As of 2024-03-29 08:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found