4.2. The if/unless Statement

Next up in order of complexity is the if statement. This construct takes a control expression (evaluated for its truth) and a block. It may optionally have an else followed by a block as well. In other words, it looks like this:

if (some_expression) {
    true_statement_1;
    true_statement_2;
    true_statement_3;
} else {
    false_statement_1;
    false_statement_2;
    false_statement_3;
}

(If you're a C or Java hacker, you should note that the curly braces are required. This eliminates the need for a "confusing dangling else" rule.)

During execution, Perl evaluates the control expression. If the expression is true, the first block (the true_statement statements above) is executed. If the expression is false, the second block (the false_statement statements above) is executed instead.

But what constitutes true and false? In Perl, the rules are slightly weird, but they give you the expected results. The control expression is evaluated for a string value in scalar context (if it's already a string, no change, but if it's a number, it is converted to a string[1]). If this string is either the empty string (with a length of zero), or a string consisting of the single character "0" (the digit zero), then the value of the expression is false. Anything else is true automatically. Why such funny rules? Because it makes it easy to branch on an emptyish versus nonempty string, as well as a zero versus nonzero number, without having to create two versions of interpreting true ...

Get Learning Perl, Second 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.