Summary: How to sort a Perl string array (when you don't have to worry about whether the strings are all uppercase or lowercase).
Perl excels at a number of tasks, especially text-processing, and if you have an array of strings, and all of the elements in the array are either uppercase or lowercase, sorting your string array is very easy. In this tutorial I'll show how to sort an array of strings, and will also show how to sort your string array in reverse order.
NOTE: If you want to sort a Perl string array in a case-insensitive manner, please read our "Sorting a Perl string array in a case-insensitive manner" tutorial. It provides a different solution than what is shown here.
Our example Perl array
In all of my examples I'll work with my usual Perl array of pizzas, @pizzas
, which I define like this:
@pizzas = qw(pepperoni cheese veggie sausage);
As you may remember, this qw
syntax creates an array of strings (qw
stands for "quoted words").
Now let's look at how to sort these pizzas.
Perl sort function - printing the pizzas in sorted order
If all of your strings are lowercase, as in this example, sorting your array of strings is very easy. You just use the Perl sort function:
@sorted_pizzas = sort @pizzas;
For instance, if I print my list of @sorted_pizzas
, like this:
print "@sorted_pizzas\n";
I will get the following output:
cheese pepperoni sausage veggie
It's very important to note that this example only works because all of my strings are in lowercase. By default, the Perl sort function sorts the array elements it is given in ASCII order, so this approach only works if all of your strings are either uppercase or lowercase. (Again, if you need a case-insensitive sorting algorithm, please read our "Sorting a Perl string array in a case-insensitive manner" tutorial.)
Two things to remember
The first important thing to remember about this sorting approach is that the Perl sort function doesn't actually modify the @pizzas
array; it just returns a sorted array from the given array. In my case I assigned my sorted results to a new variable named @sorted_pizzas
, but I could have just as easily made the assignment like this:
@pizzas = sort @pizzas;
And again, just to emphasize the point, the second important thing to remember is that this Perl array sort approach is case-sensitive.
Reversing the sort order
It turns out that sorting an array in reverse order is also very easy with Perl. Just use this syntax:
@reverse_sorted_pizzas = reverse sort @pizzas;
If I now print my list of @reversesortedpizzas
, like this:
print "@reverse_sorted_pizzas\n";
I will get the following output:
veggie sausage pepperoni cheese
That's pretty cool isn't it? As mentioned, I'll add an article out here shortly about how to make this Perl array sort functionality case-insensitive.