Node:The if/unless Structures, Next:, Previous:A Digression---Truth Values, Up:Control Structures



The if/unless Structures

The if and unless structures are the simplest control structures. You are no doubt comfortable with if statements from C, C++, or Java. Perl's if statements work very much the same.

     use strict;
     if (expression) {
         Expression_True_Statement;
         Expression_True_Statement;
         Expression_True_Statement;
     } elsif (another_expression) {
         Expression_Elseif_Statement;
         Expression_Elseif_Statement;
         Expression_Elseif_Statement;
     } else {
         Else_Statement;
         Else_Statement;
         Else_Statement;
     }
     

There are a few things to note here. The elsif and the else statements are both optional when using an if. It should also be noted that after each if (expression) or elsif (expression), a code block is required. These means that the {}'s are mandatory in all cases, even if you have only one statement inside.

The unless statement works just like an if statement. However, you replace if with unless, and the code block is executed only if the expression is false rather than true.

Thus unless (expression) { } is functionally equivalent to if (! expression) { }.