Kay Bieri <[EMAIL PROTECTED]> writes:

> > Right! I have the same idea as you, and I have 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])  }
> >
> > And I finally got the same ans. =)
> > Deal with it by a hash is the only choice....
> >
> 
> Your script does have some problems. For instance, if the string you're
> looking for is in the first (index = 0) position and also in a later
> position, the for loop will only find the latter. Also if $GetLocation
> stays 0, you don't know whether the string is not present in the array at
> all or whether it is just in the beginning position.

Try this instead:

#!/usr/bin/perl -wl

my @list = qw/BCDE 1234 4567 789A BCDE FGHI/;

my $value = 'BCDE';

my @locations = grep { $list[$_] eq $value } (0 .. $#list);

if (@locations) {
  print "String '$value' found at index(es): " . join(", ", @locations);
}
else {
  print "String '$value' not found.";
}


display:
String 'BCDE' found at: 0, 4


If you find yourself using 'for', it's often best to stop and think
for a bit about a more 'perlish' way to do the same thing with map,
grep, or foreach.  Look to `perldoc -f grep` or the camel book for
more interesting examples of grep usage.

-RN


-- 

Robin Norwood
Red Hat, Inc.

"The Sage does nothing, yet nothing remains undone."
-Lao Tzu, Te Tao Ching

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

Reply via email to