in reply to finding highest number

Why do something C-style when you can speak simple Perlish?

my @sorted = sort {$b <=> $a} @numbers; my $highest = $sorted[0];

This sorts your array from highest to lowest and puts it in @sorted.

Update: changed "my $highest = $numbers[0];" to "my $highest = $sorted[0];" Many thanks to UnderMine for pointing this out.

John J Reiser
newrisedesigns.com

Replies are listed 'Best First'.
Re: Re: (nrd) finding highest number
by gjb (Vicar) on Dec 05, 2002 at 13:04 UTC

    This may be Perlish, but it is also rather inefficient: O(n*log(n)) vs. O(n).

    If you want to do it the Perlish way, why not use max that can be found in the wonderful List::Util module?

    Just my 2 cents, -gjb-

      Oddly enough, it's more efficient to use sort rather than an explicit Perl loop for for up to a dozen or two elements, if I recall the benchmarks.

      Of course, List::Util has a max function, which would be faster still.

      But don't be so quick to optimize... you may be unoptimizing.

      -- Randal L. Schwartz, Perl hacker
      Be sure to read my standard disclaimer if this is a reply.

Re: Re: (nrd) finding highest number
by UnderMine (Friar) on Dec 05, 2002 at 15:02 UTC
    my $highest =(sort {$b <=> $a} @numbers)[0];
    This is a bit more compact

    Hope it helps
    UnderMine

Re: Re: (nrd) finding highest number
by Anonymous Monk on Dec 05, 2002 at 12:59 UTC
    thanks but i need to keep the order of the array intact for the next stage. ;-)

      You still have your original list in @numbers: sort copies, it doesn't change the original list.

      Hope this helps, -gjb-