perl - 在数组 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";
推荐阅读
- php - 检查嵌套数组值,如果匹配:合并两者的数据
- javascript - 在 Selenium Python 中单击元素未触发事件(事件键不在数据文件中)
- ios - 如何在 Xcode 中从物理设备模拟应用程序时修复错误“dyld:未加载库:@rpath/Realm.framework/Realm”
- vba - 从 Outlook 中打开 Windows 资源管理器以选择模板
- javascript - 没有 jQuery 的 jQuery $.when().done() 等价物
- batch-file - 将文件从一个位置复制到另一个位置。仅当源位置较新时才覆盖文件。批处理脚本
- javascript - 使用异步函数 TypeScipt 导入 Excel 文件
- sql-server - 给定字符串的字符移位
- java - 如何改进我的 Java 代码以生成所有已知的完美数字?
- angular - 无法列出惰性路由:未知模块 './src/app/app.module#AppModule'