The if Control Structure
Once you can compare two values, you’ll probably want your
program to make decisions based upon that comparison. Like all similar
languages, Perl has an if control
structure:
if ($name gt 'fred') {
print "'$name' comes after 'fred' in sorted order.\n";
}If you need an alternative choice, the else keyword provides
that as well:
if ($name gt 'fred') {
print "'$name' comes after 'fred' in sorted order.\n";
} else {
print "'$name' does not come after 'fred'.\n";
print "Maybe it's the same string, in fact.\n";
}Those block curly braces are required around the conditional code (unlike C, whether you know C or not). It’s a good idea to indent the contents of the blocks of code as we show here; that makes it easier to see what’s going on. If you’re using a programmers’ text editor (as discussed in Chapter 1), it’ll do most of the work for you.
Boolean Values
You may actually use any scalar value as the conditional of the
if control structure. That’s handy
if you want to store a true or false value into a variable, like
this:
$is_bigger = $name gt 'fred';
if ($is_bigger) { ... }But how does Perl decide whether a given value is true or false? Perl doesn’t have a separate Boolean data type, like some languages have. Instead, it uses a few simple rules:[*]
If the value is a number,
0means false; all other numbers mean true.Otherwise, if the value is a string, the empty string (
'') means false; all other strings mean true.Otherwise (that is, if the value is another kind of ...