Let's take a look at a simple unless statement:
for ($count = 1; $count <= 10; $count++) {So this would produce the output:
print "counter: $count\n";
unless ($count == 5) {
print "The counter is NOT equal to 5.\n";
}
}
counter: 1You can see that the code inside the unless block is executed every single time the loop increments except in one case - when $count equals 5. You could write this code the same way using an if statement and a not equal to operator 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
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++) {In fact, the choice between if and unless is really cosmetic. The typical usage is to use if for most everything, but use unless in place of an 'if not' situation like the one above. When you read it out, it simple feels and looks cleaner to say 'do some things unless this is true' instead of 'do some things if this is NOT true. Use unless when it feels right or simplifies the code - whoever has to decipher your programming down the road will thank you.
print "counter: $count\n";
if ($count != 5) {
print "The counter is NOT equal to 5.\n";
}
}
Previous: Conditionals - else, elsif
