On Jul 13, Connie Chan said:

>I now have an array like this : @list = ('1234', '4567', '789A', 'BCDE',
>'FGHI', .....);
>
>and now, I want to find where is the location of 'BCDE' in list , so I
>write like this :
>
>my @list = ('1234', '4567', '789A', 'BCDE', 'FGHI');
>my $GetLocation = 0;
>my $value = 'BCDE';
>
>for (my $atLoc = 0; $atLoc <= $#list and ! $GetLocation ; $atLoc++)
>{ $GetLocation = $atLoc if ($value eq  $list[$atLoc])  }
>
>ok, so $GetLocation is the result I want...
>but any other smarter method ?

Once you have FOUND the element, you can exit the loop.  Also, your loop
is testing !$GetLocation, which returns true if the element is found at
index 0.  Your code will end up ASSUMING the element is index 0 if it
isn't found in the array at all.  Here's are two solutions:

  my @list = ...;
  my $wanted = 'foo';
  my $pos = -1;  # -1 means not found

  for (my $i = 0; $i < @list; $i++) {
    $pos = $i, last if $list[$i] eq $wanted;
  }

Now you'll have $pos being either -1 (not found) or the index in the
array.  You'd check via

  if ($pos != -1) { ... }  # it was found
  else { ... }             # it wasn't found

Here's the other solution:

  my @list = ...;
  my $wanted = 'foo';
  my $pos = 0;  # 0 means not found

  for (my $i = "0E0"; $i < @list; $i++) {
    $pos = $i, last if $list[$i] eq $wanted;
  }

Now you'll have $pos being either 0 (not found), or the index in the
array, BUT! it will be "0E0" if it was the first element.  This means you
CAN test it like so:

  if ($pos) { ... }  # it was found
  else { ... }       # it wasn't found

because "0E0" is a string that is not false, but is treated as the number
0 when used numerically.

-- 
Jeff "japhy" Pinyan      [EMAIL PROTECTED]      http://www.pobox.com/~japhy/
RPI Acacia brother #734   http://www.perlmonks.org/   http://www.cpan.org/
** Look for "Regular Expressions in Perl" published by Manning, in 2002 **
<stu> what does y/// stand for?  <tenderpuss> why, yansliterate of course.
[  I'm looking for programming work.  If you like my work, let me know.  ]


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to