Skip to Content
Perl Best Practices
book

Perl Best Practices

by Damian Conway
July 2005
Intermediate to advanced content levelIntermediate to advanced
544 pages
13h 8m
English
O'Reilly Media, Inc.
Content preview from Perl Best Practices

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Modern Perl Best Practices

Modern Perl Best Practices

Damian Conway
Perl in a Nutshell, 2nd Edition

Perl in a Nutshell, 2nd Edition

Nathan Patwardhan, Ellen Siever, Stephen Spainhour
Perl in a Nutshell

Perl in a Nutshell

Nathan Patwardhan, Ellen Siever, Stephen Spainhour

Publisher Resources

ISBN: 0596001738Supplemental ContentErrata