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
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
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.