You're lucky if you actually get any kind ofsorting, because <=> is the numeric comparison operator, this means that perl will expect number, and turn "D1", "P5" and your other strings (except those that start by a number) into the value 0. It's quite easy to remember which operator do what in perl, numeric operators look like mathematics symbols (== < > <= >= <=>) and string operators look like strings (eq lt gt le ge cmp).

Now, as long as your numbers are one digit long, all you need to do is sort { $b->{GRADE} cmp $b->{GRADE} } @$AG; where cmp is the alphabetic comparison operator.

But if you can have numbers that are longer you'll have to choose between to behaviours. Either you still want alphabetic order, and then the code I gave you will work, and P10 will be sorted before P2 (because 1 is before 2, and in alphabetic order you look at one char at a time and ignore the rest), or you want to sort by using the full number. In the latter case, the way to provide several sort conditions is:

sort { $a->{NAME} cmp $b->{NAME} # compare name (will return 0 if they a +re the same), using alphabetic order (cmp) or $a->{AGE} <=> $b->{AGE} # compare age only if the names are equ +al, use numeric order (<=>) } @people;
This means that you'll have to find a way to extract the letter and number from your string (not that I couldn't give you the answer, but you'll understand it better if you find it by yourself).


In reply to Re: Sorting a Hash by Eily
in thread Sorting a Hash by GuiPerl

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.