in reply to Re: Re: sort and hash
in thread sort and hash
Limbic~Region metioned to me that you might be wanting to preserve the sort, that is, the keys stay sorted even after you add new ones. You can use the CPAN module Tie::Hash::Sorted for this, but first see A Guide to Installing Modules if you are not familiar with the CPAN. Tie's are, in my opinion, a bit hard to grasp if you are new to Perl (see perltie), but here goes anyway. :)
Data::Dumper is another CPAN module, but it comes with your Perl installation so you don't have to install it like you do Tie::Hash::Sorted. Once you have \ installed it, run the above example and notice the output. Note that even though your hash stays 'magically' sorted, there are a lot of CPU cycles burned to achieve it. In other words, if you really don't need to keep the hash sorted, then don't don't keep it sorted.use strict; use warnings; use Data::Dumper; use Tie::Hash::Sorted; my %sequence = ( 1345 => 10, 123 => 20, 500 => 30, ); print Dumper \%sequence; # and here's the part that makes ears bleed ... tie my %sorted_sequence, 'Tie::Hash::Sorted', Hash => \%sequence, Sort_Routine => sub {[sort {$a <=> $b} keys %{$_[0]}]}, ; print Dumper \%sorted_sequence; $sorted_sequence{901} = 40; $sorted_sequence{201} = 50; print Dumper \%sorted_sequence;
Also, don't rule out using an array. Hashes are really good for quick lookups. If you are more concerned with sorting then looking up items, use an array.
jeffa
L-LL-L--L-LL-L--L-LL-L-- -R--R-RR-R--R-RR-R--R-RR B--B--B--B--B--B--B--B-- H---H---H---H---H---H--- (the triplet paradiddle with high-hat)
|
|---|