|Just another Perl shrine|
Complex sortingby vroom (Pope)
|on Dec 31, 1999 at 22:02 UTC||Need Help??|
Ever wanted to sort on a computed value or a certain column in a string within an array. It can get pretty tricky to do right. You only want to compute the value you're sorting on once for each array element not every time you do a comparison throughout the sort.
One key function you'll want to know how to use is map. Map allows you to apply a change to a list and get back a new list with the changes.
There are two ways you can use the map function;
The first example takes a list of words and returns a list of each of those words with the letters reversed. This is done by splitting them, then reversing the resulting array, and then returning the joined array which is the word reversed. The second example takes an array of letters and returns a list of their ascii values;
Now say we want to sort an array that contains 3 columns of numbers separated by spaces. We want to sort this array on the sum of these three numbers.
The first thing we want to do is map the original array to an array with the calculated sums, as well as the original values in it.
We start by doing the basic transform within the innermost map. The current list value comes in as the default variable($_), then we split the columns, add them up, and return [$_, $sum] which contains the original value followed by the computed value for sorting on. We then sort numerically on this computed value. And then use map so the array only contains the original stuff.
This whole process is known as the Schwartzian Transform.
Here's a template for doing complex sorting
This should hopefully give you a better understanding of what is going on when you need to do a complex sort, and hopefully allow you to do it right with very little hassle.