Michael Alipio 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'! }

If you need to keep unique hash values as well as keys then you should maintain
a second hash which uses the values as keys.

my (%hash, %values);
my ($key, $val) = qw/programmer office/;

if (exists $hash{$key} or exists $values{$val}) {
 die; # Or something more appropriate!
}
else {
  $hash{$key} = $val;
  $values{$val} = undef;
}

If you have an existing hash that you need to add data to you can initialize
your parallel values hash with:

my %values;
@values{values %has} = ();

before adding new key/value pairs as above

What if I got thousands of keys?

This is still the faster way

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?

exists $hash{$key} is fantastically, unimaginably faster than using a for loop,
even if there is only a single entry in the hash.

HTH,

Rob

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


Reply via email to