in reply to max key-value pair in a hash

Less cute, but (arguably) better readable and the time increases linearly with the number of records:
use strict; use warnings; my %some_hash = ( sunny => .63, cloudy => .17, rainy => .2 ); my @key_list = keys %some_hash; my $max_key = pop @key_list; foreach (@key_list) { $max_key = $_ if $some_hash{$_} > $some_hash{$max_key}; } print $max_key." :: ".$some_hash{$max_key}."\n";

CountZero

"If you have four groups working on a compiler, you'll get a 4-pass compiler." - Conway's Law

Replies are listed 'Best First'.
Re^2: max key-value pair in a hash
by jdporter (Paladin) on Mar 27, 2006 at 15:01 UTC

    For some reason, each strikes me as a slightly more natural way to do this. If nothing else, it avoids the construction of the key list.

    my %h = ( sunny => 0.063, cloudy => 0.017, rainy => 0.020, hellish => 0.103, ); my( $max_key, $max_val ) = each %h; while ( my($k,$v) = each %h ) { $v > $max_val and ($max_key,$max_val) = ($k,$v); } print "$max_key => $max_val\n";
    We're building the house of the future together.