You are viewing the version of this documentation from Perl 5.005_04. View the latest version
exists EXPR

Returns TRUE if the specified hash key exists in its hash array, even if the corresponding value is undefined.

print "Exists\n" 	if exists $array{$key};
print "Defined\n" 	if defined $array{$key};
print "True\n"      if $array{$key};

A hash element can be TRUE only if it's defined, and defined if it exists, but the reverse doesn't necessarily hold true.

Note that the EXPR can be arbitrarily complicated as long as the final operation is a hash key lookup:

if (exists $ref->{A}->{B}->{$key}) 	{ }
if (exists $hash{A}{B}{$key}) 	{ }

Although the last element will not spring into existence just because its existence was tested, intervening ones will. Thus $ref->{"A"} and $ref->{"A"}->{"B"} will spring into existence due to the existence test for a $key element. This happens anywhere the arrow operator is used, including even

undef $ref;
if (exists $ref->{"Some key"})	{ }
print $ref; 	    # prints HASH(0x80d3d5c)

This surprising autovivification in what does not at first--or even second--glance appear to be an lvalue context may be fixed in a future release.