Tweet

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

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

    my @strings = ("Becky", "Simon", "Bianca", "Steven", "Greg", "Andrew");

    my @sorted_strings = sort @strings;
    print "@sorted_strings\n";

This gives you the following output:

    Andrew Becky Bianca Greg Simon Steven

Sort an array of numbers

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

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

    my @numbers = (23, 1, 22, 7, 109, 9, 65, 3);

    my @sorted_numbers = sort @numbers;
    print "@sorted_numbers\n";

The output you would see would be:

    1 109 22 23 3 65 7 9

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

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

    my @numbers = (23, 1, 22, 7, 109, 9, 65, 3);

    my @sorted_numbers = sort {$a <=> $b} @numbers;
    print "@sorted_numbers\n";

The output would now be:

    1 3 7 9 22 23 65 109

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

To find out more, see the tutorial Sorting in perl, or run the command:

    perldoc -f sort
[Top]