Perl If-elsif-else, unless
Statement Blocks
A statement block is simply a sequence of statements enclose in curly braces:
{
first_statement;
second_statement;
last_statement
}
Conditional Structures (If/elsif/else)
The basic construction to execute blocks of statements is the if statement. The if statement permits execution of the associated statement block if the test expression evaluates as true. It is important to note that unlike many compiled languages, it is
necessary to enclose the statement block in curly braces, even if only one statement is to be executed.
The general form of an if/then/else type of control statement is as follows:
if (expression_one) {
true_one_statement;
} elsif (expression_two) {
true_two_statement;
} else {
all_false_statement;
}
For convenience, Perl also offers a construct to test if an expression is false:
unless (expression) {
false_statement;
} else {
true_statement;
}
Note that the order of the conditional can be inverted as well:
statement if (expression);
statement unless (expression);
The “ternary” operator is another nifty one to keep in your bag of tricks:
$var = (expression) ? true_value : false_value;
It is equivalent to:
if (expression) {
$var = true_value;
} else {
$var = false_value;
}