One another thing forgot to mention in the last post, the way you check for existence of a key in hash(phonebook) is not right way. Because if you take this eg: then will come to know
my %h = (a=>undef);
if ($h{a}){print $h{a};} # this way you check, but it should like,
if (exists $h{a}){print $h{a};#but the value is undefined, so you can check this as well and print some useful message}
katharnakh.
I think your example is a little misleading. If all he did was check for the existance of the hash key and it is undefined (or has a value of undef) he will get a false positive if the key exists but has no value.
#!/usr/bin/perl;
#playplay.pl
use warnings;
use strict;
my %phonebook = (
dog => "7777777",
cat => "8888888",
monster => "99999999",
cow => undef,
);
#print ("Please Enter a name to be search:\t");
$nama = 'cow';
if(exists $phonebook{$nama})
{
print ("The phone number of $nama is $phonebook{$nama}");
}
else
{
print ("The phone number of $nama cannot be found.");
}
But if the code is run as originally coded it will produce the correct output:
#!/usr/bin/perl;
#playplay.pl
use warnings;
use strict;
my %phonebook = (
dog => "7777777",
cat => "8888888",
monster => "99999999",
cow => undef,
);
#print ("Please Enter a name to be search:\t");
$nama = 'cow';
if($phonebook{$nama})
{
print ("The phone number of $nama is $phonebook{$nama}");
}
else
{
print ("The phone number of $nama cannot be found.");
}
Even if "cow" was not a key in the hash it would still work correctly. "exists" should be used to see if a key is in a hash, not to see if there is a value associated with the key. An exception might be a multi-level hash where you don't want the hash key to autovivify if you only check for its value. See the "exists" function manpage for more information.
Or maybe I just misunderstood the point you were making.