next up previous contents
Next: The while statement Up: Control Structures Previous: if and unless statements   Contents


Compound Statements

When you have a single if or unless statement whose block of statments consists of just a single statement, it is somewhat inconvenient to have to surround that statement with curly braces. For example, if we want to change the value of a variable which is less than 0 to 0, we could use the following perl statements:
     if($x < 0){
         $x = 0;
     }
In a case like this, one way of simplifying things is to include the braces and statement on the same line as the if (remember that perl itself doesn't care one way or the other):
     if($x < 0){$x = 0;}

Perl offers a more attractive alternative known as a compound statement. When you have a single statement following an if or unless statement, you can reverse the order of the statement and the if or unless, and eliminate the curly braces. So our example could be more easily written as

     $x = 0 if $x < 0;
Note that the compound statement is only valid when there is a single statement to be executed. The else and elsif statements are not available when you use a compound statement.


next up previous contents
Next: The while statement Up: Control Structures Previous: if and unless statements   Contents
Phil Spector 2002-10-18