Search code examples
perlsortingnumericalphabetical-sort

sort numbers numerically and strings alphabetically in an array perl


It's a very easy problem but can't get my way around it. I have an array

@arr = qw(txt text anothertext 38.09 100.87 0.876)

How can I sort the numbers in the array numerically and the strings alphabetically. So the output would look like, either:

@sorted_as = (anothertext text txt 100.87 38.09 0.876)

or,

@sorted_des = (txt text anothertext 100.87 38.09 0.876)

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


Solution

  • Divide into 2 lists, sort each individually, then combine back into 1 list.

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

    Outputs:

    anothertext text txt 100.87 38.09 0.876
    

    To get des also, add these lines:

    @word = reverse @word;
    my @sorted_des = (@word, @num);
    print "@sorted_des\n";