Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??

Hi, I've recently been learning a bit of perl and this site has been super helpful, so thanks to everyone who contributes.

Anyway, I've come across a problem I cannot seem to be able to figure out. I'm trying to find the coresponding key for the highest value of a hash.

My attempt is:

#!/usr/bin/perl use warnings; use strict; my %hash= ( '1', '8', '2', '6', '3','3' ,'4','7'); my $highest =0; while (my ($key, $value) = each %hash) { $highest=$key if ($highest < $value) ; print "$key key has a value $value \n"; } print "$highest key has the highest value\n";

and my results look like:

4 key has a value 7 1 key has a value 8 3 key has a value 3 2 key has a value 6 2 key has the highest value

Where as I am trying to get the last line to say "1 key has the highest value" since the value of "1" is "8"... Both keys 1 and 4 have a higher value than 2.

any tips are much appreciated.

In reply to highest value in hash by maciej

Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or or How to display code and escape characters are good places to start.
Log In?

What's my password?
Create A New User
Domain Nodelet?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (6)
As of 2022-08-11 11:45 GMT
Find Nodes?
    Voting Booth?

    No recent polls found