Finding the Largest Numeric Value in an Array: A Perl Solution

AI Thread Summary
To return the largest numeric value in an array in Perl, a common approach is to iterate through the array while maintaining a variable that stores the maximum value encountered. A sample implementation involves using the `pop` function to initialize the maximum value and then comparing each element in the array to update this variable as needed. An alternative method using `map` filters out non-numeric values and finds the maximum, but it requires additional checks to ensure the array contains numbers. For smaller sets of numbers, a simple conditional comparison can suffice, but for larger arrays, the iterative method is more efficient. Proper syntax is crucial, especially when comparing multiple values, to avoid logical errors.
Monique
Staff Emeritus
Science Advisor
Gold Member
Messages
4,211
Reaction score
68
How do you return the largest numeric value in an array, in Perl?
 
Computer science news on Phys.org
Maybe this helps (I don't have any Perl skills, only Googling skills :smile: ).

sub max
{ my $max = pop(@_);
foreach (@_)
{ $max = $_ if $_ > $max;
}
$max;
}

http://www.codetoad.com/forum/18_23829.asp
 
Last edited by a moderator:
Monique said:
How do you return the largest numeric value in an array, in Perl?
I don't think perl has a maximum function so you have to do something like
Code:
my $tmp='';
map {$tmp=$_ if ($_>$tmp and $_=~/^-?\d*.?\d*$/s and $_=~ /\d/}  @array
die("The array doesn't contain any numbers ") unless ($tmp=~ /\d/);
return $tmp;
 
I always try to advise people by asking how they would do it.

If you had to find the largest number in a list of a million numbers, how would you do it?

You would probably go through it one by one, remembering the largest number you've seen.


So, that's how you should do it on the computer: you have a variable for storing the largest number you've seen, and you iterate through the array, updating this variable whenever you see a bigger number.
 
Well, luckily I only needed to compare three values so I took the easy way out:

Code:
        if ($frame1>$frame2&&$frame3){
            $ORF=$frame1;
        } elsif ($frame2>$frame3){
            $ORF=$frame2;
        } else {
            $ORF=$frame3;
        }
I guess the way you suggest would be best for a large array, thanks :)
 
$frame1>$frame2&&$frame3

I'm not familiar with Perl syntax, but don't you mean something like ($frame1>$frame2)&&($frame1>$frame3)? (In other languages, at least, the two are much different)
 
Hey, thanks! I tested it with some numbers and you're right :blushing:
 
Back
Top