Checking for Key/Value Existence in Perl Hash

If you try to access a key/value pair from a hash in Perl that doesn't exist, you'll normally get the undefined value, and if you have warnings switched on, then you'll get a warning generated at run time. You can get around this by using the exists function, which returns true if the named key exists, irrespective of what its value might be −


 Live Demo

%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
if( exists($data{'Lisa'} ) ) {
   print "Lisa is $data{'Lisa'} years old\n";
} else {
   print "I don't know age of Lisa\n";

Here we have introduced the IF...ELSE statement, which we will study in a separate chapter. For now, you just assume that if( condition ) part will be executed only when the given condition is true otherwise else part will be executed. So when we execute the above program, it produces the following result because here the given condition exists($data{'Lisa'} returns true −


Lisa is 30 years old