- defined EXPR
Returns a Boolean value telling whether EXPR has a value other than the undefined value
undef. If EXPR is not present,
$_will be checked.
Many operations return
undefto indicate failure, end of file, system error, uninitialized variable, and other exceptional conditions. This function allows you to distinguish
undeffrom other values. (A simple Boolean test will not distinguish among
undef, zero, the empty string, and
"0", which are all equally false.) Note that since
undefis a valid scalar, its presence doesn't necessarily indicate an exceptional condition:
undefwhen its argument is an empty array, or when the element to return happens to be
You may also use
defined(&func)to check whether subroutine
&funchas ever been defined. The return value is unaffected by any forward declarations of
&func. Note that a subroutine which is not defined may still be callable: its package may have an
AUTOLOADmethod that makes it spring into existence the first time that it is called -- see perlsub.
definedon aggregates (hashes and arrays) is deprecated. It used to report whether memory for that aggregate has ever been allocated. This behavior may disappear in future versions of Perl. You should instead use a simple test for size:
When used on a hash element, it tells you whether the value is defined, not whether the key exists in the hash. Use exists for the latter purpose.
Note: Many folks tend to overuse
defined, and then are surprised to discover that the number
""(the zero-length string) are, in fact, defined values. For example, if you say
- "ab" =~ /a(.*)b/;
The pattern match succeeds, and
$1is defined, despite the fact that it matched "nothing". But it didn't really match nothing--rather, it matched something that happened to be zero characters long. This is all very above-board and honest. When a function returns an undefined value, it's an admission that it couldn't give you an honest answer. So you should use
definedonly when you're questioning the integrity of what you're trying to do. At other times, a simple comparison to
""is what you want.