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 reply to Re: Permanently sort a hash by herveus
in thread Permanently sort a hash by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.