in reply to max value in a hash

my $max = 0; $_ > $max and $max = $_ for values %hashName; print $max;

dave

Replies are listed 'Best First'.
Re: Re: max value in a hash
by liz (Monsignor) on May 31, 2004 at 09:31 UTC
    This approach will not give the correct result if all of the values are negative:
    my %hashName = (a => -1, b => -2, c => -3); my $max = 0; $_ > $max and $max = $_ for values %hashName; print $max; __END__ 0 # expected -1
    Of course, if you are sure that all values are positive numeric values, there is no problem. But it is something to keep in mind in general, I think.

    Liz

      And to add in general use of situations like this (for min and max) use 'each' first. Modified version from above.
      my %hashName = (a => -1, b => -2, c => -3); my $max = $hash{each %hashName}; $_ > $max and $max = $_ for values %hashName; print $max;
      And you'll the scalar set as one in the hash in the beginning.
Re: Re: max value in a hash
by rsiedl (Friar) on May 31, 2004 at 09:18 UTC
    thanks dave