next up previous contents
Next: Combining Logical Expressions Up: Control Structures Previous: Control Structures   Contents

Basics

Although the basic building block of all perl programs are single statements, without some means of conditionally or repeatedly executing statements, it would be very difficult to write programs to do anything useful. To process every element of an array or list, for example, some sort of loop is necessary; to execute statements only if certain conditions are met requires some way to test a condition and then either execute statements or not, depending on the value of the condition. Perl provides most of the control structures of other languages, as well as some variations which are often more convenient. In the discussion that follows, we'll often refer to a block of statements. In perl, a block of statements is one or more statements, surrounded by curly braces ({ and }). Unlike many other languages, you need to use the curly braces even if the block contains only a single statement. (The compound control structures described in Section 5.4 are often handy when a block contains only a single statement.)

For conditional execution of statements, a perl expression must be evaluated to determine whether or not the statements will be executed. Perl will evaluate the expression as a scalar, so the rule for conversion of lists and arrays (Section 4.2) are in effect. If the value of this expression is true, then the statements will be executed; otherwise they will not. In perl, an expression is considered to be false if its string representation is either an empty string ("" or '') or a zero ("0"). Any other value is considered to be true; there are no special ``logical'' variables in perl. These rules will rarely cause problems, but there are a few things to be aware of. First, remember that there is a difference between an empty string, which will evaluate to false, and a blank (" " or ' '), which will evaluate to true. Similarly the numeric value 0 evaluates to false, as does the numeric value 0.0 (since its string representation is 0), but the string value "0.0" evaluates to true, since its string represention is not a single zero. This said, you'll find that expressions in conditional expressions generally behave just the way you'd expect them to.


next up previous contents
Next: Combining Logical Expressions Up: Control Structures Previous: Control Structures   Contents
Phil Spector 2002-10-18