You are viewing the version of this documentation from Perl 5.41.8. This is a development version of Perl.
sort may also refer to the module: sort
sort SUBNAME LIST
sort BLOCK LIST
sort LIST

In list context, this sorts the LIST and returns the sorted list value. In scalar context, the behaviour of sort is undefined.

If SUBNAME or BLOCK is omitted, sorts in standard string comparison order. If SUBNAME is specified, it gives the name of a subroutine that returns a numeric value less than, equal to, or greater than 0, depending on how the elements of the list are to be ordered. (The <=> and cmp operators are extremely useful in such routines.) SUBNAME may be a scalar variable name (unsubscripted), in which case the value provides the name of (or a reference to) the actual subroutine to use. In place of a SUBNAME, you can provide a BLOCK as an anonymous, in-line sort subroutine.

If the subroutine's prototype is ($$), the elements to be compared are passed by reference in @_, as for a normal subroutine. This is slower than unprototyped subroutines, where the elements to be compared are passed into the subroutine as the package global variables $a and $b (see example below).

If the subroutine is an XSUB, the elements to be compared are pushed on to the stack, the way arguments are usually passed to XSUBs. $a and $b are not set.

If two or more elements of LIST compare the same (i.e. the comparison operation returns 0 for them), they retain the relative order they had in LIST. In other words, sorting is stable (and has been since v5.8.0).

The values to be compared are always passed by reference and should not be modified.

You also cannot exit out of the sort block or subroutine using any of the loop control operators described in perlsyn or with