Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

comment on

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

Not that there is anything wrong with the other solutions, but here is another one. I sort the keys by values, then use a while loop to figure out where the highest value ends in the list of sorted keys, @keys. Once I know that, I slice @keys to get the right keys.

#!/usr/bin/perl my %h = ( red => 2, pink => 1, orange => 4, black => 3, blue => 4, green => 3, ); my $i = 0; my @keys = sort { $h{$b} <=> $h{$a} } keys %h; 1 while( $h{$keys[++$i]} == $h{$keys[0]} ); my @largest = @keys[0..$i-1]; print qq|Largest are "@largest"\n|;

I had a solution that used grep, but that's stupid since I don't need to go through the rest of the elements once I know I've seen the highest ones.

#!/usr/bin/perl use strict; my %h = ( red => 2, pink => 1, orange => 4, black => 3, blue => 4, ); my @keys = sort { $h{$b} <=> $h{$a} } keys %h; my @largest = grep { $h{$_} == $h{$keys[0]} } @keys; print qq|Largest are "@largest"\n|;
brian d foy <>

In reply to Re: printing largest hash value by brian_d_foy
in thread printing largest hash value by Anonymous Monk

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 browsing the Monastery: (3)
As of 2022-05-27 06:52 GMT
Find Nodes?
    Voting Booth?
    Do you prefer to work remotely?

    Results (94 votes). Check out past polls.