Sunday, October 5, 2008

Start to learn Perl: Differences among exists, defined, and true

my %h = ();
#%h is a hash table
$h{'undef'} = undef;
$h{'defined_but_false'} = 0;
$h{'defined_and_true'} = 'true';

$key = 'undef';
print "Value EXISTS, but may be undefined.\n" if exists  $h{ $key };
print "Value is DEFINED, but may be false.\n" if defined $h{ $key };
print "Value is TRUE at h key $key.\n"     if         $h{ $key };
print "\n";

$key = 'defined_but_false';
print "Value EXISTS, but may be undefined.\n" if exists  $h{ $key };
print "Value is DEFINED, but may be false.\n" if defined $h{ $key };
print "Value is TRUE at h key $key.\n"     if         $h{ $key };
print "\n";

$key = 'defined_and_true';
print "Value EXISTS, but may be undefined.\n" if exists  $h{ $key };
print "Value is DEFINED, but may be false.\n" if defined $h{ $key };
print "Value is TRUE at h key $key.\n"     if         $h{ $key };
print "\n";

____________________________________________________________
Store the above to "test.pl"
and run "perl test.pl"
You will get the following results:

"
Value EXISTS, but may be undefined.

Value EXISTS, but may be undefined.
Value is DEFINED, but may be false.

Value EXISTS, but may be undefined.
Value is DEFINED, but may be false.
Value is TRUE at h key defined_and_true.
"

So if a variable is true, then it is defined, and if a variable is defined, then it exists.
But reverse is not true.
A variable exists but may not have been defined, and a variable is defined but may not be true

No comments: