Conditional Statements

Conditional statements evaluate an expression and execute a statement or statement block depending on whether result of the evaluation is true or false.

In its simplest form, a conditional statement begins with the keyword if, followed by an expression in parentheses, and a statement block. The statement block must be enclosed in curly braces.

if (expression)
{
   statement block;
}

If the expression evaluates to true, the statement block is executed; otherwise, it is skipped.

Conditional statements are commonly used for branching, that is, for selectively executing parts of a code based on a number of conditions. Additional tests can be added to an if statement with the keyword elsif. If an if statement is followed by one or more elsif statements. The if / elsif expressions will be evaluated in sequence. If one evaluates to true, the corresponding statement block will be executed, and the program continues AFTER the entire if / elsif construct.

if (expression A)
{
   statement block A;
}
elsif (expression B)
{
   statement block B;
}
elsif (expression C)
{
    statement block C;
}

[ program flow resumes here]

Their is no limit on the number of elsif statements.

Which statement block would be executed in the above example depends entirely on which of the expressions will evaluate to true first. But it is also possible that none will be executed.

Perl includes one more conditional construct that will execute a statement block if any preceding if or elsif tests turn out to be false. This can be achieved with the keyword else.

if (expression A)
{
   statement block A;
}
elsif (expression B)
{
   statement block B;
}
elsif (expression C)
{
    statement block C;
}
else
{
    statement block;
}

[ program flow resumes here]

else does not evaluate an expression since it covers ALL conditions not expressed by the preceding if / elsif statements. Just as if must be the first conditional statement, else must be the last.