greetings all,

I am trying to go the extra mile on some classwork and make it so that my program can output processed data as a hash that is sorted by its values rather than its keys.

I am looking to end up with something like this:

Homer is 37 years old. Marge is 36 years old. Bart is 12 years old. Lisa is 9 years old. Maggie is 2 years old.

Ok, I know you can't actually sort a hash. Instead I am instead trying to pass my results into an array, use the sort function to organize the array. The goal would be to be able to use the program to sort any similar hashes. (Think %Jetsons and %Scoobydoo)

So far I have this:

#first the example %hash my %age = ( "Maggie" => 2, "Homer" => 37, "Bart" => 12, "Lisa" => 9, " +Marge" => 36); #Setting up and sorting the array... my @simpson_age = sort by_age keys %age; #I snagged this is From O'reilly's Learning Perl, 3rd ed... sub by_age { $age{$b} <=> $age{$a} }

I feel that I am close - but so far, no dice! Any tips on where to go from here?


Thanks, mox

In reply to Sorting a hash by values... by chinamox

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



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.