views:

131

answers:

6
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.?

+1  A: 

You can predefine function which should be used to comparing values in your array. perldoc -f sort gives you an example:

# sort using explicit subroutine name
sub byage {
   $age{$a} <=> $age{$b};  # presuming numeric
}
@sortedclass = sort byage @class;

<=> operator is used to sort numerically.

@sorted = sort {$a <=> $b} @unsorted;
Konstantin Likhter
+6  A: 

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

@sorted = sort { $a <=> $b } @_;
codaddict
How does this work?
Lazer
@Lazer: See my explanations (I submitted the same answer, just slightly later;-)).
sleske
+5  A: 

From perldoc -f sort:

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

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

eugene y
+7  A: 

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!)

sleske
I'd take that link down, it is distributing copyrighted material without the holder's consent. You could recommend the original work (the Perl Cookbook, Christiansen and Torkington) instead.
Philip Potter
It seems to be a consensus on [Perl] tag that linking to pirated copies of O'Reilly books (or any books) is Bad. Editing to remove
DVK
Sorry, didn't realize the link was to pirated material. Thanks for fixing it.
sleske
Google books often has nice non-pirated material suitable for linking.
daotoad
+1  A: 
@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 }

adamse
+4  A: 

This is a Perl FAQ. From the command line:

perldoc -q sort

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

toolic