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 }
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 different things.
Put a newline between a closing brace and else.
Do not put space between a function name and its opening parenthesis.
Do not put space before a semicolon.
Put space after each comma.
Break long lines after an operator (but before and and or, even when spelled && and ||).
Line up corresponding items vertically.
Omit redundant punctuation as long as clarity doesn't suffer.
Larry has his reasons for each of these things, but he doesn't claim that everyone else's mind works the same as his does (or doesn't).
Here are some other, more substantive style issues to think about:
Just because you can do something a particular way doesn't mean you should do it that way. Perl is designed to give you several ways to do anything, so consider picking the most readable one. For instance:
is better than:open(FOO,$foo) or die "Can't open $foo: $!";
because the second way hides the main point of the statement in a modifier. On the other hand:die "Can't open $foo: $!" unless open(FOO,$foo);
is better than:print "Starting analysis\n" if $verbose;
since the main point isn't whether the user typed -v or not.$verbose and print "Starting analysis\n";
Similarly, just because an operator lets you assume default arguments doesn't mean that you have to make use of the defaults. The defaults are there for lazy programmers writing one-shot programs. If you want your program to be readable, consider supplying the argument.
Along the same lines, just because you can omit parentheses in many places doesn't mean that you ought to:
When in doubt, parenthesize. At the very least it will let some poor schmuck bounce on the % key in vi.return print reverse sort num values %array; return print(reverse(sort num (values(%array))));
Even if you aren't in doubt, consider the mental welfare of the person who has to maintain the code after you, and who will probably put parentheses in the wrong place.
Don't go through silly contortions to exit a loop at the top or the bottom. Perl provides the last operator so you can exit in the middle. You can optionally "outdent" it to make it more visible:
LINE: for (;;) { statements; last LINE if $foo; next LINE if /^#/; statements; }
Don't be afraid to use loop labels--they're there to enhance readability as well as to allow multilevel loop breaks. See the example just given.
Avoid using grep, map, or backticks in a void context, that is, when you just throw away their return values. Those functions all have return values, so use them. Otherwise, use a foreach loop or the system function.
For portability, when using features that may not be implemented on every machine, test the construct in an eval to see whether it fails. If you know the version or patch level of a particular feature, you can test $] ($PERL_VERSION in the English module) to see whether the feature is there. The Config module will also let you interrogate values determined by the Configure program when Perl was installed.
Choose mnemonic identifiers. If you can't remember what mnemonic means, you've got a problem.
Although short identifiers like $gotit are probably okay, use underscores to separate words. It is generally much easier to read $var_names_like_this than $VarNamesLikeThis, especially for non-native speakers of English. Besides, the same rule works for $VAR_NAMES_LIKE_THIS.
Package names are sometimes an exception to this rule. Perl informally reserves lowercase module names for pragmatic modules like integer and strict. Other modules should begin with a capital letter and use mixed case, but should probably omit underscores due to name-length limitations on certain primitive filesystems.
You may find it helpful to use letter case to indicate the scope or nature of a variable. For example:
$ALL_CAPS_HERE # constants only (beware clashes with Perl vars!) $Some_Caps_Here # package-wide global/static $no_caps_here # function scope my() or local() variables
For various vague reasons, function and method names seem to work best as all lowercase. For example, $obj->as_string().
You can use a leading underscore to indicate that a variable or function should not be used outside the package that defined it. (Perl does not enforce this; it's just a form of documentation.)
If you have a really hairy regular expression, use the /x modifier and put in some whitespace to make it look a little less like line noise.
Don't use slash as a delimiter when your regular expression already has too many slashes or backslashes.
Don't use quotes as delimiters when your string contains the same kind of quote. Use the q//, qq//, or qx// pseudofunctions instead.
Use the and and or operators to avoid having to parenthesize list operators so much and to reduce the incidence of punctuational operators like && and ||. Call your subroutines as if they were functions or list operators to avoid excessive ampersands and parentheses.
Use here documents instead of repeated print statements.
Line up corresponding things vertically, especially if they're too long to fit on one line anyway:
$IDX = $ST_MTIME; $IDX = $ST_ATIME if $opt_u; $IDX = $ST_CTIME if $opt_c; $IDX = $ST_SIZE if $opt_s; mkdir $tmpdir, 0700 or die "can't mkdir $tmpdir: $!"; chdir($tmpdir) or die "can't chdir $tmpdir: $!"; mkdir 'tmp', 0777 or die "can't mkdir $tmpdir/tmp: $!";
That which we tell you three times is true:
Always check the return codes of system calls. Always check the return codes of system calls. ALWAYS CHECK THE RETURN CODES OF SYSTEM CALLS!
Error messages should go to STDERR and should say which program caused the problem and what the failed call and its arguments were. Most importantly, for failed syscalls, messages should contain the standard system error message for what went wrong. Here's a simple but sufficient example:
opendir(D, $dir) or die "Can't opendir $dir: $!";
Line up your transliterations when it makes sense:
tr [abc] [xyz];
Think about reusability. Why waste brainpower on a one-shot script when you might want to do something like it again? Consider generalizing your code. Consider writing a module or object class. Consider making your code run cleanly with use strict and -w in effect. Consider giving away your code. Consider changing your whole world view. Consider ... oh, never mind.
Be consistent.
Be nice.
Copyright © 2001 O'Reilly & Associates. All rights reserved.