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

标签 perl sorting numeric alphabetical-sort

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

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

关于perl - 在数组 perl 中按数字顺序对数字进行排序,并按字母顺序对字符串进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62065124/

相关文章:

python - 排序一个巨大的文本文件并进行二进制搜索

arrays - 如何在线性时间内对二进制数组进行排序?

jquery - 如何通过下拉列表的更改根据数据属性对 div 进行排序

c++ - C++验证数字输入中的逗号位置

c++ - 防止长时间运行平均溢出?

perl - perl中的bless和tie有什么区别?

regex - 删除指定字符之间的所有内容,包括多行

Perl - 使用指针和索引进行二进制解包

perl - Perl Web 编程的 MVC 框架?

sql - 在Oracle中查找不包含数字数据的行