Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!swrinde!cs.utexas.edu!sun-barr!newstop!central!convex!usenet From: tchrist@convex.COM (Tom Christiansen) Newsgroups: comp.lang.perl Subject: Re: does perl have an "in" operator? Message-ID: <1991May16.014446.10539@convex.com> Date: 16 May 91 01:44:46 GMT References: Sender: usenet@convex.com (news access account) Reply-To: tchrist@convex.COM (Tom Christiansen) Distribution: comp Organization: CONVEX Software Development, Richardson, TX Lines: 47 Nntp-Posting-Host: pixel.convex.com From the keyboard of rusty@groan.Berkeley.EDU (Rusty Wright): :I've used a language where with arrays there's an "in" operator that :checks to see if an element is in an arry. For example, if you do : : @array = ( 1, 2, 3 ); : : if ( 1 in @array ) { print "true\n"; } : :it would print true. Does perl have anything like this? Not as such. Here's question #26 from the FAQ: 26) How can I test whether an array contains a certain element? There are several ways to approach this. If you are going to make this query many times and the values are arbitrary strings, the fastest way is probably to invert the original array and keep an associative array around whose keys are the first array's values. @blues = ('turquoise', 'teal', 'lapis lazuli'); undef %is_blue; grep ($is_blue{$_}++, @blues); Now you can check whether $is_blue{$some_color}. It might have been a good idea to keep the blues all in an assoc array in the first place. If the values are all small integers, you could use a simple indexed array. This kind of an array will take up less space: @primes = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31); undef @is_tiny_prime; grep($is_tiny_prime[$_]++, @primes); Now you check whether $is_tiny_prime[$some_number]. If the values in question are integers, but instead of strings, you can save quite a lot of space by using bit strings instead: @articles = ( 1..10, 150..2000, 2017 ); undef $read; grep (vec($read,$_,1) = 1, @articles); Now check whether vec($read,$n,1) is true for some $n. -- Tom Christiansen tchrist@convex.com convex!tchrist "So much mail, so little time."