On Fri, Nov 30, 2001 at 02:07:16PM -0500, Andre` Niel Cameron wrote:

> 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}

>From perldoc -f array:

=head2 How can I tell whether a list or array contains a certain element?

Hearing the word "in" is an I<in>dication that you probably should have
used a hash, not a list or array, to store your data.  Hashes are
designed to answer this question quickly and efficiently.  Arrays aren't.

That being said, there are several ways to approach this.  If you
are going to make this query many times over arbitrary string values,
the fastest way is probably to invert the original array and keep an
associative array lying about whose keys are the first array's values.

    @blues = qw/azure cerulean teal turquoise lapis-lazuli/;
    undef %is_blue;
    for (@blues) { $is_blue{$_} = 1 }

Now you can check whether $is_blue{$some_color}.  It might have been a
good idea to keep the blues all in a hash 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;
    for (@primes) { $is_tiny_prime[$_] = 1; }

Now you check whether $is_tiny_prime[$some_number].

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to