In this second part to a nine-part series on Perl control structures, we'll delve more deeply into operators and take a look at how to compare numbers. It is excerpted from chapter three of the book Beginning Perl, Second Edition, written by James Lee (Apress; ISBN: 159059391X).
Operators Revisited
The ifstatement, and all the other control structures we’re going to visit in this chapter, test to see if a condition is true or false. They do this using the Boolean logic mentioned in Chapter 2, together with Perl’s ideas of true and false. To remind you of these:
An empty string,"", is false.
The number 0 and the string"0"are both false.
An empty list,(), is false.
The undefined value is false.
Everything else is true.
However, you need to be careful for a few traps here. A string containing invisible characters, like spaces or newlines, is true. A string that isn’t"0"is true, even if its numerical value is 0, so"0.0"for instance, is true.
Larry Wall has said that programming Perl is an empirical science—you learn things about it by trying them out. Is(())a true value? You can look it up in books and the online documentation, or you can spend a few seconds writing a program like this:
#!/usr/bin/perl -w # emptylist.pl
use strict;
if ( (()) ) { print "Yes, it is.\n"; }
This way you get the answer straight away, with the minimum of fuss. (If you’re interested, it isn’t a true value.) We’ve also seen that conditional operators can test things out, returning1if the test was successful and empty string if it was not. Let’s see more of the things we can test.