在一个数组中按数字和字符串的字母顺序排序,perl

问题描述 投票:2回答:2

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

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

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

perl sorting numeric alphabetical-sort
2个回答
4
投票

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

0
投票

使用... 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 为二阶。

© www.soinside.com 2019 - 2024. All rights reserved.