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.$aand$bare 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/$bupdates 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
Implementation Notes
perl5 (pp_sort.c): OPpSORT_NUMERIC (0x01): use C-level numeric compare (detected at compile time) OPpSORT_DESCEND (0x08): reverse order OPpSORT_BLOCK (0x20): comparison sub on stack (custom comparator) Default (no flags): lexical string sort via sv_cmp
perl5 detects { $a <=> $b } at compile time (S_simplify_sort in op.c), sets OPpSORT_NUMERIC, and deletes the comparison block entirely. The sort then uses a C-level SvIV compare — zero sub calls.