perl - Return all hash key/value pairs with maximum value -


i have hash (in perl) values numbers. need create hash contains key/value pairs first hash value maximum of values.

for example, given

my %hash = (     key1 => 2,     key2 => 6,     key3 => 6, ); 

i create new hash containing:

%hash_max = (     key2 => 6,     key3 => 6, ); 

i'm sure there many ways this, looking elegant solution (and opportunity learn!).

use list::util 'max'; $max = max(values %hash); %hash_max = map { $hash{$_}==$max ? ($_, $max) : () } keys %hash; 

or one-pass approach (similar different answer):

my $max; %hash_max; keys %hash; # reset iterator while (my ($key, $value) = each %hash) {     if ( !defined $max || $value > $max ) {         %hash_max = ();         $max = $value;     }     $hash_max{$key} = $value if $max == $value; } 

Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -