sort_function

Sorting

The sort function sorts a list (an array). The default is to sort alphabetically. However, you can define your own sorts to get around numbers and complex data structures.

Sort an array of strings

This gives you the following output:

Sort an array of numbers

The Perl sort function sorts by strings instead of by numbers. If you were to use:

The output you would see would be:

To sort numerically, declare your own sort block and use the flying saucer operator <=>:

The output would now be:

Note that $a and $b do not need to be declared, even with use strict on, because they are special sorting variables.

Sorting backwards

To sort backwards you need to declare your own sort block, and simply put $b before $a.

For example, the standard sort is as follows:

The output would be:

To do the same, but in reverse order:

The output is:

And for numbers:

The output is:

Of course, in both these cases there is another way:

The output is:

And

The output is:

Sorting hashes

You can use sort to order hashes. For example, if you had a hash as follows:

And you wanted to display the fruit sorted alphabetically, you could do this:

Output:

If you wanted to sort the same hash by the values (i.e. the number beside each fruit), you could do the following:

Output:

Sorting complex data structures

You can also use sort to sort more complex data strucutes. For example, if you had an array of hashes:

And you wish to display the data about the uses, in alphabetical order, you could do the following:

The output is:

Providing a sort subroutine

Rather than writing the code inline, you can also pass in a subroutine name. The subroutine needs to return an integer less than, equal to, or greater than 0. Do not modify the $a and $b variables as they are passed in by reference, and modifying them will probably confuse your sorting.

The output would be:

More

To find out more, run the command:

Scroll to Top