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.?
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.
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.
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.
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.
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!)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With