Brainteaser (help!)

Robbie Bow robbie at robbiebow.co.uk
Wed Mar 14 11:55:27 PDT 2007


> I was wondering if anyone could think of a solution to a problem I have. I
> have a script which contains an array which looks like:
> 
>    @arrayG = qw (1.048 0.657 0.437 2.363 1.964 0.787 1.078 0.686);
> 
> I need to know the array position of the largest number, ie 2.363 is
> largest, but I need to return $arrayG[3] - the '3' is what I need.

Here's my easy to read way:

 use strict;

 my @arrayG = qw (1.048 0.657 0.437 2.363 1.964 0.787 1.078 0.686);
 my $index  = undef;
 my $num    = undef;

 for (my $i=0; $i<scalar(@arrayG); $i++) {
     if ($arrayG[$i] > $num) {
         $num   = $arrayG[$i];
         $index = $i;
     }
 }

But I never have found an easier way to iterate through a list and know
at what iteration I am at.






More information about the MiltonKeynes-pm mailing list