Advanced Sorting

Sorting array elements

The built-in sort function sorts elements in a list by ascending ASCII 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/bin/perl

#################################################
print "\nSTRINGS:\n";
#################################################
@strings = ("cc", "aa", "bb");

print "Original:       @strings\n";

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

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

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

print "Original:       @numbers\n";

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

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

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

print "original:       @array\n";

@sorted = sort (@array);
print "Default ASCII 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: @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 ASCII sort:  aa bb cc
Sort by char:        aa bb cc

NUMBERS:
Original:            3 57 12
Default ASCII 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.


Table of Contents.
Next