Perl sort
last modified October 8, 2026
The Perl sort operator takes a list and returns its
elements in sorted order. By default, it compares values as strings. A
comparison block lets you choose a numeric, reverse, or
application-specific order.
sort returns a sorted list; it does not rearrange the
source array. Assign the result to an array when you want to keep the
sorted values.
Default string sorting
Without a comparison block, values are sorted in string (lexical) order.
#!/usr/bin/perl
use strict;
use warnings;
use v5.30.0;
my @names = ('Pear', 'apple', 'plum', 'Banana');
my @sorted = sort @names;
say "@sorted";
$ perl strings.pl Banana Pear apple plum
String comparison is case-sensitive. It compares character values rather than treating digit-containing strings as numbers.
Numeric sorting
Use the numeric comparison operator <=> to sort
numbers in ascending order. The comparator's result is negative, zero, or
positive when $a is less than, equal to, or greater than
$b.
#!/usr/bin/perl
use strict;
use warnings;
use v5.30.0;
my @numbers = (40, 3, 100, 12, 3);
my @ascending = sort { $a <=> $b } @numbers;
my @descending = sort { $b <=> $a } @numbers;
say "ascending: @ascending";
say "descending: @descending";
$ perl numbers.pl ascending: 3 3 12 40 100 descending: 100 40 12 3 3
$a and $b are special package variables
supplied to the sort comparator. They are exempt from strict
'vars'; do not declare them with my.
Custom string sorting
A comparator can apply a transformation before comparing. This example sorts names without regard to letter case:
#!/usr/bin/perl
use strict;
use warnings;
use v5.30.0;
my @names = ('Pear', 'apple', 'plum', 'Banana');
my @sorted = sort { lc($a) cmp lc($b) } @names;
say "@sorted";
$ perl case_insensitive.pl apple Banana Pear plum
For locale-aware ordering or language-specific collation, use a
suitable collation module rather than assuming lc plus
cmp implements every language's sorting rules.
Sorting records by a field
References allow a list to contain structured records. Dereference the records in the comparator to choose a field.
#!/usr/bin/perl
use strict;
use warnings;
use v5.30.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;
$ perl records.pl Ada: 36 Linus: 55 Grace: 85
Sorting keys and preserving the original
Hash iteration order is not a presentation order. Sort the keys when displaying their associated values.
use strict;
use warnings;
use v5.30.0;
my %scores = (Mira => 91, Alex => 84, Jo => 97);
for my $name (sort keys %scores) {
say "$name: $scores{$name}";
}
To sort an array without changing it, keep the result in a different array:
my @original = (4, 1, 3);
my @ordered = sort { $a <=> $b } @original;
See Perl map for transforming lists and Perl hash for working with hash keys and values.
Source
Author
List all Perl tutorials.