Programming with Style

You'll certainly have your own preferences in regard to formatting, but there are some general guidelines that will make your programs easier to read, understand, and maintain.

The most important thing is to run your programs under the use warnings pragma. (You can turn off unwanted warnings with no warnings.) You should also always run under use strict or have a good reason not to. The use sigtrap and even the use diagnostics pragmas may also prove of benefit.

Regarding aesthetics of code layout, about the only thing Larry cares strongly about is that the closing brace of a multiline BLOCK should be "outdented" to line up with the keyword that started the construct. Beyond that, he has other preferences that aren't so strong. Examples in this book (should) all follow these coding conventions:

  • Use four-column indents.

  • An opening brace should be put on the same line as its preceding keyword, if possible; otherwise, line them up vertically.

    while ($condition) {        # for short ones, align with keywords
        # do something
    # if the condition wraps, line up the braces with each other
    while ($this_condition and $that_condition
           and $this_other_long_condition) 
        # do something
  • Put space before the opening brace of a multiline BLOCK.

  • A short BLOCK may be put on one line, including braces.

  • Omit the semicolon in a short, one-line BLOCK.

  • Surround most operators with space.

  • Surround a "complex" subscript (inside brackets) with space.

  • Put blank lines between chunks of code that do ...

Get Programming Perl, 3rd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.