# Largest numeric value array

1. Feb 2, 2005

### Monique

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

2. Feb 2, 2005

### da_willem

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: May 1, 2017
3. Feb 2, 2005

### NateTG

I don't think perl has a maximum function so you have to do something like
Code (Text):

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;

4. Feb 2, 2005

### Hurkyl

Staff Emeritus
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.

5. Feb 2, 2005

### Monique

Staff Emeritus
Well, luckily I only needed to compare three values so I took the easy way out:

Code (Text):

7. Feb 2, 2005

### Monique

Staff Emeritus
Hey, thanks! I tested it with some numbers and you're right