Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

sort

Sorts a list of values and returns them in sorted order.

Sorts the input list according to the comparison mode determined by the op’s private flags:

  • Default (string): Lexicographic comparison via cmp.
  • Numeric (OPpSORT_NUMERIC, 0x01): Floating-point comparison.
  • Custom block (OPpSORT_BLOCK, 0x20): A CV on the stack is used as the comparator. $a and $b are set in the current package via cached cells and the CV is executed using the multicall pattern (pad + call frame set up once, only $a/$b updates per comparison) with a merge-sort algorithm.
  • Descend (OPpSORT_DESCEND, 0x08): Reverses the final result.

Array arguments are flattened before sorting.

Synopsis

my @sorted = sort @list;                    # lexicographic
my @sorted = sort { $a <=> $b } @list;      # numeric
my @sorted = sort { $b cmp $a } @list;      # reverse lexicographic
my @sorted = sort \&compare, @list;          # named comparator

See Also

reverse, map, grep