in reply to Determining hash order for sorting array

From perldoc -f keys section of the perlfunc manpage:
The actual random order is subject to change in future versions of perl, but it is guaranteed to be the same order as either the "values" or "each" function produces (given that the hash has not been modified).
So in short you cannot depend on the keys, values, or each functions to provide results in a pre-determined order. There are ways around this .. I believe (haven't actually used it personally) that Tie::Hash Tie::IxHash can (will?) preserve hash order for you. Also, you can always sort the results of keys/values calls. For example:
my %h = ( ... ); foreach my $k ( sort { lc $a cmp lc $b } keys %h ){ # get keys sorte +d by lowercase of key ... } foreach my $k ( sort { lc $h{$a} cmp lc $h{$b} } keys %h ){ $ get key +s sorted by lowercase of value ... }

Replies are listed 'Best First'.
Re^2: Determining hash order for sorting array
by halley (Prior) on Aug 21, 2005 at 18:02 UTC
    Also, the iteration order can change drastically after any new key is added, since that key may have forced an internal rehash into a different number of internal bins for efficiency. Two identically-filled hashes might have different iteration orders because of attack-proofing in the hash function. And so on.

    In short, while the word "random" is not accurate, one should never depend on the iteration order of a hash.

    --
    [ e d @ h a l l e y . c c ]

Re^2: Determining hash order for sorting array
by bart (Canon) on Aug 21, 2005 at 20:17 UTC
    I believe (haven't actually used it personally) that Tie::Hash can (will?) preserve hash order for you.
    It doesn't. However, there's a few modules that serve to tie a hash so its keys order is the same as the insertion order: Tie::IxHash (Pure Perl) and Tie::Hash::Indexed (ditto, but XS).