You need to consider what you really want to do with your data. A hash is a bag that holds a bunch of data that you access using a key. There is no 'order' to the data. In fact, what order it may have will change as data is added and removed from the bag.

If you want fast access to a chunk of data given a key, use a hash. If you want to preserve the order of a list of stuff, use an array. If you want to do both use a tied hash (Tie::IxHash as suggested by Zaxo). Note though that a tied hash does neither job as well as the built in structures.

Most often though all you need is to generate a sorted list of keys when you need them using something like sort keys %hash. If what you want is to sort by the values and don't care about the keys you can sort values %hash. But really, any general advice is likely to be overtaken by your actual application. To get solid advice, provide a small sample of the sort of data and the code that you are using. Mention too how much data there is and how often you may need to access the data in sorted order. All those things influence the choices that may be made.


DWIM is Perl's answer to Gödel

In reply to Re: Hash sorting by GrandFather
in thread Hash sorting by pickledegg

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.