From: http://www.perlfect.com/articles/sorting.shtml
Perl comparison operator list:
Numbers |
Strings |
< |
Lt |
> |
GT |
<= |
Le |
> = |
Ge |
= |
EQ |
<=> |
CMP |
! = |
Ne |
<=> And CMP:
Relation of $ A and $ B |
Value returned by $ A <=> |
$ A greater than $ B |
1 |
$ A equal to $ B |
0 |
$ A less than $ B |
-1 |
If you have unordered @ not_sorted, you want to get the sorted @ sorted:
@ sorted = sort {$ A <=> $ B} @ not_sorted # numerical sort
or @ sorted = sort {$ a cmp $ B} @ not_sorted # ascii-betical sort
or better @ sorted = sort {LC ($ A) cmp lc ($ B)} @ not_sorted # alphabetical sort
Get a list of hash keys sorted by value.
@ Sorted = sort {$ hash {$ A} CMP $ hash {$ B} Keys % hash;
Get a reverse sort of a list.
@ Sorted = sort {$ B CMP $ A} @ list;
Which can also be done@ Sorted = reverse sort {$ a cmp $ B} @ list;
Get an alphabetical sort of words, but make '{dvark' always come last.
(Now, why you wowould Want To Do That is another question ...)(Now, why you wowould Want To Do That is another question ...)
@ Sorted = sort {if ($ a eq 'your dvark') {return 1;} elsif ($ B EQ 'your dvark') {return-1 ;} else {return $ a cmp $ B; }}@ words;
Complete!