in reply to Permanently sort a hash

This is a FAQ: How can I always keep my hash sorted?. Why do you need this? Generally, this query is an XY Problem...

Replies are listed 'Best First'.
Re^2: Permanently sort a hash
by Limbic~Region (Chancellor) on Jun 04, 2009 at 15:13 UTC
    kennethk,
    Actually, that FAQ is wrong.

    Although this does keep your hash sorted, you might not like the slow down you suffer from the tie interface.

    What Tie::IxHash actually does is preserve your insertion order. It does have rudimentary capability to re-order by asciibetical sorted keys or values but it is not persistent. If you add key/val pairs, they don't insert into their sorted position and you have to re-order them again. You also can't do anything more complex when sorting.

    Tie::Hash::Sorted OTOH does answer the FAQ but I feel a bit odd sending a doc patch to p5p pimping my own module.

    Cheers - L~R

Re^2: Permanently sort a hash
by Anonymous Monk on Jun 04, 2009 at 15:00 UTC

    Thank you for such a quick reply!
    The reason why I wanted it sorted, is because I have to print frequently a hash where key order matters. Instead of sorting every time the keys before looping I wanted to have it sorted permanently.

      ikegami's solution is a good one then - cache the sorted keys. You can even forgo the foreach loop using hash Slices:

      my @sorted_keys = sort { $a <=> $b } keys(%foo); print join("\n",@hash{@sorted_keys})