Summary: How to sort Perl arrays, in this case, a Perl integer array.
Sorting a Perl integer array (technically a Perl numeric array) is relatively simple, well, at least once you know the magic formula. The key thing to know is that you need to provide the Perl sort function a helper function (or block of code) that tells it how to sort integers. By default, the Perl sort function sorts arrays in ASCII order, and that's not going to work very well for you.
(This 'helper function' approach is very similar to other languages, like Java, where you provide helper functions like this to help generic sort algorithms sort your lists or arrays.)
A Perl integer array sorting example
Here's a short script that demonstrates how to sort a Perl integer array:
# create the perl array @numbers = (9, 3, 5, 6, 2); # sort the perl array numerically @numbers = sort { $a <=> $b } @numbers; # print the array print "@numbers\n";
To the best of my knowledge, this method for sorting Perl integer arrays was first described in the book Learning Perl, though by now I've probably seen it in hundreds of Perl scripts.
There are longer ways to write this code that might make the code more readable, but I've skipped all of those and gone straight to this solution, which I have seen most-commonly used.
Perl integer array sorting - Discussion
I'm going to keep this short for today, but if you're very new to sorting in Perl, there are a few more things I should mention here:
- The block of code in between the curly braces helps the Perl sort function. In this case, it helps Perl sort the array numerically.
- Perl is being very smart for you here, and automatically assigns the
$a
and$b
variables for you. As an experiment, if you try changing$a
and$b
to other variable names, you'll see that this sort function no longer works.
I've included other Perl array sorting tutorials on this website. Most notably, my tutorial on how to sort a Perl string array is very similar to this approach, except it uses the Perl cmp operator to perform the string comparison.
Perl integer array sorting - Summary
I know I've skipped some other things here, but I'm guessing that most people just want that Perl integer array sorting algorithm, so I'm going to stop here for today. If you have any questions, just leave a note in the Comments section, and I'll get back with you.