in reply to Sort Hash by Size of the Arrays it References

Make judicious use of dereferencing and the sort() function
my %hash = (foo => [1..2], bar => [1..3], baz => [1]); my @keys = sort { @{$hash{$a}} <=> @{$hash{$b}} } keys %hash; print "$_ - @{$hash{$_}}", $/ for @keys; __output__ baz - 1 foo - 1 2 bar - 1 2 3

HTH

_________
broquaint

Replies are listed 'Best First'.
Re:x2 Sort Hash by Size of the Arrays it References (mention scalar context explicitly)
by grinder (Bishop) on May 02, 2002 at 13:41 UTC
    Yep, no argument with that.

    The only thing I would add is that my personal taste is to mention explicitly when I am using arrays in scalar context. A newbie^W^WSomeone looking at that code might wonder whether entire arrays were being compared, and if so, how?

    Saying sort { scalar @{$hash{$a}} <=> scalar @{$hash{$b}} } keys %hashprovides a more explicit idea of what is going on, the fact that the number of elements in the arrays are being compared. Hmm, of course the person might not realise that an array in scalar context gives the number of elements, but at least the scalar keyword gives them some to ponder and hopefully understand.


    print@_{sort keys %_},$/if%_=split//,'= & *a?b:e\f/h^h!j+n,o@o;r$s-t%t#u'