Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

comment on

( [id://3333] : superdoc . print w/replies, xml ) Need Help??
I made several attempts at returning a sorted hash:
#!/usr/bin/perl use strict; use Data::Dumper; my %unsorted = ( key3 => 'bread', key2 => 'apples', key1 => 'steak', key4 => 'butter', key5 => 'oranges', key6 => 'cake', ); my @keys_by_value = sort { $unsorted{$a} cmp $unsorted{$b} } keys %uns +orted; print "Keys by value: @keys_by_value\n"; print "Sorted values: @unsorted{ @keys_by_value }\n"; my @sorted_keys_values = map { $_, $unsorted{$_} } sort { $unsorted{$ +a} cmp $unsorted{$b} } keys %unsorted; print "Keys/values by value: @sorted_keys_values\n"; #my $foo = { @sorted_keys_values }; my $as_hash = { map { $_, $unsorted{$_} } sort { $unsorted{$a} cmp $u +nsorted{$b} } keys %unsorted }; print "Data Dumper:\n"; print Data::Dumper->Dump( [$as_hash],['as_hash'] );

and though it's fairly easy to get the keys and values sorted by value, as soon as perl converts the data back into a hash structure, it goes back to its natural (unordered) state:
Keys by value: key2 key3 key4 key6 key5 key1 Sorted values: apples bread butter cake oranges steak Keys/values by value: key2 apples key3 bread key4 butter key6 cake key +5 oranges key1 steak Data Dumper: $as_hash = { 'key1' => 'steak', 'key2' => 'apples', 'key3' => 'bread', 'key4' => 'butter', 'key5' => 'oranges', 'key6' => 'cake' };
So I was unable to create a sorted hash without resorting (as IlyaM and dws mentioned) to 'tie'.

Rather than roll my own tie-based solution, I went to CPAN: Tie::SortHash or Tie::IxHash may do what you need.

Impossible Robot

In reply to Re: More Sorted Business with Hashes by impossiblerobot
in thread More Sorted Business with Hashes by Spenser

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.