Loading ...
Sorry, an error occurred while loading the content.

Re: [PBML] Sort hash by keys

Expand Messages
  • Jeff Pinyan
    ... No. Hashes maintain an internal order that can change over time as more keys are added (or deleted). If you want to keep the keys of a hash in a
    Message 1 of 2 , Sep 19, 2007
    • 0 Attachment
      On 9/19/07, Ryan J Nauman <RJNauman@...> wrote:
      > I have a hash. I want to sort it by its keys and maintain its newly
      > sorted version. I know you can use sort keys but isn't there a simple one
      > liner to take a hash, sort it by its keys, and retain the sort from
      > there-on?

      No. Hashes maintain an internal order that can change over time as
      more keys are added (or deleted). If you want to keep the keys of a
      hash in a particular order, store them in an array:

      my @keys_in_order = sort keys %hash;

      Then you can use @keys_in_order to walk through your hash in a
      particular order. There are also modules you can use to intervene,
      which would make what appears to be a regular hash actually one that
      always keeps its keeps sorted. The Tie::Hash::Sorted module does just
      that:

      use Tie::Hash::Sorted;
      tie my %sorted_hash, 'Tie::Hash::Sorted';

      Then just use %sorted_hash like it's a regular hash, and you'll find
      that every time you access its keys, you'll get them in sorted order.

      --
      So he got up and went back to his father. While he was still a long
      way off, his father caught sight of him, and was filled with
      compassion. He ran to his son, embraced him and kissed him. ~ Luke
      15:20

      [Mary said,] "Do whatever he tells you." ~ John 2:5
    Your message has been successfully submitted and would be delivered to recipients shortly.