Perl exists() Function - Quick Tutorial

Portait of young hacker with computer screen reflecting in the man's glasses.
Erik Tham / Getty Images
 exists HASH 

Perl's exists() function is used to check whether an element in an array or hash exists. It can also be used to check for the existence of subroutines. exists will return true as long as the element has been initialized, and even if the element is undefined.

 %sampleHash = ('name' => 'Bob', 'phone' => '111-111-1111');
 print %sampleHash;
 print "\n";
 print "Found phone\n" if exists $sampleHash{'phone'};
 if (exists $sampleHash{'address'}) {
 print "Found address\n";
 }
 else {
 print "No address\n";
 }
 

In the above example, we look at a hash of our contact Bob and his phone number. First, we check for the existence of the phone element, which is obviously returning true. Next, we check for an element that does not exist, address, and you'll see this one returns false.
Let's look at the same routine, but with a blank address key:

 %sampleHash = ('name' => 'Bob', 'phone' => '111-111-1111', 'address' => '');
 print %sampleHash;
 print "\n";
 print "Found phone\n" if exists $sampleHash{'phone'};
 if (exists $sampleHash{'address'}) {
 print "Found address\n";
 }
 else {
 print "No address\n";
 }
 

You'll see that this one returns true on the address, even though there is no actual value. Be careful relying on the logic of exists, and remember the distinction between exists and has value.