Reputation: 147
It's a very easy problem but can't get my way around it. I have an array
@arr = qw(txt text anothertext 38.09 100.87 0.876)
How can I sort the numbers in the array numerically and the strings alphabetically. So the output would look like, either:
@sorted_as = (anothertext text txt 100.87 38.09 0.876)
or,
@sorted_des = (txt text anothertext 100.87 38.09 0.876)
Sorry if I duplicate any question but could not find a suitable answer.
Upvotes: 2
Views: 945
Reputation: 385645
Using Sort::Key::Multi:
# urns = (u)nsigned int, (r)everse (n)umber, (s)tring
use Sort::Key::Multi qw( urnskeysort );
my @sorted =
urnskeysort {
/^[0-9]/
? ( 1, $_, "" )
: ( 0, 0, $_ )
}
@unsorted;
Similarly, you can use urnrskeysort
for the second order.
Upvotes: 0
Reputation: 62037
Divide into 2 lists, sort each individually, then combine back into 1 list.
use warnings;
use strict;
my @arr = qw(txt text anothertext 38.09 100.87 0.876);
my @word = sort {$a cmp $b} grep { /^[a-z]/i } @arr;
my @num = reverse sort {$a <=> $b} grep { !/^[a-z]/i } @arr;
my @sorted_as = (@word, @num);
print "@sorted_as\n";
Outputs:
anothertext text txt 100.87 38.09 0.876
To get des also, add these lines:
@word = reverse @word;
my @sorted_des = (@word, @num);
print "@sorted_des\n";
Upvotes: 4