Developer Forums | About Us | Site Map


Useful Lists

Web Host
site hosted by netplex

Online Manuals

Road to better programming: Chapter 3. Loops, clean code, and the Perl idioms
By Teodor Zlatanov - 2004-02-16 Page:  1 2 3 4 5

If, else, elsif, unless, or, how to confuse a cat

Few things are as important to a programmer as understanding and using logical conditions and Boolean algebra in general. It is simply impossible to write a program without logical branching (ask any Computer Science professor if you don't believe me). Perl's logical operators are very similar to C. Consult the perldoc perlop page for specifics on operator syntax.

Several things are different, however. First and foremost for the C/C++/Java refugees, Perl does not normally allow using expressions as the if or else block -- they have to be blocks, not expressions. In other words:

Listing 5. The if or else block

if (something) dothis();                # does NOT work
if (something)                          # usually works great
dothis() if (something);                # my favorite, but see 3.1
                                        # (it should be documented)

The unless() statement is immensely useful. Use it. If you find yourself writing the middle of an if(), and the condition has to be inverted before it's checked, you should almost definitely use unless() instead. The common exceptions: you need an elsif() branch, the logical statement controlling the loop is too complex, or you have a problem with inverted Boolean statements that haunts you.

Much like the Monty Python "How to confuse a cat" sketch, Perl's unless() branching logic can be bewildering at first. The concept of unless() didn't originate with Perl, but most Perl novices haven't used a language with it before. Novices can feel intimidated by the power of unless(). It was not, after all, taught in college Computer Science courses like if() -- therefore, sometimes unless() is seen as at best a vagabond, at worst a meddler. Not true. The unless() statement is a different way of thinking. It changes a fundamental control structure from an awkward inversion to a natural form. Compare the following:

Listing 6. If unless, but learn basic Boolean

if (!eof()) ...
unless(eof()) ...
if (!clear && !ready) ...
unless(clear || ready) ...

The only trick is to invert the logical statement from the inside out -- every individual term is logically negated, and the Boolean operators are inverted too. Basic Boolean algebra is easy to learn (see Resources later in this article), while fixing logic bugs is neither easy nor fun. Invest the time to learn the basics of Boolean algebra, and all your code will benefit.

View Road to better programming: Chapter 3. Loops, clean code, and the Perl idioms Discussion

Page:  1 2 3 4 5 Next Page: The road to cleanliness (no shower cap required)

First published by IBM developerWorks

Copyright 2004-2019 All rights reserved.
Article copyright and all rights retained by the author.