Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: sorting hashes

by Limbic~Region (Chancellor)
on Apr 20, 2005 at 12:37 UTC ( [id://449567]=note: print w/replies, xml ) Need Help??


in reply to sorting hashes

olecs,
When people post hash sorting question, almost invariably, they just want to know how to sort the hash. They are not concerned with things like changing what sort routine to use or how to keep the hash in the order you want when inserting new keys and values. This is probably for good reason as hashes aren't intended to be in sorted order.

On the other hand, sometimes that is exactly what you want which is why I wrote Tie::Hash::Sorted.

#!/usr/bin/perl use strict; use warnings; use Tie::Hash::Sorted; my $numerically = sub { my $hash = shift; [ sort { $a <=> $b } keys %$hash ]; }; tie my %hash, 'Tie::Hash::Sorted', 'Sort_Routine' => $numerically; %hash = map { $_ => undef } 1..25; for ( keys %hash ) { tie %{ $hash{ $_ } }, 'Tie::Hash::Sorted', 'Sort_Routine' => $nume +rically; %{ $hash{ $_ } } = map { (int rand 5000) => undef } 1..5; for my $key ( keys %{ $hash{ $_ } } ) { @{ $hash{ $_ }{ $key } }{ qw/first last min max/ } = map { int +(rand 100) + 1 } 1..4; } } # Modify %hash however you want and don't worry about it for my $o_key ( keys %hash ) { for my $i_key ( keys %{ $hash{ $o_key } } ) { print "$o_key : $i_key\n"; # do something with $hash{ $o_key }{ $i_key } if you want } }
Remember, anytime you use a tied implementation there is going to be a performance penalty. I have taken quite a few steps to optimize this module so if it is something you are interested, be sure to read the docs on how to get the most out of it. If you have any questions, please let me know.

Cheers - L~R

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://449567]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (3)
As of 2024-03-29 01:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found