Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi.

What's the code to retrieve the greatest (largest) numerical value in an array (list)?

Thanks,
Ralph.

Replies are listed 'Best First'.
Re: Get biggest value from array
by theorbtwo (Prior) on Aug 25, 2002 at 05:24 UTC

    Like with most things perl, there's more then one way to do it. You could use Quantum::Superpositions, or (sort @array)[-1], or you could do somthing more reasonable, like

    my $max=$array[0]; foreach (@array) { $max=$_ if ($_>$max) }

    Or you could use List::Util::max (which is included with perl >=5.8.0)


    Confession: It does an Immortal Body good.

Re: Get biggest value from array
by bart (Canon) on Aug 25, 2002 at 08:35 UTC
    What's the code to retrieve the greatest (largest) numerical value in an array (list)?

    No need to reinvent the wheel: use a module.

    use List::Util qw(max); $largest = max(qw(1 11 2 3)); print $largest;
Re: Get biggest value from array
by larryk (Friar) on Aug 25, 2002 at 09:27 UTC
    Update: Oops, just saw that theorbtwo had already done this one.
    #!perl use strict; use warnings; my @array = 1..99; my $largest = (sort @array)[-1]; print $largest;
       larryk                                          
    perl -le "s,,reverse killer,e,y,rifle,lycra,,print"
    
Re: Get biggest value from array
by Anonymous Monk on Aug 25, 2002 at 05:40 UTC
    Ok, thanks. But how can I do this for only numerical values? Cause the array has also got mixed up, alphabetical records.

    Regards,
    Ralph.
      If your array conntains non numerical values then you just need to add a test for digits in theorbtwo's suggestion:
      foreach (@array) { if (/^\d+$/) { $max=$_ if ($_>$max) } }


      Hotshot
        Hi,

        If @array=(-3, -4, -2); then this code will fail.

        The $max variable should be initialised by shift()ing a value from @array.
        A small change would be required to the regex to allow negative numbers too. So we have
        #!/usr/bin/perl -w use strict; my @array=(-3,-4,-2); my $max=shift @array ; foreach (@array) { if (/^-?\d+$/) { $max=$_ if ($_>$max) } } print $max;
        cheers

        thinker