in reply to finding highest number

It's because you're only comparing the current and next numbers in the array. The way I would do it, is keep track of the highest number in another variable. The variable is initialized to the first number in the array.
use strict; my @array = (1, 5, 4, 10, 20, 2, 1, 3, 7); my $highest = $array[0]; foreach (@array) { $highest = $_ if $_ > $highest; } print $highest;
Which gives me 20. I'm sure there are prettier ways, but this seems to work.

Update: and of course, the perlish way would be to use sort. duh. ++newrisedesigns. I need a coffee.

--
"I don't intend for this to take on a political tone. I'm just here for the drugs." --Nancy Reagan

Replies are listed 'Best First'.
Re^2: finding highest number
by diotalevi (Canon) on Dec 05, 2002 at 13:18 UTC

    No... that would be known as the slow way. This is an operation which should only have to traverse the array *once* where sort() has higher overhead (perhaps gjb has it right as O(n*log(n)) versus O(n)).

    The better answer is to use something akin to what you posted. I'd want to check for undefined values as well. For an answer I just copied right from a toy mapping app I just coded up last night.

    sub max { my $m; for (@_) { next unless defined; $m = $_, next unless defined $m; $m = $_, next if $m < $_; } $m }
    __SIG__ use B; printf "You are here %08x\n", unpack "L!", unpack "P4", pack "L!", B::svref_2object(sub{})->OUTSIDE;
Re: Re: finding highest number
by Anonymous Monk on Dec 05, 2002 at 13:09 UTC
    thanks LTjake this is cool, but how could you adapt it to calculate second and third highest numbers also??
          how could you adapt it to calculate second and third highest numbers?

      something like:
      use strict; my @array = (1, 5, 4, 10, 20, 2, 1, 3, 7); my @hi = (0) x 3; # '0' assumes positive #'s foreach (@array) { $_ <= $hi[0] and next; @hi = (sort $a<=>$b, @hi, $_)[-3..-1]; } print "@hi";
      (untested)   (and, as said, of course the sort method would be better, at least for small arrays, and would be even more better for finding the top three values:  (sort ..., @array)[-3..-1] )

        p