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 <bdfoy@cpan.org>
-
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 How to display code and escape characters
are good places to start.