1. Home
  2. Computing & Technology
  3. Perl

Conditionals - How to make decisions in Perl
Conditionals - unless

by Kirk Brown
for About.com

The unless conditional is the last one we're looking at in this tutorial. It operates in the opposite manner when compared to the if conditional in that the block is executed every time, unless the statement in the parenthesis evaluates to true (rather than if it does). Remember the trick of thinking in terms of a sentence? With the if conditional we had - if (this is true) { do some things here } - so with unless it looks like this: unless (this is true) { do some things here }.

Let's take a look at a simple unless statement:

for ($count = 1; $count <= 10; $count++) {
print "counter: $count\n";
unless ($count == 5) {
print "The counter is NOT equal to 5.\n";
}
}
So this would produce the output:
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
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.
You 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:
for ($count = 1; $count <= 10; $count++) {
print "counter: $count\n";
if ($count != 5) {
print "The counter is NOT equal to 5.\n";
}
}
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.

Previous: Conditionals - else, elsif

Explore Perl
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Perl
  4. Perl Tutorials
  5. Perl conditionals tutorial - Conditionals in Perl, how to make decisions and branch code in your Perl scripts with conditionals.>

©2009 About.com, a part of The New York Times Company.

All rights reserved.