Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Position of string within array? 3

Status
Not open for further replies.

domster

Programmer
Oct 23, 2003
30
0
0
GB
Hi, I can't find a function that will return the position of a string within an array. For example, if the array is:

[aardvark, abacus, abandon, abate, abattoir...]

I want to search it for 'abate' and return position 3. What I want to do is search an alphabetically-sorted list and see which words are next in the list to the search word.

I can't believe there isn't an obvious way of doing this, though maybe my brain just isn't working today. Thanks for your help.

Dom
 
The following short program should do what you want :)

Code:
#!c:/Perl/bin/Perl.exe
print "Content-type: text/html\n\n";

@list=("Monday","Tuesday","Wednesday","Thursday","Friday");
$look_for="Wednesday";

for ($i=0; $i<$#list; $i++) {
    if ($list[$i] eq $look_for) { last; }
}

print "The word $look_for is item number $i in the list";

It's a bit messy but works.
 
Thanks - I thought of that, but the list is going to be very long - it's the contents of a dictionary, basically. This seems very inefficient to me, surely there's a better way?
 
Another way:
Code:
#!/usr/bin/perl -w
@dict = qw[aardvark abacus abandon abate abattoir];
@hash{@dict} = (1..scalar(@dict));
$lookfor = "abattoir";
print "$lookfor is in position $hash{$lookfor}\n";
Cheers, Neil
 
thanks toolkit, I was wondering the same thing. One thing though, shouldn't it be "0..scalar(@dict)" instead of 1 since array element numbering starts at 0?
 
If you want your position to be zero based, instead of 1-based, then I think (I'm at home, so I can't test these) the code should be:
Code:
@hash{@dict} = (0..$#dict);
Cheers, Neil
 
toolkit, your original code works perfectly just replacing the 1 with a 0.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top