Checking for Key/Value Existence in Perl Hash

PERLServer Side ProgrammingProgramming Scripts

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 −

Example

 Live Demo

#!/usr/bin/perl
%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 −

Output

Lisa is 30 years old
raja
Published on 29-Nov-2019 05:52:55
Advertisements