sort numbers numerically and strings alphabetically in an array of hashes perl

北城余情 提交于 2020-05-29 09:55:45

问题


It's a very easy problem but can't get my way around it. I have an array of hashes. The data structure as follows:

my @unsorted = (
    {
        'key_5' => '14.271 text',
        # ...
    },
    {
        'key_5' => 'text',
        # ...
    },
    {
        'key_5' => '13.271 text',
        # ...
    },
    {
        'key_5' => 'etext',
        # ...
    },
);

How can I sort the array based on key_5 of the hash. The string part should be sorted alphabetically. and where the key is number string (format is always like this),it should be sorted numerically (ignoring the string part completely). So the output would look like, either:

my @sorted = (
    {
        'key_5' => 'etext',
        # ...
    },
    {
        'key_5' => 'text',
        # ...
    },
    {
        'key_5' => '13.271 text',
        # ...
    },
    {
        'key_5' => '14.271 text',
        # ...
    },
);

So, the array elements are sorted based on key_5 of the hash elements.

Sorry if I duplicate any question but could not find a suitable answer.


回答1:


Using Sort::Key::Natural:

use Sort::Key::Natural qw( natkeysort );

my @sorted = natkeysort { $_->{key_5} } @unsorted;

The above produces the following from your input:

[
    {
        'key_5' => '13.271 text'
        # ...
    },
    {
        'key_5' => '14.271 text'
        # ...
    },
    {
        'key_5' => 'etext'
        # ...
    },
    {
        'key_5' => 'text'
        # ...
    },
]

If that's not good enough, you can use the following:

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;


来源:https://stackoverflow.com/questions/62069381/sort-numbers-numerically-and-strings-alphabetically-in-an-array-of-hashes-perl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!