Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Print key when sorting hash by value

by Anonymous Monk
on Sep 26, 2014 at 16:04 UTC ( [id://1102157]=perlquestion: print w/replies, xml ) Need Help??

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

Dear Monks, Hoping you can help. I have a hash of strings which I want to sort by string length ( which I can do). However I also want to print out the hash key. Thanks.
foreach my $value ( sort { length($b) <=> length($a) } values %has +h ) { print "Value: $value\n"; print "Key: ???\n"; }

Replies are listed 'Best First'.
Re: Print key when sorting hash by value
by choroba (Cardinal) on Sep 26, 2014 at 16:08 UTC
    Sort the keys by the lengths of the values:
    for my $key (sort { length($hash{$a}) <=> length($hash{$b}) } keys %ha +sh) { print "$key : $hash{$key}\n"; }
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
      Thanks for your speedy reply! You're the best, thanks!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1102157]
Approved by farang
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (5)
As of 2024-04-26 07:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found