In Perl, conditional statements are used to execute a block of code only if a certain condition is met. The most commonly used conditional statement in Perl is the ‘if‘ statement. It takes the following form:
if (condition) {
# code to be executed if the condition is true
}
For example:
$x = 10;
if ($x > 5) {
print "x is greater than 5n";
}
In this example, the ‘if‘ statement checks whether the value of the variable ‘$x‘ is greater than 5. If the condition is true, which it is in this case, the code inside the curly braces is executed and the message "x is greater than 5" is printed to the console.
The ‘else‘ keyword is used to execute a block of code if the condition in the ‘if‘ statement is false. For example:
if ($x > 5) {
print "x is greater than 5n";
} else {
print "x is less than or equal to 5n";
}
In this example, if the condition is true, the first block of code in the ‘if‘ statement is executed. If the condition is false, the code in the ‘else‘ block is executed instead, and the message "x is less than or equal to 5" is printed to the console.
Sometimes we need to check multiple conditions. For that purpose, Perl provides the ‘elsif‘ keyword, which allows us to check for additional conditions after the initial ‘if‘ statement. The syntax looks like this:
if (condition1) {
# code to execute if condition1 is true
} elsif (condition2) {
# code to execute if condition2 is true
} else {
# code to execute if both conditions are false
}
For example:
if ($x > 10) {
print "x is greater than 10n";
} elsif ($x > 5) {
print "x is greater than 5, but less than or equal to 10n";
} else {
print "x is less than or equal to 5n";
}
In this example, if ‘$x‘ is greater than 10, the first block of code is executed. If it’s between 5 and 10, the second block of code is executed. If ‘$x‘ is less than or equal to 5, the third block of code is executed.
Perl also provides the ‘unless‘ keyword, which is like an inverse of the ‘if‘ statement. It executes a block of code only if a condition is false, like this:
unless (condition) {
# code to execute if the condition is false
}
For example:
$x = 3;
unless ($x > 5) {
print "x is less than or equal to 5n";
}
In this example, because the condition ‘$x > 5‘ is false, the code inside the ‘unless‘ block is executed and the message "x is less than or equal to 5" is printed to the console.
These are the basic conditional statements in Perl. They are very powerful and can be combined with loops, functions, and many other language features to create complex logic and decision-making structures in your code.