We don't bite newbies here... much | |
PerlMonks |
Re: Permanently sort a hashby herveus (Prior) |
on Jun 04, 2009 at 15:01 UTC ( [id://768458]=note: print w/replies, xml ) | Need Help?? |
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
In Section
Seekers of Perl Wisdom
|
|