Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: highest value in hash

by Athanasius (Chancellor)
on Mar 31, 2013 at 02:44 UTC ( #1026319=note: print w/replies, xml ) Need Help??


in reply to highest value in hash

Hello maciej, and welcome to the Monastery!

Expanding on the advice from Anonymous Monk, here is one way to implement the solution:

#! perl use warnings; use strict; my %hash = (1 => 8, 2 => 6, 3 => 3, 4 => 7); my $highest_value; my $highest_key; while (my ($key, $value) = each %hash) { print "$key key has value $value\n"; if (!defined $highest_value || $highest_value < $value) { $highest_key = $key; $highest_value = $value; } } print "The element with key $highest_key " . "has the highest value $highest_value\n" if defined $highest_key +;

Output:

12:36 >perl 591_SoPW.pl 4 key has value 7 1 key has value 8 3 key has value 3 2 key has value 6 The element with key 1 has the highest value 8 12:38 >

Note that this uses < to compare values numerically. To compare the values as strings, you would need to use lt instead:

if (!defined $highest_value || $highest_value lt $value)

Hope that helps,

Update: ++Anonymous Monk for the syntax below: it’s both simpler and more efficient. Confession: I had to re-read the documentation for each to verify that it Does the Right Thing here (it does). :-)

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Replies are listed 'Best First'.
Re^2: highest value in hash (defined)
by Anonymous Monk on Mar 31, 2013 at 04:12 UTC
    Just say no to defined :)
    ... my( $highest_value, $highest_key ) = each %hash; while (my ($key, $value) = each %hash) ...

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1026319]
help
Chatterbox?
[GotToBTru]: I remember hearing about somebody misplacing a list of code phrases or something
[marto]: 12345
[GotToBTru]: the "nuclear codes" are in the case cuffed to the wrist of some guy
[LanX]: not always
[LanX]: it's up to the Supreme commander
[GotToBTru]: we don't have one of those ;)
[LanX]: commander in chief whatever
Discipulus fears to ears this in German..

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (7)
As of 2017-01-20 12:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you watch meteor showers?




    Results (174 votes). Check out past polls.