next up previous contents index
Next: Input/Output Up: Conditionals Previous: Multiple conditions   Contents   Index

Defined and existence

At times one might want to phrase a condition to test for in terms of a test on just whether or not some variable exists, in some sense. Such boolean (true/false) types of tests are very useful, but there are subtelties involved.

As an example, suppose we have a variable $switch which can take one of two values: 0 or 1. The following

my $switch = 0;
if ($switch) {
   print qq{The switch is on};
}
else {
  print qq{The switch is off};
}
will report that the switch is off, because in the sense of if($variable) , $variable has to be true, which is something other than 0, an empty string, or not undefined via $variable = undef). An analagous test may be used to test if an array or has has any elements:
my @array = ();
if (@array) { 
  print qq{\@array is not empty};
}
else {
  print qq{\@array is empty};
}

In some cases though you may want to see if a certain variable is defined, and not care if it has a value of zero or not. For example, consider

my %person = (name => 'George', 
             test_score => 0);
if ($person{test_score}) {
    print "A test score has been recorded";
}
else {
    print "No test score was recorded";
}
This will print out that no test score was recorded, even though apparently one was (with a value of 0). If you want to test if a variable is defined (which may in principle include a value of 0 or an empty string), you can use the defined function, which will test for the existence of a value other than undefined (set through, for example, $var = undef):
my %person = (name => 'George', 
             test_score => 0);
if (defined $person{test_score}) {
    print "A test score has been recorded";
}
else {
    print "No test score was recorded";
}

In some cases it may be desireable to test for the existence of, for example, a hash or array element, and not care if it is defined or not. For this you can use the exists function, which tests just if some element has ever been initialized, even if it's value is undefined. For example,

my %person = (name => 'George', 
             test_score => undef);
if (exists $person{test_score}) {
    print "A test score exists";
}
else {
    print "No test score exists";
}
will report that a test score exists, even though it's value is undefined.
next up previous contents index
Next: Input/Output Up: Conditionals Previous: Multiple conditions   Contents   Index