David Michael wrote:
: I have a hash that needs to be displayed in a certain order. I tried
:
: foreach $key (sort (keys %HASH)) {
: print $key;
: }
:
: that sorts alphabetically. I need it in the order it was inserted, so I made the
:value a number that increased for each key. I need to sort by the value, but display
:the key. Any ideas ?
You can provide sort() with a subroutine that prescribes how to do the
pairiwse comparisons:
foreach $key (sort { $HASH{$a} <=> $HASH{$b} } keys %HASH ) {
print $key;
}
Or you can use the Tie::IxHash module- available on CPAN- which allows
you to create hashes that preserve the order in which the keys were
created:
use Tie::IxHash;
tie %HASH => tie 'Tie::IxHash';
foreach $key (sort keys %HASH) {
print $key;
}
Then it doesn't matter what the %HASH values are.
-- tdk