Jeremy Kister wrote:
I am trying to optimize some sorting code I have. The data structure is
as follows:
my %hash = (x => [ 'a','b','c' ],
y => [ 'd','e' ],
z => [ 'f' ],
);
The result I expect is simply the highest number of elements. In this
case, the result should be "3" because x has three elements, which is
more than y and z have.
I whipped up two versions of the sort code:
foreach my $key (keys %hash){
if(@{$hash{$key}} > $highest){
$most = @{$hash{$key}};
}
}
#and
my $most = @{$hash{(sort { @{$hash{$b}} <=> @{$hash{$a}} } keys
%hash)[0]}};
I ran each 500,000 times. I expected the second version finish sooner,
but it is noticeably slower than the first.
Can someone show me a better way to get this done ?
How about this?
Rob
use strict;
use warnings;
use List::Util qw/max/;
my %hash = (x => [ 'a','b','c' ],
y => [ 'd','e' ],
z => [ 'f' ],
);
my $most = max map scalar @$_, values %hash;
print $most;
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/