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:
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).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;
In reply to Re: Sorting a Hash
by Eily
in thread Sorting a Hash
by GuiPerl
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |