Perl Programming/Conditionals

= Conditionals =

The if statement
The if statement is the primary conditional structure in Perl. The syntax is as follows:

If the boolean expression evaluates to true, the statements between the two braces will be executed. The braces around statements are mandatory, even if there is only one statement (unlike C or Java).

An alternative syntax to the if statement may be used on a single statement. This involves putting the conditional at the end of the statement rather than before, and does not include braces:

The following statements are synonymous:

You should choose whichever one is clearer in a given situation. For example, the following is legal, but unclear:

This hides the last (which is like break, and ends the loop) over at the right. Instead, use a postfix if:

The boolean expression conditional can contain any one of the comparison operators covered in the next section.

Multiple conditions can be checked together using the boolean expression operators:


 * && - logical and, C style; used for most conditionals
 * and - logical and, but with a lower precedence; used for flow control
 * <tt>||</tt> - logical or, C style; used for most conditionals
 * <tt>or</tt> - logical or, but with a lower precedence; used for flow control
 * <tt>!</tt>  - logical not, C style
 * <tt>not</tt> - logical not, but with a lower precedence

Conditional statements can also be extended with the <tt>elsif</tt> and <tt>else</tt> structures:

Note that an <tt>if</tt> statement is followed by any number (including zero) of <tt>elsif</tt> statements, and finally an optional <tt>else</tt> statement. The statements of an <tt>elsif</tt> will be executed, if its boolean expression is true, and no preceding <tt>(els)if</tt> statement's boolean expression is true. The trailing <tt>else</tt> (if present) is executed, if none of the preceding statements' boolean expressions are true.

Shorthand <tt>if ... else</tt> notation
If you want to shorten the conditional into one line, you may use the shortcut syntax:

This code uses the shorthand syntax within a line.