--- Andre` Niel Cameron <[EMAIL PROTECTED]> wrote: > Hi, > > I am having a bit of a problem. Does anyone have any idea how I could have > a variable and see if the value of that variable is also located in an array > and hash? IE: > > $myvar= 6 > > @myarray= ("4", "7", 10", 6") > > if (6 exists in @myarray) ( > dothis} > else{ > dothis} > > andre > Regards, > Andre` C. > Technical Support > ԿԬ
The previous answers about putting setting the array as hash keys work out nicely. One quick way of setting the hash keys is to use a hash slice: my @array = qw/ 1 2 5 hello Ovid /; my %data; @data{ @array } = undef; Now, %data has the keys set to the array values (with all hash values set to undef). I suspect that this is faster than the for loop, but I haven't benchmarked it. One limitation of this technique is that you are pretty much forced to have an exact match. One thing you can do is use grep with a regular expression *in scalar context*. This can allow complex matching of data in the array and quickly tell you how many elements matched! my @array = qw/ 1 2 5 hello Ovid /; my $count = grep /ovid/i, @array; print "$count element(s) matched"; You can read "perldoc -f grep" for details. In the meantime, in the example above, grep takes and expression and an array as arguments. Each element of the array is set to $_, in turn, and this value will be returned by grep if the expression evaluates as true. my $count = grep /ovid/i, @array; # is the same as my $count = grep $_ =~ /ovid/i, @array; # is the same as my @new_array; foreach ( @array ) { push @new_array, $_ if /ovid/i; } my $count = @new_array; Since grep is used in scalar context, in this example, $count is set to the number of items that grep returns. If you use an array on the left, the array will be populated with only those items that grep returns. my @matches = grep /ovid/i, @array; Hope this helps. Cheers, Curtis "Ovid" Poe ===== Senior Programmer Onsite! Technology (http://www.onsitetech.com/) "Ovid" on http://www.perlmonks.org/ __________________________________________________ Do You Yahoo!? Yahoo! GeoCities - quick and easy web site hosting, just $8.95/month. http://geocities.yahoo.com/ps/info1 -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]