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

I have a hash in which each mapping references an array. Anyone know how I could sort the hash based on the size of the referenced arrays?

Thus:
key0 -> (f, a)
key1 -> (a, b, c, d, e)
key2 -> (g)
key3 -> (h, i, j)

From this example I want to generate the output

key2 -> 1
key0 -> 2
key3 -> 3
key1 -> 5

I.e. The keys are sorted in ascending order based on the size of their referenced arrays (and I want to print the above keys/sizes to a text file).

Best wishes, Arun

  • Comment on Sort Hash by Size of the Arrays it References

Replies are listed 'Best First'.
Re: Sort Hash by Size of the Arrays it References
by broquaint (Abbot) on May 02, 2002 at 10:09 UTC
    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

      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'