How to sort numbers in Perl

51,821

Solution 1

You can pass a custom comparison function to Perl's sort routine. Just use:

@sorted = sort { $a <=> $b } @unsorted;

The sort function accepts a custom comparison function as its first argument, in the form of a code block. The {...} part is just this code block (see http://perldoc.perl.org/functions/sort.html ).

sort will call this custom comparison function whenever it needs to compare two elements from the array to be sorted. sort always passes in the two values to compare as $a, $b, and the comparison function has to return the result of the comparison. In this case it just uses the operator for numeric comparison (see http://perldoc.perl.org/perlop.html#Equality-Operators ), which was probably created just for this purpose :-).

Solution shamelessly stolen from "Perl Cookbook", Chapter 04 Sub-chapter 15 (buy the book - it's worth it!)

Solution 2

Supply a comparison function to sort():

# sort numerically ascending
my @articles = sort {$a <=> $b} @files;

# sort numerically descending
my @articles = sort {$b <=> $a} @files;

The default sort function is cmp, string comparison, which would sort (1, 2, 10) into (1, 10, 2) . <=> , used above, is the numerical comparison operator.

Solution 3

Perl's sort by default sorts alphabetically in ASCII order. To sort numerically you can use:

@sorted = sort { $a <=> $b } @_;

Solution 4

This is a Perl FAQ. From the command line:

perldoc -q sort

perlfaq4: How do I sort an array by (anything)?

Solution 5

@l = (4109, 4121, 6823, 12967, 12971, 14003, 20186, 1, 3, 4);
@l = sort { $a <=> $b } @l;
print "@l\n"; # 1 3 4 4109 4121 6823 12967 12971 14003 20186

You have to supply your own sorting subroutine { $a <=> $b }

Share:
51,821
Lazer
Author by

Lazer

Updated on July 21, 2022

Comments

  • Lazer
    Lazer almost 2 years
    print "@_\n";
    4109 4121 6823 12967 12971 14003 20186
    

    How do I sort it in Perl?

    Using @sorted = sort(@_); gives me an alphabetical ordering:

    13041 13045 14003 20186 4109 4121 6823
    

    How do I get a numerical ordering? Does Perl have built-in functions for merge-sort, insertion-sort, etc.?