1. Home
  2. Computing & Technology
  3. Perl

Perl exists() function - Quick Tutorial

How to use the exists() function

From About.com

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.
More Perl Quick Tips

Explore Perl

More from About.com

  1. Home
  2. Computing & Technology
  3. Perl
  4. Programming Perl
  5. Perl exists function reference - learn how to use Perl's exists() function in this quick tutorial.

©2008 About.com, a part of The New York Times Company.

All rights reserved.