Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
coldfingertips,
It seems that people often want to use a hash so they can have key lookup functionality but also want the hash to come out in a specific order as well.

If you want the hash to come out in the order it was created, than Tie::IxHash is probably for you ( and if you need speed look at Tie::Hash::Indexed which is written in XS ). Do not use these modules if you need your hash sorted though. While it does provide 3 methods to resort the hash (user provided key list or ASCIIBetically by keys/values), it does not provide any mechanism for retaining auto-sorting new keys/values.

This is one of the reasons I wrote Tie::Hash::Sorted. It allows the user to define their own sort routine (even using lexicals the module wouldn't normally see) as well as numerous optimization options to choose from. Your code would look something like:
#!/usr/bin/perl use strict; use warnings; use Tie::Hash::Sorted; my $sort = sub { my $hash = shift; [ sort { $hash->{$b} <=> $hash->{$a} || $a cmp $b } keys %$hash ]; }; tie my %sorted_data, 'Tie::Hash::Sorted', 'Sort_Routine' => $sort; %sorted_data = ( rock => 3, candle => 25, bug => 3, rain => 12, dust => 17, spider => 12 ); print "$_ : $sorted_data{$_}\n" for keys %sorted_data;
Modifying the hash does not require any additional work to keep the sorted order.

Cheers - L~R


In reply to Re: Twice the pleasure of sorting a hash by Limbic~Region
in thread Twice the pleasure of sorting a hash by coldfingertips

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (5)
As of 2024-04-23 06:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found