By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,852 Members | 2,198 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,852 IT Pros & Developers. It's quick & easy.

find the highest number in a array

P: 72
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
Share this Question
Share on Google+
3 Replies


numberwhun
Expert Mod 2.5K+
P: 3,503
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
Expert 100+
P: 410
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
Expert 2.5K+
P: 4,059
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.