We can take the greatest five from a hash without sorting. I don't know if that makes it more efficient. For example, the following prints the five colors having the longest wavelengths.
#!/usr/bin/perl
use strict;
use warnings;
my %d = (violet => 400,
red => 650,
indigo => 445,
orange => 590,
blue => 475,
yellow => 570,
green => 510);
my @p;
foreach my $r (0 .. 4){
foreach my $k (keys %d){
if (!defined$p[$r]
or $d{$k} > $d{$p[$r]}){
$p[$r] = $k;
}
}
delete $d{$p[$r]};#After saving one of top 5, delete it from hash
}
print join "\n", @p;
d5e5
Practically a Posting Shark
831 posts since Sep 2009
Reputation Points: 162
Solved Threads: 163
Skill Endorsements: 1
Question Answered as of 1 Year Ago by
d5e5
and
sfandino