O'Reilly logo

Perl Best Practices by Damian Conway

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 6. Control Structures

Nothing is more difficult, and therefore more precious, than to be able to decide.

Napoleon I

Control structures are all about choosing: choosing whether to do something, choosing between two or more alternatives, choosing how often to repeat something. As in real life, much programming grief springs either from making the wrong choice or from using the wrong approach when making a choice.

This chapter looks at a range of programming practices that can help to make your code's decision making less error-prone, more efficient, and easier to verify.

The basic principles are simple: make the decision stand out; make the consequences of any decision stand out; base the decision on as few criteria as possible; don't phrase the decision negatively; avoid flag variables and count variables; and make it very easy to detect variations in the flow of control.

If Blocks

Use block if, not postfix if.

One of the most effective ways to make decisions and their consequences stand out is to avoid using the postfix form of if. For example, it's easier to detect the decision and consequences in:

if (defined $measurement) {
    $sum += $measurement;}

than in:

$sum += $measurement if defined $measurement;

Moreover, postfix tests don't scale well as the consequences increase. For example:

$sum += $measurement
and $count++
and next SAMPLE
    if defined $measurement;

and:

do {
    $sum += $measurement;
    $count++;
    next SAMPLE;
} if defined $measurement;

are both much harder to comprehend than:

if (defined ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required