469,312 Members | 2,524 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,312 developers. It's quick & easy.

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 9240
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
KevinADC
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

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

3 posts views Thread by Massimiliano Alberti | last post: by
21 posts views Thread by Jaspreet | last post: by
13 posts views Thread by mike | last post: by
21 posts views Thread by Imran | last post: by
17 posts views Thread by rhitz1218 | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by zhoujie | last post: by
reply views Thread by suresh191 | last post: by
reply views Thread by harlem98 | last post: by
reply views Thread by harlem98 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.