perlcat has asked for the wisdom of the Perl Monks concerning the following question:

Dear Perlmonks,

I am using the code below to sort a hash by the length of its keys in ascending order.

On top of that, I would like the keys to be also sorted alphabetically.

Could someone help me out? Many thanks.

foreach my $key (sort hashKeyLengthAsc (keys(%count))) [...] } sub hashKeyLengthAsc { length($a) <=> length($b) }

Replies are listed 'Best First'.
Re: Sort hash by key length and alphabetically
by moritz (Cardinal) on Jul 22, 2010 at 06:51 UTC
    length($a) <=> length($b) || $a cmp $b
    Perl 6 - links to (nearly) everything that is Perl 6.
Re: Sort hash by key length and alphabetically
by salva (Canon) on Jul 22, 2010 at 06:54 UTC
    my @sorted = sort { length($a) <=> length($b) or $a cmp $b } keys %count;
Re: Sort hash by key length and alphabetically
by davido (Cardinal) on Jul 22, 2010 at 08:45 UTC

    Note that depending on what you consider to be alphabetical order, you may need to use locale; and tweak that pragma's settings to get cmp to do what you want. See perlop and perllocale. The idea is that "ABCDEabcde", "AaBbCcDdEe", "aAbBcCdDeE", among others can all be valid sorting outcomes, but unless you specify, you may get an order you're not wanting.


    Dave