Sorting Arrays: From Basic to Advanced
Perl’s sort is one of the language’s most frequently used functions. It’s simple to call, but its power comes from the fact that the comparison block can be as intricate as you need. Below we walk through a handful of real‑world scenarios, starting with the most common usage and progressing to situations where you need a custom comparator or even an external file to drive the order.
Take a typical month list:
Printing the array alphabetically is straightforward. The built‑in sort performs a lexicographic comparison of the string representations of the elements, yielding:
Each name appears on its own line, arranged from A to Z. If you want the list in reverse alphabetical order, prepend the reverse function to the sort list:
Unlike the name “reverse” might suggest, this call does not alter the original array. Instead, reverse creates a new list that is the inverted order of the sorted array. The original @month remains unchanged, which is handy when you need both orders in the same program.
Sometimes you simply want to walk through an array from the last element to the first, without any sorting involved. In that case, drop the sort call entirely:
Now the output begins with December and ends with January. This trick proves useful when you are dealing with logs or time‑stamped data that you want to process in reverse chronological order.
Moving beyond alphabetical ordering, consider a list of strings where case sensitivity matters:





No comments yet. Be the first to comment!