The Definition of Truth

Perl has an unusual definition of what’s true and what’s not:

  • An undefined variable is false.

  • An empty string is false as well.

  • The value “0” is false. (Exact match!)

  • Anything else (a non-empty string or a number that’s not zero) is true.

For example, the values undef, “0”, and “” are false. The values “sam”, “1”, and “55” are true.

String “00”

One of the more unusual true values is the string “00”. Take a look at how Perl treats this value:

  1. Is it undefined? If it is, it’s false. Not undefined.

  2. Is it the empty string? If it is, it’s false. Not the empty string.

  3. Is it the same as the string “0”? If it is, it’s false. Because “0” is not equal to “00”, it’s not the same as “0”.

  4. Then it must be true.

This string is defined, not empty, and not the string “0,” so it is true.


What Is Truth Anyway?

For a long time, people have been searching for the meaning of truth. However the legal profession has created a precise definition of this philosophical term.

“Truth is anything the judge says it is. An absolute truth is anything 5 out of 9 Supreme Court Justices agree upon.”


Simple Dividing Program

Listing 2.7 contains a program that divides two numbers. To make sure that nothing goes wrong, a check is provided to make sure that you don’t divide by zero.

One problem with this program is that it doesn’t check the input to make sure that it’s numeric. The technique for doing this is covered later in Chapter 4, “Regular Expressions.”

Listing 2.7. divide.pl
# Divided one number by another 
use strict; 
use warnings; 

print "Enter a number: "; 
my $num1 = <STDIN>; 
chomp($num1); 

print "Enter a second number: "; 
my $num2 = <STDIN>; 
chomp($num2); 

# We should check $num1 and $num2 to make sure that 
# they were numeric.   We'll learn how in a later 
# chapter.   
if ($num2 == 0) {
    print "ERROR: Can't divide by zero
"; 
} else {
    my $result = $num1 / $num2; 
    print "$num1 / $num2 = $result
"; 
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset