Since the if conditional tests for true or false, what happens if you want to run a block of code when your statement doesn't evaluate? That's when the else and elsif conditionals come into play. First, let's look at the plain old else statement. It sometimes helps to think of these conditionals in the form of a sentence. Something like - if (this is true) { do some things here } else { do these other things }.
You can see this way that the else statement chains to the if and executes an alternate block of code should the if statement fail. It's a bit like saying 'otherwise'. Let's take a look at an else in action:
for ($count = 1; $count <= 10; $count++) {This is exactly like our if statement example, and in fact uses the same test (whether or not $count is equal to 5). This time, though, we've added a block of code after the if block using else. As the program loops, the else block will execute every single time the if statement is false - in this case, every time that $count is NOT equal to 5. That's the key thing to remember when using the else statement - it will execute every single time that the if fails. Here's what the output looks like:
print "counter: $count\n";
if ($count == 5) {
print "The counter is currently equal to 5.\n";
} else {
print "The counter is NOT equal to 5.\n";
}
}
counter: 1Let's say that you want to execute another bit of code, but only if $count is a certain different value. Using elsif you can chain more if statements on to your conditionals, providing alternate tests and blocks that run if they evaluate correctly. It's basically the same as an if statement, but would come after the initial if like so:
The counter is NOT equal to 5.
counter: 2
The counter is NOT equal to 5.
counter: 3
The counter is NOT equal to 5.
counter: 4
The counter is NOT equal to 5.
counter: 5
The counter is currently equal to 5.
counter: 6
The counter is NOT equal to 5.
counter: 7
The counter is NOT equal to 5.
counter: 8
The counter is NOT equal to 5.
counter: 9
The counter is NOT equal to 5.
counter: 10
The counter is NOT equal to 5.
for ($count = 1; $count <= 10; $count++) {And as you would expect, the output looks like this:
print "counter: $count\n";
if ($count == 5) {
print "The counter is currently equal to 5.\n";
} elsif ($count == 8) {
print "The counter is currently equal to 8.\n";
} else {
print "The counter is NOT equal to 5.\n";
}
}
counter: 1
The counter is NOT equal to 5.
counter: 2
The counter is NOT equal to 5.
counter: 3
The counter is NOT equal to 5.
counter: 4
The counter is NOT equal to 5.
counter: 5
The counter is currently equal to 5.
counter: 6
The counter is NOT equal to 5.
counter: 7
The counter is NOT equal to 5.
counter: 8
The counter is currently equal to 8.
counter: 9
The counter is NOT equal to 5.
counter: 10
The counter is NOT equal to 5.
Next: Conditionals - unless
