This discussion of the sort function is targeted at beginners to perl coding. More experienced perl coders will find nothing new or useful. Sorting lists or arrays is a very common requirement of programs. If you don't know the difference between a list and array don't worry about it. A list is just an array without a name. They both can hold the same type of data: scalars or strings. I will use the terms "list" and "array" to mean the same thing.
The sort() Function
The sort() function sorts a copy of the original list and returns a new list. This means you can't use the sort() function in a void context like you can with some of perls other built-in functions:
Expand|Select|Wrap|Line Numbers
- sort(@array); # bad - void context
Expand|Select|Wrap|Line Numbers
- @sorted = sort(@arrray);
Expand|Select|Wrap|Line Numbers
- @array = sort(@arrray);
Perl's built-in function for sorting is generally not much use with real-world data. The default sort is by standard string comparison. To the uninitiated perl coder this can be quite confusing. Lets look at an example.
Expand|Select|Wrap|Line Numbers
- @array = qw(@foo 1 32 11 4 2 44 22 !bar Mary mary Adam ant xxx XXX);
- @sorted = sort (@array);
- print "$_\n" for @sorted;
Expand|Select|Wrap|Line Numbers
- !bar
- 1
- 11
- 2
- 22
- 32
- 4
- 44
- @foo
- Adam
- Mary
- XXX
- ant
- mary
- xxx
To sort data in descending order prefix the sort function with the reverse function:
Expand|Select|Wrap|Line Numbers
- @sorted = reverse sort (@array);
Expand|Select|Wrap|Line Numbers
- @sorted = sort {$b cmp $a} @array; # descending order same as reverse sort above
- @sorted = sort {$a cmp $b} @array; # ascending order same as the default sort
Part Two will discuss more advanced ways to sort data using perl.
This article is protected under the Creative Commons License .