Clear questions and runnable code get the best and fastest answer |
|
PerlMonks |
perlfunc:definedby gods (Initiate) |
on Aug 24, 1999 at 22:42 UTC ( [id://270]=perlfunc: print w/replies, xml ) | Need Help?? |
definedSee the current Perl documentation for defined. Here is our local, out-dated (pre-5.6) version: defined - test whether a value, variable, or function is defined
defined EXPR defined
Returns a Boolean value telling whether
EXPR has a value other than the undefined value undef. If
EXPR is not present,
Many operations return undef to indicate failure, end of file, system error, uninitialized variable, and
other exceptional conditions. This function allows you to distinguish undef from other values.
(A simple Boolean test will not distinguish among
undef, zero, the empty string, and
You may also use defined() to check whether a subroutine exists, by saying 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. Examples:
print if defined $switch{'D'}; print "$val\n" while defined($val = pop(@ary)); die "Can't readlink $sym: $!" unless defined($value = readlink $sym); sub foo { defined &$bar ? &$bar(@_) : die "No bar"; } $debugging = 0 unless defined $debugging;
Note: Many folks tend to overuse defined(), and then are surprised to discover that the number
"ab" =~ /a(.*)b/;
The pattern match succeeds, and Currently, using defined() on an entire array or hash reports whether memory for that aggregate has ever been allocated. So an array you set to the empty list appears undefined initially, and one that once was full and that you then set to the empty list still appears defined. You should instead use a simple test for size:
if (@an_array) { print "has array elements\n" } if (%a_hash) { print "has hash members\n" } Using undef() on these, however, does clear their memory and then report them as not defined anymore, but you shouldn't do that unless you don't plan to use them again, because it saves time when you load them up again to have memory already ready to be filled. The normal way to free up space used by an aggregate is to assign the empty list. This counterintuitive behavior of defined() on aggregates may be changed, fixed, or broken in a future release of Perl. |
|