if Statement
Perl if statement allows you to control the execution of your code based on
conditions. The simplest form of the if statement is as follows:
if (expression);
In this form, you can put the if statement after another statement. Let’s
take a look at the following example:
my $a = 1;
print("Welcome to Perl if tutorial\n") if ($a == 1);
The message is only displayed if the expression $a == 1 evaluates to true.
if (expression) {
statement;
statement;
...
}
|
The curly braces |
Perl provides the if else statement that allows you to execute a code block
if the expression evaluates to true, otherwise, the code block inside the
else branch will execute.
if (expression) {
// if code block;
} else {
// else code block;
}
my $a = 1;
my $b = 2;
if ($a == $b) {
print("a and b are equal\n");
} else {
print("a and b are not equal\n");
}
The code block in the else branch will execute because $a and $b are not equal.
In some cases, you want to test more than one condition:
-
If
$aand$bare equal, then do this. -
If
$ais greater than$bthen do that. -
Otherwise, do something else.
Perl provides the if elsif statement for checking multiple conditions and executing the corresponding code block:
if (expression) {
...
} elsif (expression2) {
...
} elsif (expression3) {
...
} else {
...
}