in reply to largest number inside array/hash

And in the spirit of TIMTOWTDI:

: : my $max=0; map { $max=($max < $_ ? $_ : $max )} @array_of_nums; : : or a hash... my $kmax=0; map { $kmax =($kmax < $_ ? $_ : $kmax) } keys %hash_nums;

Replies are listed 'Best First'.
Re: Re: largest number inside array/hash
by RMGir (Prior) on Apr 06, 2004 at 20:54 UTC
    my $max=0;

    That's the classic max (or min) implementation error. What if all numbers are negative?

    $ perl -e'@a=qw(-1 -2 -3 -4 -5); $max=0; printf "Answer allegedly is %d\n",map { $max=($max < $_ ? $ +_ : $max )} @a;' Answer allegedly is 0 $ perl -e'@a=qw(-1 -2 -3 -4 -5); $max=$a[0]; # Or shift @a, if you can be destructive printf "Answer allegedly is %d\n",map { $max=($max < $_ ? $ +_ : $max )} @a;' Answer is -1

    Mike