471,830 Members | 1,661 Online

# find the highest number in a array

i wonder am i make a mistake or not...
Expand|Select|Wrap|Line Numbers
1. use Data::Dumper;
2.
3. my @array= qw(1 2 3 4 5 6 8 9 2 5);
4.
5. my \$highest=@array[0];
6.
7. foreach my \$number (@array) {
8.     if (@array[\$number] > \$highest) {
9.     \$highest = @array[\$number];
10.     }
11. }
12. print Dumper \$highest;
i get the output as \$VAR1 = 8;

suppose the answer should be 9 right?
Jul 23 '08 #1
3 9996
numberwhun
3,503 Expert Mod 2GB
If you are looking for the last element in the array, you can get that with the special variable:

Expand|Select|Wrap|Line Numbers
1. \$#arrayname
2.
On the other hand, take that number and add one and you have the number of elements in the array (not starting at zero).

Regards,

Jeff
Jul 23 '08 #2
nithinpes
410 Expert 256MB
The problem lies in this section of your script:
Expand|Select|Wrap|Line Numbers
1. foreach my \$number (@array) {
2.     if (@array[\$number] > \$highest) {
3.
foreach loop will fetch each element of the array, not each index. So, the comparison section should be:
Expand|Select|Wrap|Line Numbers
1. foreach my \$number (@array) {
2.     if (\$number > \$highest) {
3.     \$highest = \$number;
4.     }
5. }
6.
Jul 23 '08 #3
4,059 Expert 2GB
use sort function, which will be much faster anyway:

Expand|Select|Wrap|Line Numbers
1. my @array= qw(1 2 3 4 5 6 8 9 2 5);
2. print ((sort {\$b <=> \$a} @array)[0]);
Jul 23 '08 #4