I know this question may have been asked a million times but I am stumped. I have an array that I am trying to sort. The results I want to get are
A
B
Z
AA
BB
The sort routines that are available dont sort it this way. I am not sure if it can be done. Here's is my perl script and the sorting that I am doing. What am I missing?
# header
use warnings;
use strict;
use Sort::Versions;
use Sort::Naturally 'nsort';
print "Perl Starting ... \n\n";
my @testArray = ("Z", "A", "AA", "B", "AB");
#sort1
my @sortedArray1 = sort @testArray;
print "\nMethod1\n";
print join("\n",@sortedArray1),"\n";
my @sortedArray2 = nsort @testArray;
print "\nMethod2\n";
print join("\n",@sortedArray2),"\n";
my @sortedArray3 = sort { versioncmp($a,$b) } @testArray;
print "\nMethod3\n";
print join("\n",@sortedArray3),"\n";
print "\nPerl End ... \n\n";
1;
OUTPUT:
Perl Starting ...
Method1
A
AA
AB
B
Z
Method2
A
AA
AB
B
Z
Method3
A
AA
AB
B
Z
Perl End ...
Perl has a built-in sort() function to sort an array of alphabets and numbers. When an array is passed to the sort() function it returns a sorted array.
Perl has two operators that behave this way: <=> for sorting numbers in ascending numeric order, and cmp for sorting strings in ascending alphabetic order.
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.
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.
I think what you want is to sort by length and then by ordinal. This is easily managed with:
my @sortedArray = sort {
length $a <=> length $b ||
$a cmp $b
} @testArray;
That is exactly as the English: sort based on length of a vs b, then by a compared to b.
my @sorted =
sort {
length($a) <=> length($b)
||
$a cmp $b
}
@unsorted;
or
# Strings must be have no characters above 255, and
# they must be shorter than 2^32 characters long.
my @sorted =
map substr($_, 4),
sort
map pack("N/a*", $_),
@unsorted;
or
use Sort::Key::Maker sort_by_length => sub { length($_), $_ }, qw( int str );
my @sorted = sort_by_length @unsorted;
The second is the most complicated, but it should be the fastest. The last one should be faster than the first.
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