Sorting Arrays

Let's learn how to sort elements of an array in Perl in this lesson.

Sorting array of strings

sort() is a built-in subroutine in Perl that can be used to sort an array of strings in ascending order. Let’s run the code below to see an example of the sort() subroutine:

Press + to interact
#defining and array
@fruits = ('Rasberry', 'Orange', 'Apricot','Banana', 'Apple','Olive' );
@fruits = sort(@fruits); #applying the sort function
print("@fruits"); #printing the sorted array

Sorting array of numbers

The default usage of the sort() subroutine is to sort the array of strings. If we use it with numbers, then the numbers will be treated as strings. To sort the numbers numerically, this subroutine is used with the spaceship operator ($a <=> $b) before the array name, enclosed in { } curly braces.

$a and $b are special package variables. The sort() subroutine iterates over the elements of the array and assigns the values to these package variables to compare them numerically using the spaceship operator. Let’s run the code below to see an example of sort().

Press + to interact
@numbers = (13, 9, 22, 27, 1, 3, -4, 10);
print "Original: @numbers\n\n";
@sorted_numbers = sort { $a <=> $b } @numbers;
print "After sorting: @sorted_numbers";