sorting - In Perl, how do I print hash keys in order of their (numerical) values? -


i have hash in keys strings , values single-digit numbers; here's slice of said hash:

      'f92a0d43-a230-4bfd-b580-9eac5e0ce6cf' => 7,       '26c4b622-969f-4861-bbab-dd506ea4b00a' => 1,       'afb1f925-4109-4b1d-967f-3958106e0bc3' => 3,       'a099a6dc-0c66-4683-94c3-29d6ef6947fd' => 1,       'e71c4860-224d-4b8d-ae9e-4700e9e65a97' => 2, 

i want print keys in order of descending values. slice listed there, output be:

       'f92a0d43-a230-4bfd-b580-9eac5e0ce6cf' => 7        'afb1f925-4109-4b1d-967f-3958106e0bc3' => 3        'e71c4860-224d-4b8d-ae9e-4700e9e65a97' => 2        '26c4b622-969f-4861-bbab-dd506ea4b00a' => 1        'a099a6dc-0c66-4683-94c3-29d6ef6947fd' => 1 

the order of keys identical values not matter. answers question: in perl, how can print key corresponding maximum value in hash? suggest using sort function; have:

  @values = sort { $b <=> $a } values %id_hash; 

what having trouble printing keys in order.

i tried:

    foreach(@values) {         $cur = $_;         print "$id_hash{$cur}\t$cur\n";     } 

which fails because i'm supplying values rather keys.

i know can print key/value pairs tab-separated file , use unix version of sort i'm sure there's way perl. appreciated.

sort keys values in hash, use sorted keys print.

for $key ( sort { $id_hash{$b} <=> $id_hash{$a} } keys %id_hash ) {     print join( "\t", $key, $id_hash{$key} ), "\n"; } 

this equivalent may little clearer:

my @sorted_keys = sort { $id_hash{$b} <=> $id_hash{$a} } keys %id_hash ;  print "$_\t$id_hash{$_}\n" @sorted_keys; 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -