Advanced Sorting

Sorting array elements

The built-in sort function sorts elements in a list by ascending ACSII order.

To apply other sort mechanisms, e.g. numerical sort or a combination of several levels of numerical and alphabetical sort, you have to define a comparison subroutine.
For example,

  @array2 =  sort  subname (@array1);
The subroutine will make use of the following:

Read more about advanced sorting in the "Learning Perl" book, pp. 156-159 or in the "Programming Perl" book (2nd ed. pp.217-219, 3rd ed. pp. 789-793).

Example

#!/usr/local/bin/perl
use strict;

my (@strings, @sorted, @numbers, @array);
#################################################
print "\nstrings:\n";
#################################################
@strings = ("cc", "aa", "bb");

print "original:       @strings\n";

@sorted = sort (@strings);
print "default sort:   @sorted\n";

@sorted = sort by_char (@strings);
print "sort by char:   @sorted\n";

#################################################
print "\nnumbers:\n";
#################################################
@numbers = (3, 57, 12);

print "original:       @numbers\n";

@sorted = sort (@numbers);
print "default sort:   @sorted\n";

@sorted = sort by_number (@numbers);
print "sort by number: @sorted\n";

#################################################
print "\ncombination:\n";
#################################################
@array = ("cc", 3, 57, "aa", 12, "bb");

print "original:       @array\n";

@sorted = sort (@array);
print "default sort:   @sorted\n";

@sorted = sort by_number (@array);
print "sort by number: @sorted\n";

@sorted = sort by_num_char (@array);
print "sort by number and then by char:\n",
      "                @sorted\n";

#################################################
print "\n";
#################################################

# subroutines

sub by_char {    # redundant, this is the default
   $a cmp $b;
}

sub by_number {
   $a <=> $b;
}

sub by_num_char {
   $a <=> $b || $a cmp $b;
}

#################################################

Output:

strings:
original:       cc aa bb
default sort:   aa bb cc
sort by char:   aa bb cc

numbers:
original:       3 57 12
default sort:   12 3 57
sort by number: 3 12 57

combination:
original:       cc 3 57 aa 12 bb
default sort:   12 3 57 aa bb cc
sort by number: cc aa bb 3 12 57
sort by number and then by char:
                aa bb cc 3 12 57

#################################################

The comparison functions are ordinary subroutines. They may have any name you want, and in principle they may contain additional commands.


Next
Table of Contents.