Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: max value in a hash

by mscharrer (Hermit)
on Sep 15, 2008 at 08:28 UTC ( [id://711408]=note: print w/replies, xml ) Need Help??


in reply to max value in a hash

Hi, while you already got a solution for your problem I would like to comment on your code. You seem to use a foreach loop only to abort it in the first iteration which you don't really have to in Perl. It looks very C'ish to me.

First, instead of:

my $i = 0; foreach (sort sortHash (keys (%hashName))) { if ($i == 0) { $max = $hashName{$_}; last } } # end-foreach
you could write:
foreach (sort sortHash (keys (%hashName))) { $max = $hashName{$_}; last; } # end-foreach
because there is no need for the $i when you just check for 0.

Second, even easier in Perl, you can index returned lists when you put them in ( ):

my $max = ( sort sortHash (keys (%hashName)) )[0]; # also possible: my $min = ( sort sortHash (keys (%hashName)) )[-1];
or simply by doing an array assignment:
my ($max) = sort sortHash (keys (%hashName));
also the ( ) around and after keys aren't necessary and avoiding them would make the code more readable.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://711408]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (8)
As of 2024-04-19 15:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found