Control Structures:"If..else" and "If..elsif.." in Perl
Here comes another article about Perl. In this one, I’ll teach you how to use one of the most commonly used control structures in programming: the “if..else” statement, as well as its more complex form, “if..elsif”. This control structure is used to manage the flow of data in a program — that is, if a condition is true, it performs one action; if it’s false, it performs another.
The “if..else” structure is divided into two parts
if (condition) {
# block
} else {
# block
}
As you can see, it has a very simple structure. But to help you better understand how it works, I’ll explain step-by-step what happens in an example.
if (condition) {
# if the condition is true executes this code block
} else {
# unless execute this code block
It might seem a bit tricky the first time. So now let’s look at a practical example. Imagine we want to write a script that analyzes a user-provided number and determines whether it’s positive or negative. To do this, we write something like:
#!/usr/bin/perl -w
use strict;
print "Insert a number";
chomp(my $val = <STDIN>);
if($val > 0) {
print "number is positive";
} else {
print "number is negative";
}
In this case, we use if
to check whether the number is positive or negative.
Now you might be wondering: what if we have more than two conditions to check?
Or, in the previous example, how do we handle the case where the number is zero?
Well, to deal with situations like that, we use a variation of the if
statement — the “if..elsif” structure.
Its logic is quite similar to the simple if
, except in this case we check two or more conditions. Below is a basic structure of an if..elsif
statement.
if (condition) {
# if the condition is true executes this code block
}elsif(condition){
# if the condition is true executes this code block
}else{
# unless execute this code block
}
This kind of structure allows for more complex data control. Of course, I’ll also provide a practical example of this statement. Let’s take the previous script and adapt it using this structure to also check whether the entered value is zero.