in reply to split to hash, problem with random keys

Use the CPAN module Tie::IxHash. It maintains the key order for you. Keys will return in the order that they are defined.

As for why does keys return in a pseudo-random order?
Its faster!
  • Comment on Re: split to hash, problem with random keys

Replies are listed 'Best First'.
Re: Re: split to hash, problem with random keys
by sauoq (Abbot) on Jul 03, 2003 at 17:30 UTC

    If you must use a tied hash (which is slower and only allows you to order the keys one hash at a time) you should be aware of the fact that tied hashes don't act like normal hashes when used in boolean contexts.

    my %hash tie my %tied, 'Tie::IxHash'; $hash{foo} = 1; $tied{foo} = 1; print "hash is true\n" if %hash; print "tied is true\n" if %tied; # Won't print.
    Until this is fixed, I think it's a good reason to avoid tied hashes when possible.

    As for why does keys return in a pseudo-random order?
    Its faster!

    Or, more likely, it takes less space. Such a feature would probably be implemented with a separate array that holds the keys in order (which is basically how Tie::IxHash does it.)¹ With that strategy, returning them in order wouldn't be any faster, but storing them takes more space.

    1. Tie::IxHash actually keeps both the data and the keys in arrays. It then keeps a hash of indexes. But, its the storage that grows, not the time to return the keys.

    -sauoq
    "My two cents aren't worth a dime.";