This is well documented in perldoc entries for defined and exists . Here is a brief summary:
defined $hash{key} indicates whether a value is defined for a given key (ie, not undef ). Use it to distinguish between undefined values and values that are false in a boolean context, such as 0 and '' .
exists $hash{key} indicates whether or not %hash contains the given key. Use it to distinguish between undefined and nonexistent values.
This is easiest to see with an example. Given this hash:
my %hash = (a => 1, b => 0, c => undef);
Here are the results of a search, definition, and existence:
# key value defined exists a 1 1 1 b 0 1 1 c undef 0 1 d undef 0 0
In practice, people often write only if ($hash{key}) {...} , because (in many common cases) only true values are significant / possible. If the false values are valid, you must add defined() to the test. exists() used much less frequently. The most common case is probably when using a hash as a set. eg.
my %set = map { $_ => undef } 'a' .. 'z';
Using undef for given values has several advantages:
- This more accurately represents intent (only keys make sense, not meanings).
- All
undef values share a single allocation (which saves memory). exists() tests are slightly faster (because Perl does not need to retrieve the value, but only determine what it is).
It also has the disadvantage that you must use exists() to verify membership in a set, which requires more typing and will do the wrong thing if you forget it.
Another place where exists is useful is to examine locked hashes before trying to retrieve a value (which will throw an exception).
Michael Carman Jun 30 2018-11-11T00: 00Z
source share