首页 > 解决方案 > 在数组 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)

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

标签: perlsortingnumericalphabetical-sort

解决方案


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

推荐阅读