Book HomeLearning Perl, 3rd EditionSearch this book

2.7. 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";
}

Unlike in C, those block curly braces are required around the conditional code. 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, "Introduction"), it'll do most of the work for you.

2.7.1. 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:

  1. The special value undef is false. (We'll see this a little later in this section.)

  2. Zero is false; all other numbers are true.

  3. The empty string ('') is false; all other strings are normally true.

  4. The one exception: since numbers and strings are equivalent, the string form of zero, '0', has the same value as its numeric form: false.

So, if your scalar value is undef, 0, '', or '0', it's false. All other scalars are true -- including all of the types of scalars that we haven't told you about yet.

If you need to get the opposite of any Boolean value, use the unary not operator, !. If what follows it is a true value, it returns false; if what follows is false, it returns true:

if (! $is_bigger) {
  # Do something when $is_bigger is not true
}


Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.