What is the difference between
if (defined $hash{$key}) { }
and
if (exists $hash{$key}) { }
When do I know which to use?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This is well-documented in the perldoc entries for
definedandexists. Here’s a quick summary:defined $hash{key}tells you whether or not the value for the given key is defined (i.e. notundef). Use it to distinguish between undefined values and values that are false in a boolean context such as0and''.exists $hash{key}tells you whether or not%hashcontains the given key. Use it to distinguish between undefined values and non-existent ones.This is easiest to see with an example. Given this hash:
Here are the results for retrieval, defined-ness, and existence:
In practice, people often write just
if ($hash{key}) {...}because (in many common cases) only true values are meaningful/possible. If false values are valid you must adddefined()to the test.exists()is used much less often. The most common case is probably when using a hash as a set. e.g.Using
undeffor set values has a few advantages:undefvalues share a single allocation (which saves memory).exists()tests are slightly faster (because Perl doesn’t have to retrieve the value, only determine that there is one).It also has the disadvantage that you have to use
exists()to check for set membership, which requires more typing and will do the wrong thing if you forget it.Another place where
existsis useful is to probe locked hashes before attempting to retrieve a value (which would trigger an exception).