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

Viewed 159

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.

Important: Cannot use any perl packages that are not shipped with native perl installation. Using perl 5.18

1 Answers

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;
Related