Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!sdd.hp.com!think.com!mintaka!ogicse!intelhf!agora!markb From: markb@agora.uucp (Mark Biggar) Newsgroups: comp.lang.perl Subject: Re: The best way to search an array ? Keywords: detab Message-ID: <1990Dec3.035541.24184@agora.uucp> Date: 3 Dec 90 03:55:41 GMT References: <443@stephsf.stephsf.com> Organization: Open Communications Forum Lines: 65 In article <443@stephsf.stephsf.com> wengland@stephsf.stephsf.com (Bill England) writes: > > What is the best method for discovering if a string is in > a given set of strings? For example say you want to verify > that the string 'WA' is a valid two char state abreviation? > > I can think of at least four methods ... > > Method Description > > 1 Search a string that contains all two letter state names; > Here you would prefix and suffix the state var and > then search the string. Something like ; > ... > $state = '~AK~AL~AR~AZ~CA~CO~...'; > $search_string = '~'.$prove_state.'~'; > if( /$search_string/ eq $state) { ... } > If you search set is small this may be the bets way, but use index() instead of of an regular expression, like so: if (index($state, "~$prove_state~") > = 0) Besides your if condition is wrong, it should be: if ($state =~ /~$prove_state~/) > 2 Build an associative array %state so that you have; > $state{'AK'}="Alaska"; > $state{'AL'}="Alabama"; > $state{'AR'}="Arkansas"; > $state{'AZ'}="Arizona"; > $state{'CA'}="California"; > ... > Then test for the existance of $state{$prove_state}. > ( Has disadvantage of extra bagage if you don't need the > states full name. ) > if you don't need the full names just set the associated array value to 1. this is a very good way to go if the search set is generated by your program. If you have a very large constant search set using a dbm file for it may be the best way to go. > 3 Build a simple array and then search with a foreach > @state = ('AK','AL','AR','AZ','CA', ...); > foreach $st(@state){ > last if $st eq $prove_state; > } > This is only good if you need the array for other reasons, such as an array of month names that you wish to index by month number. > 4 The same as 3 above but, use a binary search instead of > a linear search. > Same problems as with 3. > Which of the above would be the best to use in perl? > > Is there a better way ??? That pretty much covers it. -- Perl's maternal uncle Mark Biggar Brought to you by Super Global Mega Corp .com