Well it depends on what you mean by "too long", you could always just
try it and see if it suites your needs.  However if you can change the
code that builds this hash, you could have it put the values into a
hash as keys allowing for fast lookups later.  Its kind of hard for me
to make helpful suggestions without knowing anything more about the
code :)

On 1/18/07, Michael Alipio <[EMAIL PROTECTED]> wrote:



----- Original Message ----
From: Jason Roth <[EMAIL PROTECTED]>
To: Michael Alipio <[EMAIL PROTECTED]>
Cc: begginers perl.org <beginners@perl.org>
Sent: Friday, January 19, 2007 9:53:49 AM
Subject: Re: Searching hash if a given value exists

Hi Michael,

> To answer your questions, If you want to know if there is already a
> key with a certain value, you have to look through the entire hash.
> However if you want to see if a given key exists, just do "if (exists
> $hash{$key})".  This will take constant time regardless of the number
> of elements in your hash.

I see... so, I really have to do a

for (keys %hash){
    if ($hash{$_} eq 'somevalue'){
       #do something
    }
}

If I have hundreds of thousands keys and I want to know which contains the
same values, will I end up waiting too long?




> Hope this helps.

-Jason

On 1/18/07, Michael Alipio <[EMAIL PROTECTED]> wrote:
> Hi,
>
> Suppose I have a hash:
>
> my %hash = (dog => 'house', pig => 'barn', bird=> 'cage');
>
> Now I want to know if there is already a key with a 'house' value as I do
not want to create another key with the same value.
> Is there any other faster way to do it than doing a
>
> for (keys %hash){
> if ($hash{$_} eq 'house'){
>   #found 'house'!
> }
>
>
> What if I got thousands of keys?
>
> Lastly, how fast is the "if (exists $hash{$key})"? Is it faster than doing
a 'for keys' loop, and testing if a given $_ key will appear?
>
>
> Thanks.
>
>
>
>
>
____________________________________________________________________________________
> Never miss an email again!
> Yahoo! Toolbar alerts you the instant new Mail arrives.
> http://tools.search.yahoo.com/toolbar/features/mail/
>


 ________________________________
It's here! Your new message!
Get new email alerts with the free Yahoo! Toolbar.

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to