Test whether a value is defined.
The defined function returns true if the expression has a value other than undef. It is the proper way to distinguish between an undefined value and a defined but false value (like 0 or the empty string).
This is important because in Perl, undef, 0, the empty string, and the string '0' are all false in boolean context. defined allows you to distinguish 'has no value' (undef) from 'has a false value'.
defined can be used on scalars, array elements, hash values, and function return values. It is commonly used when checking whether a hash key exists and has been assigned a value.
| Name | Description | Optional |
|---|---|---|
EXPR |
The expression to test for definedness. | No |
my $x = 0;
print "defined" if defined $x; # prints 'defined'
my $y;
print "defined" if defined $y; # prints nothing
if (defined $hash{$key}) {
print "Key has a value\n";
}