Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort numbers in Perl

Tags:

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

like image 209
Lazer Avatar asked Aug 26 '10 10:08

Lazer


People also ask

How does Perl sort work?

The way sort works in Perl is that it goes over every two elements of the original array. In every turn it puts the value from the left side into the variable $a, and the value on the right side in the variable $b. Then it calls a comparison function.

How do I sort a string in Perl?

Sorting in Perl can be done with the use of a pre-defined function 'sort'. This function uses a quicksort algorithm to sort the array passed to it. Sorting of an array that contains strings in the mixed form i.e. alphanumeric strings can be done in various ways with the use of sort() function.

What does Perl sort return?

Perl sort() function sorts a list and returns a sorted list. The original list remains intact. The sort() function has three forms: sort list; sort block list; sort subroutine_name list.

How do I sort a hash value in Perl?

First sort the keys by the associated value. Then get the values (e.g. by using a hash slice). my @keys = sort { $h{$a} <=> $h{$b} } keys(%h); my @vals = @h{@keys}; Or if you have a hash reference.


1 Answers

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

like image 119
sleske Avatar answered Sep 19 '22 18:09

sleske