home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


sort [

Sorts a list and returns the sorted list value. By default (without a code argument), it sorts in standard string comparison order (undefined values sorting before defined null strings, which sort before everything else). code , if given, may be the name of a subroutine or a code block (anonymous subroutine) that defines its own comparison mechanism for sorting elements of list . The routine must return to the sort function an integer less than, equal to, or greater than 0, depending on how the elements of the list are to be ordered. (The handy <=> and cmp operators can be used to perform three-way numeric and string comparisons.)

The normal calling code for subroutines is bypassed, with the following effects: the subroutine may not be a recursive subroutine, and the two elements to be compared are passed into the subroutine as $a and $b , not via @_ . The variables $a and $b are passed by reference, so don't modify them in the subroutine.

Do not declare $a and $b as lexical variables (with my ). They are package globals (though theyre exempt from the usual restrictions on globals when you're using use strict ). You do need to make sure your sort routine is in the same package though, or else you must qualify $a and $b with the package name of the caller.

In versions preceding 5.005, Perl's sort is implemented in terms of C's qsort(3) function. Some qsort(3) versions will dump core if your sort subroutine provides inconsistent ordering of values. As of 5.005, however, this is no longer true.