if else statement in perl
In Perl, the if-else statement allows you to execute one block of code if a certain condition is true, and a different block of code if the condition is false. The basic syntax of the if-else statement is:
if (condition) {
# Code to execute if condition is true
} else {
# Code to execute if condition is false
}
Here, condition is a Boolean expression that is evaluated to either true or false. If the condition is true, the code block enclosed in the first set of curly braces {} is executed. If the condition is false, the code block enclosed in the second set of curly braces {} is executed.
For example, the following code checks whether a given number is positive, negative, or zero using the if-else statement:
my $num = -10;
if ($num > 0) {
print "$num is positive\n";
} elsif ($num < 0) {
print "$num is negative\n";
} else {
print "$num is zero\n";
}
In this code, the first condition $num > 0 checks whether the number is greater than zero, which indicates that the number is positive. If the condition is true, the code block print "$num is positive\n"; is executed, which prints a message indicating that the number is positive. If the first condition is false, the second condition $num < 0 checks whether the number is less than zero, which indicates that the number is negative. If the second condition is true, the code block print "$num is negative\n"; is executed, which prints a message indicating that the number is negative. If both conditions are false, the else block is executed, which prints a message indicating that the number is zero.
