my %hash = (
foo => 'bar', # Exists, Defined, Positive length, True.
baz => '', # Defined, False, Zero-length, Exists.
blink => undef, # Exists, Not Defined, Zero-length, False.
# buzz => '' # Does not exist, Not defined (because commented out
+).
);
foreach my $key (qw(foo baz buzz blink)) {
print "$key ", (exists $hash{$key} ? "exists.\n" : "does not exist
+.\n");
print "$key is ", (defined $hash{$key} ? "defined.\n" : "not defin
+ed.\n");
print "$key has a length of ", (defined $hash{$key} ? length($hash
+{$key}) : "zero because it is not defined"), ".\n";
print "$key\'s value is ", (defined $hash{$key} ? $hash{$key} : 'u
+ndefined'), ".\n";
print "$key\'s Boolean value is ", ($hash{$key} ? "true.\n" : "fal
+se.\n");
print "\n";
}
That will produce the following output:
foo exists.
foo is defined.
foo has a length of 3.
foo's value is bar.
foo's Boolean value is true.
baz exists.
baz is defined.
baz has a length of 0.
baz's value is .
baz's Boolean value is false.
buzz does not exist.
buzz is not defined.
buzz has a length of zero because it is not defined.
buzz's value is undefined.
buzz's Boolean value is false.
blink exists.
blink is not defined.
blink has a length of zero because it is not defined.
blink's value is undefined.
blink's Boolean value is false.
So, you can test exists to see if the key exists, you can test defined to see if it has a defined value, you can test length to see if it consists of an empty string, and you can test its Boolean value (even for undefined values) for truth and falsehood. Each test has its own unique perspective. Boolean tests, for example, will return false for both 0 and empty, and undefined.
If you know what you are looking for, Perl provides a way to look for it.
|