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

Get Perl Best Practices now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.