Perl sort
last modified November 25, 2026 Perl 5.44
The Perl sort function takes a list and returns its elements in
sorted order. By default it compares the values as strings. A comparison block
lets us choose a numeric, reverse or application-specific order.
This article covers the basics: the default order, numeric sorting, the comparison block, sorting hash keys and records, and picking the top items. Sorting by several keys, sort stability and the Schwartzian transform are covered in Perl advanced sorting.
Default string sorting
Without a comparison block, sort orders the values as strings,
character by character.
#!/usr/bin/perl
use warnings;
use v5.34.0;
my @names = ('Pear', 'apple', 'plum', 'Banana');
my @sorted = sort @names;
say "@sorted";
say "@names";
The sorted list is assigned to a new array. sort does not change
the array it receives, so @names keeps its original order.
The comparison is case-sensitive and uses character codes. All uppercase
letters come before all lowercase letters, which is why Banana
and Pear are placed before apple.
$ perl strings.pl Banana Pear apple plum Pear apple plum Banana
Numbers sorted as strings
The default string order is a common source of bugs when the list holds numbers. Each number is compared as text, one digit at a time.
#!/usr/bin/perl use warnings; use v5.34.0; my @numbers = (40, 3, 100, 12, 9); my @sorted = sort @numbers; say "@sorted";
The string "100" comes before "12" because the
second character 0 is smaller than 2. Likewise,
"40" comes before "9". The result is not what we
want for numbers.
$ perl numbers_wrong.pl 100 12 3 40 9
Numeric sorting
To sort numbers, we pass a comparison block that uses the numeric comparison
operator <=>, often called the spaceship operator.
#!/usr/bin/perl
use warnings;
use v5.34.0;
my @numbers = (40, 3, 100, 12, 9);
my @sorted = sort { $a <=> $b } @numbers;
say "@sorted";
say 3 <=> 12;
say 12 <=> 12;
say 100 <=> 12;
Inside the block, sort sets the special variables
$a and $b to the two elements being compared. The
block must return a negative number, zero or a positive number when
$a should come before, is equal to, or should come after
$b. The <=> operator returns exactly these
values: -1, 0 and 1.
$a and $b are package variables that
strict lets us use without a declaration. We must not declare them
with my. The string counterpart of <=> is
cmp; the default order is the same as
sort { $a cmp $b }.
$ perl numbers.pl 3 9 12 40 100 -1 0 1
Descending order
To sort in descending order, we swap $a and $b in
the comparison block. Another way is to reverse the sorted list.
#!/usr/bin/perl
use warnings;
use v5.34.0;
my @numbers = (40, 3, 100, 12, 9);
my @words = qw(pear apple plum banana);
my @big_first = sort { $b <=> $a } @numbers;
my @z_to_a = sort { $b cmp $a } @words;
my @reversed = reverse sort { $a <=> $b } @numbers;
say "@big_first";
say "@z_to_a";
say "@reversed";
{ $b <=> $a } puts the larger numbers first and
{ $b cmp $a } sorts the words from z to a. The
reverse function gives the same result for the numbers, but it
needs an extra pass over the list. Swapping the variables is the usual idiom.
$ perl descending.pl 100 40 12 9 3 plum pear banana apple 100 40 12 9 3
Case-insensitive sorting
A comparison block can transform the values before it compares them. Here we compare the case-folded forms of the names.
#!/usr/bin/perl
use warnings;
use v5.34.0;
my @names = ('Pear', 'apple', 'plum', 'Banana', 'Apple');
my @by_case = sort @names;
my @no_case = sort { fc($a) cmp fc($b) } @names;
say "@by_case";
say "@no_case";
The fc function returns the case-folded form of a string, which
is meant for case-insensitive comparisons; it is enabled by
use v5.34.0. The words apple and
Apple fold to the same string, so their order is left to
sort. For language-specific collation, use the
Unicode::Collate module instead.
$ perl case_insensitive.pl Apple Banana Pear apple plum apple Apple Banana Pear plum
Sorting by length
The comparison does not have to look at the values themselves. Any number computed from them can serve as the sort key.
#!/usr/bin/perl
use warnings;
use v5.34.0;
my @words = qw(forest sky mountain at ocean);
my @short_first = sort { length($a) <=> length($b) } @words;
my @long_first = sort { length($b) <=> length($a) } @words;
say "@short_first";
say "@long_first";
We compare the lengths of the words with <=>, since the
lengths are numbers. Swapping $a and $b puts the
longest word first.
$ perl by_length.pl at sky ocean forest mountain mountain forest ocean sky at
Sorting in place
Because sort returns a new list, sorting an array in place means
assigning the result back to the same array.
#!/usr/bin/perl
use warnings;
use v5.34.0;
my @queue = (5, 2, 8, 1);
my @ordered = sort { $a <=> $b } @queue;
say "copy: @ordered";
say "original: @queue";
@queue = sort { $a <=> $b } @queue;
say "in place: @queue";
The first call stores the sorted copy in @ordered and leaves
@queue untouched. The assignment
@queue = sort ... @queue replaces the contents of the array with
its sorted elements. Perl recognizes this form and sorts the array in place
without building a separate copy.
$ perl in_place.pl copy: 1 2 5 8 original: 5 2 8 1 in place: 1 2 5 8
Sorting hash keys
Hashes have no order, so the keys function returns the keys in an
unpredictable order. To print a hash in a fixed order, we sort its keys.
#!/usr/bin/perl
use warnings;
use v5.34.0;
my %scores = (Mira => 91, Alex => 84, Jo => 97, Tom => 78);
say "by name:";
for my $name (sort keys %scores) {
say " $name: $scores{$name}";
}
say "by score:";
for my $name (sort { $scores{$b} <=> $scores{$a} } keys %scores) {
say " $name: $scores{$name}";
}
sort keys %scores lists the names alphabetically. In the second
loop, the comparison block looks up the value of each key, so the names are
ordered by their scores, from the highest to the lowest.
$ perl hash_keys.pl by name: Alex: 84 Jo: 97 Mira: 91 Tom: 78 by score: Jo: 97 Mira: 91 Alex: 84 Tom: 78
Sorting records by a field
References allow a list to hold structured records. The comparison block dereferences the records and compares the chosen field.
#!/usr/bin/perl
use warnings;
use v5.34.0;
my @people = (
{ name => 'Grace', age => 85 },
{ name => 'Ada', age => 36 },
{ name => 'Linus', age => 55 },
);
my @by_age = sort { $a->{age} <=> $b->{age} } @people;
say "$_->{name}: $_->{age}" for @by_age;
my @by_name = sort { $a->{name} cmp $b->{name} } @people;
say join ', ', map { $_->{name} } @by_name;
Each element is a hash reference. The first sort compares the
age fields numerically, the second compares the
name fields as strings. With map we extract the
names of the sorted records and join them into one line.
$ perl records.pl Ada: 36 Linus: 55 Grace: 85 Ada, Grace, Linus
Top items with a slice
To get the largest or smallest items, we sort the list and take its first elements with an array slice.
#!/usr/bin/perl
use warnings;
use v5.34.0;
my @scores = (72, 95, 61, 88, 99, 70, 84);
my @ranked = sort { $b <=> $a } @scores;
my @top3 = @ranked[0 .. 2];
say "top three: @top3";
say "highest: $ranked[0]";
say "lowest: $ranked[-1]";
my ($best) = sort { $b <=> $a } @scores;
say "best: $best";
The slice @ranked[0 .. 2] returns the three highest scores, and
the indexes 0 and -1 give the highest and the lowest score. The last
statement assigns the sorted list to a list of one variable, which keeps only
the first element.
Sorting a whole list just to get its maximum is wasteful for large lists. The
max and min functions of the
List::Util module find these values in a single pass.
$ perl top.pl top three: 99 95 88 highest: 99 lowest: 61 best: 99
Source
sort · perlop: Equality operators · fc · perlfaq4: How do I sort an array by (anything)?
In this article we have sorted lists in Perl: strings and numbers, ascending and descending order, case-insensitive and length-based comparisons, hash keys, records and the top items of a list. See also Perl advanced sorting, Perl map and Perl hash.
Author
List all Perl tutorials.