# Largest numeric value array

Staff Emeritus
Gold Member
How do you return the largest numeric value in an array, in Perl?

Maybe this helps (I don't have any Perl skills, only Googling skills ).

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

Last edited by a moderator:
NateTG
Homework Helper
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;

Hurkyl
Staff Emeritus
Gold Member
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.

Staff Emeritus
Gold Member
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 :) Hurkyl Staff Emeritus Science Advisor Gold Member$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)

Staff Emeritus