Sorting an Array

The sort function sorts an array. By default, the sort function sorts in ASCII order. For example:

my @array = qw(John Mark Ann); 
my @sorted = sort @array; 
print "@sorted\n";

This prints the following:

Ann John Mark

To sort an array in numerical order, use the statement

@result = sort {$a <=> $b}, @unsorted;

Note that this code uses an advanced feature of sort that is discussed in further detail in Chapter 7, “Subroutines and Modules.”

Get Perl for C Programmers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.