The important thing to remember is that it's still using just the keys to sort on!

Well actually it is sorting numerically on the values not the keys (PS I'm sure this was just a slip of the tongue and would have /msg if you'd been online). Anyway to clarify what boo_radley *meant*

%inv=( Apple => 10, Peach => 5, Berry => 9, Cobbler => 3, Cherry => 7 ); print "\nSort values numerically in ascending order\n"; foreach $key ( sort {$inv{$a} <=> $inv{$b}} keys %inv) { &print_it } print "\nSort values numerically in descending order\n"; foreach $key ( sort {$inv{$b} <=> $inv{$a}} keys %inv) { &print_it } print "\nSort keys alphabetically in alphabetical order\n"; foreach $key ( sort {$a cmp $b} keys %inv) { &print_it} print "\nNote this is the same as\n"; foreach $key ( sort keys %inv) { &print_it} print "\nSort keys alphabetically in reverse alphabetical order\n"; foreach $key ( sort {$b cmp $a} keys %inv) { &print_it } sub print_it { print "$key\t=> $inv{$key}\n" }

You will see from the examples that we use <=> for numerical sorts and 'cmp' for alphabetical ones. We sort based on the arguments on each side of these operators. $a is one of the keys whereas $inv{$a} is the value in the $inv hash keyed by $a. You will also note that reversing the position of the arguments reverses the sort order. By default sort uses {$a cmp $b} which is an alphabetical sort in alphabetical order.

cheers

tachyon

s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print


In reply to Re: Re: sort keys question (boo) by tachyon
in thread sort keys question by treebeard

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.