Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!swrinde!elroy.jpl.nasa.gov!usc!zaphod.mps.ohio-state.edu!uakari.primate.wisc.edu!crdgw1!uunet!stephsf!wengland From: wengland@stephsf.stephsf.com (Bill England) Newsgroups: comp.lang.perl Subject: The best way to search an array ? Keywords: detab Message-ID: <443@stephsf.stephsf.com> Date: 26 Nov 90 01:55:08 GMT Organization: Stephen Software Systems, Inc., Tacoma WA Lines: 50 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) { ... } 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. ) 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; } 4 The same as 3 above but, use a binary search instead of a linear search. Which of the above would be the best to use in perl? Is there a better way ??? +-------- | Bill England | wengland@stephsf.COM | * * H -> He +24Mev * * * ... Oooo, we're having so much fun making itty bitty suns * * *