Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: Hash key ordering?

by Cybercosis (Monk)
on May 02, 2002 at 17:49 UTC ( [id://163613]=note: print w/replies, xml ) Need Help??


in reply to Hash key ordering?

Aside from the hash algorithm changing (which shouldn't happen unless you change your perl), and barring any particularly bizarre things, you *should* be able to count on a consistant key ordering *if* you create the keys in the same order. Internally, perl copes with hash collisions (two keys hashing to the same numeric value) by sticking the offending value at the end of a linked list with the other, not-so-offending values. When it goes to assemble the list for the keys() function, it adds them in a linear fashion. So, if you have two keys that collide, keys() won't list them in the same order if they appear in a different order in the linked list. OTOH, if you sort the keys() list, they'll *always* be in the same order, so do that. =-)

~Cybercosis

nemo accipere quod non merere

Replies are listed 'Best First'.
Re: Re: Hash key ordering?
by kwilliams (Sexton) on May 03, 2002 at 05:40 UTC
    Most people's replies seem to be focusing on the details of the implementation, but this isn't the greatest idea. One can, however, make certain conclusions based only on guarantees in the documentation:
    (perldoc -f keys) The keys are returned in an appar- ently random order. The actual random order is subject to change in future versions of perl, but it is guaranteed to be the same order as either the `values' or `each' function produces (given that the hash has not been modified).
    That's exactly how much you can count on - the fact that it is "the same order as" values() and each() means that it also must be the same order as future calls to keys() (by the transitivity property of the word "same"). If you make *any* changes to the hash, this guarantee goes away.

    Of course, this is *not* the same as the OP's original phrase "provided of course that the keys are the same" - you can insert & delete things in a hash and end up with the same eventual set of keys, but your modifications may still change the order of keys().

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (2)
As of 2024-04-16 21:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found