在数组perl中按数字和字母顺序对数字和字符串进行排序

sort numbers numerically and strings alphabetically in an array perl

这是一个非常简单的问题,但我无法解决。我有一个数组

@arr = qw(txt text anothertext 38.09 100.87 0.876)

如何对数组中的数字按数字排序,对字符串按字母顺序排序。所以输出看起来像:

@sorted_as = (anothertext text txt 100.87 38.09 0.876)

或者,

@sorted_des = (txt text anothertext 100.87 38.09 0.876)

抱歉,如果我重复任何问题但找不到合适的答案。

分成 2 个列表,分别对每个列表进行排序,然后合并回 1 个列表。

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";

输出:

anothertext text txt 100.87 38.09 0.876

要同时获取 des,请添加以下行:

@word = reverse @word;
my @sorted_des = (@word, @num);
print "@sorted_des\n";

使用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;

同样,第二个订单可以使用urnrskeysort