On Thu, 26 Sep 2002, Toby Stuart wrote: > $a = 1; > @b = (1,2,3,4); > $i = grep(/$a/,@b); > print "in array" if $i > 0;
This is both an incorrect and ineffecient solution Incorrect because you are checking for the pattern 1 in all the elements of @b. If @b were to be (2, 3, 11, 12) your soln will still say "in array". The check should be $a == $_ Ineffecient because you are using grep for this purpose. If @b were to be (1, 2, 3, 4) just checking the first element should return a true, but with grep you will check all the elements no matter what. These are my comments to the OP, for an "is it present" kind of operation a hash is a better option. If you insist on an array, loop through the array and last (perldoc -f last) out of the loop when the check succeeds. If the array is sorted do a binary search on it. If you don't mind hashes you can do this my %num_hash; @num_hash{@b} = (); # This is a hash slice if (exists($num_hash{$a})) { # perldoc -f exist print "in array\n"; } You can use this if there will be infrequent "is it present" operations. If not do away with the array and use a hash with the array elements as the hash keys. Also please don't declare scalars as $a, perldoc -f sort for more details Read through perldoc -q 'How can I tell whether a certain element is con-tained in a list or array?' > > > > > -----Original Message----- > > From: Alex Cheung Tin Ka [mailto:[EMAIL PROTECTED]] > > Sent: Thursday, September 26, 2002 5:00 PM > > To: [EMAIL PROTECTED] > > Subject: how to check variable in list > > > > > > Dear All, > > I would like to know how to check whether a variable > > exists in an array > > here is my code > > > > $a = 1; > > @b = (1,2,3,4); > > > > Regards. > > Alex > > > > -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]