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 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 as some languages have. Instead, it uses a few simple rules:[55]

  • If the value is a number, 0 means false; all other numbers mean true.

  • If the value is a string, the empty string ('') means false; all other strings mean true.

  • If the value is another kind of scalar than a number or a string, convert ...

Get Learning Perl, Fourth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.