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

Re: Permanently sort a hash

by herveus (Prior)
on Jun 04, 2009 at 15:01 UTC ( [id://768458]=note: print w/replies, xml ) Need Help??


in reply to Permanently sort a hash

Howdy!

Why do you feel you need your hashes to behave in a way they weren't meant to?

The short (and flippant) answer to your question is "you can't". Hashes are unordered collections by their very nature. If you want the keys in a specific order, you have to impose that order on the list that you get by calling keys(). If the set of keys is static, you can store the list in an array in any desired order. That array will keep them in that order always, but now you have to keep the array and the hash in sync.

You cannot reliably predict the order that keys() will produce for any set of keys with more than one item. The order will depend on the set of values and the order in which they were added to the hash. If you examine the source code for your specific instance of perl, you can examine the hash function. Then you have to understand how that interacts with keys() to extract the list.

Of course, there are modules that will let you impose an ordering on keys(), but they have to subvert the standard behavior of hashes.

This question is analogous to asking for the rows in a table in a database to be kept "sorted". All that really means is "I don't want to have to sort the data myself each time I use it". One of the "costs" of using a hash is that the data is inherently unordered. If you must have it in a specific order, you either have to sort it into that order each time, or you have to use an array to maintain the desired order. Or you have to put an ORDER BY clause on your SELECT statement.

yours,
Michael

Log In?
Username:
Password:

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

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

    No recent polls found