http://qs1969.pair.com?node_id=133929


in reply to More Sorted Business with Hashes

Is there a way to sort a hash by values and leave it in a hash?

No. Hashes are inherently non-ordered. However, for what you're trying to do, something like

@keysByValue = sort { $clients{$a} cmp $clients {$b} } keys %clients;
will give you keys ordered by value.

Replies are listed 'Best First'.
Re: Re: More Sorted Business with Hashes
by IlyaM (Parson) on Dec 22, 2001 at 05:56 UTC
      Sure, a tied hash can be kept ordered, by using an array, or some heavier-weight data structure, underneath it.

      The FAQ notwithstanding, the original statement is correct. Hash lookup algorithms produce fundamentally unordered results. Perl's hashes implement a concept properly called associative arrays. They are called hashes because that is how they work under the hood.

      Therefore native Perl hashes are not obviously ordered, and anything you run across in any language called a hash should be assumed to likewise be not obviously ordered.

Re: Re: More Sorted Business with Hashes
by dha (Acolyte) on Dec 24, 2001 at 00:12 UTC
    Having not used the various modules mentioned in the thread, I'm not sure about relative overhead, but... Using the method above to get an array of sorted keys, how about passing a hash slice, rather than your original hash to wherever you're trying to use the "ordered hash"? I.e. @hash{@keysByValue} rather than just %hash ? Slices are fun! :-)
Re: Re: More Sorted Business with Hashes
by dha (Acolyte) on Dec 24, 2001 at 00:18 UTC
    And, just in case it's not clear where to go from there, use a hash slice, rather than rather than your original hash: @hash{@keysByValue}
    Slices are fun!