Robert's Perl Tutorial

http://www.sthomas.net/roberts-perl-tutorial.htm


The Truth According to Perl

There are many Perl functions which test for Truth. Some are if, while, unless . So it is important you know what truth is, as defined by Perl, not your tax forms. There are three main rules:

  1. Any string is true except for "" and "0".
  2. Any number is true except for 0. This includes negative numbers.
  3. Any undefined variable is false. A undefined variable is one which doesn't have a value, ie has not been assigned to.

Some example code to illustrate the point:

&isit;                   # $test1 is at this moment undefined

$test1="hello";         # a string, not equal to "" or "0"
&isit;

$test1=0.0;             # $test1 is now a number, effectively 0
&isit;

$test1="0.0";           # $test1 is a string, but NOT effectively 0 !
&isit;

sub isit {
        if ($test1) {                           # tests $test1 for truth or not
                print "$test1 is true\n";
        } else {                                # else statement if it is not true
                print "$test1 is false\n";
        }
}

The first test fails because $test1 is undefined. This means it has not been created by 
assigning a value to it. So according to Rule 3 it is false. The last two tests are
interesting. Of course, 0.0 is the same as 0 in a numeric context. But it is not the
same as 0 in a string context, so in that case it is true.    

So here we are testing single variables. What's more useful is testing the result of an expression. For example, this is an expression; $x * 2 and so is this; $var1 + $var2 . It is the end result of these expressions that is evaluated for truth.

An example demonstrates the point:

$x=5;
$y=5;

if ($x - $y) {
        print '$x - $y is ',$x-$y," which is true\n";
} else {
        print '$x - $y is ',$x-$y," which is false\n";
}
   

The test fails because 5-5 of course is 0, which is false. The print statement might look a little strange. Remember that print is a list operator? So we hand it a list. First item, a single-quoted string. It is single quoted because it we do not want to perform variable interpolation on it. Next item is an expression which is evaluated, and the result printed. Finally, a double-quoted string is used because we want to print a newline, and without the doublequotes the \n won't be interpolated.

What is probably more useful than testing a specific variable for truth is equality testing. For example, has your lucky number been drawn?

$lucky=15;
$drawnum=15;

if ($lucky == $drawnum) {
        print "Congratulations!\n";
} else {
        print "Guess who hasn't won!\n";
}
   

The important point about the above code is the equality operator, == .