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

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



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.