Re: maintaining order in a hash (without Tie::IxHash)



On Thu, 22 May 2008 13:22:28 -0700, sln@xxxxxxxxxxxxxx wrote:

On Thu, 22 May 2008 10:20:17 -0700 (PDT), nolo contendere <simon.chao@xxxxxxx> wrote:

Many times, there exists a module on CPAN that solves a problem I'm
attempting to solve.
I'm aware that generally the better choice to solving such a problem
is to use the CPAN module.
However, regarding the problem of maintaining sort order of a hash,
and the Tie::IxHash module, I have a question.

I've heard that Tie::IxHash can be a little slow, and the cost of
using this in addition to installation costs (where developers don't
have the permission to have modules installed, especially across all
environments, and the process for having the module(s) installed by
admins can be trying to say the least) is much higher than the simple
solution of adding an extra sortval attribute to a hash value, where
the value of sortval is simply an incremented counter.

then if you need to access the hash in the order in which items were
inserted, you could simply:

for my $key ( sort { $hash{$a}{sortval} <=> $hash{$b}{sortval} } keys
%hash ) {
# do something
}


Is there something wrong with my reasoning? Would this solution be a
good candidate for addition into the FAQ How can I make my hash
remember the order I put elements
into it?


Why is it so important to have a hash sorted?
What would a hash be necessary for then?

Wouldn't an array be better in that case?

I see you can pass parameters as arrays and read it as a hash.
I see you can pass parameters as hash and read it as array.

Is that true? If so, why is it important to sort hash?

.