这是个很简单的问题,但我无法解决。我有一个哈希数组。数据结构如下。
my @unsorted = (
{
'key_5' => '14.271 text',
# ...
},
{
'key_5' => 'text',
# ...
},
{
'key_5' => '13.271 text',
# ...
},
{
'key_5' => 'etext',
# ...
},
);
我怎么能根据数组中的 key_5
的哈希值。字符串部分应该按字母顺序排序,其中键是 number string
(格式总是这样的),它应该按数字排序(完全忽略字符串部分)。所以输出的结果会是这样的,要么。
my @sorted = (
{
'key_5' => 'etext',
# ...
},
{
'key_5' => 'text',
# ...
},
{
'key_5' => '13.271 text',
# ...
},
{
'key_5' => '14.271 text',
# ...
},
);
所以,数组元素的排序依据是: key_5
的哈希元素。
重要: 不能使用任何没有安装在本地 perl 的 perl 包。使用perl 5.18
使用 排序::键::自然:
use Sort::Key::Natural qw( natkeysort );
my @sorted = natkeysort { $_->{key_5} } @unsorted;
以上从你的输入中产生以下结果。
[
{
'key_5' => '13.271 text'
# ...
},
{
'key_5' => '14.271 text'
# ...
},
{
'key_5' => 'etext'
# ...
},
{
'key_5' => 'text'
# ...
},
]
如果这还不够好,你可以使用以下方法。
use Sort::Key::Multi qw( unskeysort ); # uns = (u)nsigned int, (n)umber, (s)tring
my @sorted =
unskeysort {
$_->{key_5} =~ /^([0-9.]+)\s+(.*)/s
? ( 1, $1, $2 )
: ( 0, 0, $_->{key_5} )
}
@unsorted;