2.4.3 The defined and undef Functions: Uninitialized Scalars

Before we proceed any further, we look at the function that helps us determine if a scalar variable has been assigned a value either by assignment statement or by other means such as Perl itself during some computation it is asked to do. The function is defined. As we know, scalar variables in Perl can be of three different subtypes: numbers, strings and references. A scalar variable that has not been initialized has an undefined value. This undefined value translates to zero when used in a numeric context and to a string of length zero when used in a string context.
We can test to see if a scalar has a value using defined. In the program below, we have declared two scalar variables using my. $aScalar is uninitialized whereas $bScalar has been initialized to the empty string. The two if statements test to see if the scalar has been defined, and print appropriate diagnostics.
Program 2.15

#!/usr/bin/perl

use strict;
my ($aScalar, $bScalar);
$bScalar = "";

if (defined ($aScalar)){
print "\$aScalar is defined with an empty string as its value\n";
}
else{
print "\$aScalar has no defined value\n";
}

if (defined ($bScalar)){
print "\$bScalar is defined with an empty string as its value\n";
}
else{
print "\$bScalar has no defined value\n";
}

In this case, the program prints the following.

$aScalar has no defined value
$bScalar is defined with an empty string as its value

Some operations return the undefined value under exceptional conditions such as end of file, system error, when assigning an uninitialized variable and such, and it may be important in some situations to test whether a scalar has an initialized value. In particular, defined allows us to distinguish between two cases in the case of strings: a string variable that has undefined null value, and a string variable that has defined null value. This is what we tested in the simple script given above.
An existing value can be undefined using the built-in function undef. undef optionally takes a scalar variable (starting with $), a list variable (starting with @), or a hash variable (starting with %), and makes its value undefined. It returns the undefined value. undef is a unary operator.