1PERLSTYLE(1) Perl Programmers Reference Guide PERLSTYLE(1)
2
3
4
6 perlstyle - Perl style guide
7
9 Each programmer will, of course, have his or her own preferences in
10 regards to formatting, but there are some general guidelines that will
11 make your programs easier to read, understand, and maintain.
12
13 The most important thing is to run your programs under the -w flag at
14 all times. You may turn it off explicitly for particular portions of
15 code via the "no warnings" pragma or the $^W variable if you must. You
16 should also always run under "use strict" or know the reason why not.
17 The "use sigtrap" and even "use diagnostics" pragmas may also prove
18 useful.
19
20 Regarding aesthetics of code lay out, about the only thing Larry cares
21 strongly about is that the closing curly bracket of a multi-line BLOCK
22 should line up with the keyword that started the construct. Beyond
23 that, he has other preferences that aren't so strong:
24
25 · 4-column indent.
26
27 · Opening curly on same line as keyword, if possible, otherwise line
28 up.
29
30 · Space before the opening curly of a multi-line BLOCK.
31
32 · One-line BLOCK may be put on one line, including curlies.
33
34 · No space before the semicolon.
35
36 · Semicolon omitted in "short" one-line BLOCK.
37
38 · Space around most operators.
39
40 · Space around a "complex" subscript (inside brackets).
41
42 · Blank lines between chunks that do different things.
43
44 · Uncuddled elses.
45
46 · No space between function name and its opening parenthesis.
47
48 · Space after each comma.
49
50 · Long lines broken after an operator (except "and" and "or").
51
52 · Space after last parenthesis matching on current line.
53
54 · Line up corresponding items vertically.
55
56 · Omit redundant punctuation as long as clarity doesn't suffer.
57
58 Larry has his reasons for each of these things, but he doesn't claim
59 that everyone else's mind works the same as his does.
60
61 Here are some other more substantive style issues to think about:
62
63 · Just because you CAN do something a particular way doesn't mean
64 that you SHOULD do it that way. Perl is designed to give you
65 several ways to do anything, so consider picking the most readable
66 one. For instance
67
68 open(FOO,$foo) || die "Can't open $foo: $!";
69
70 is better than
71
72 die "Can't open $foo: $!" unless open(FOO,$foo);
73
74 because the second way hides the main point of the statement in a
75 modifier. On the other hand
76
77 print "Starting analysis\n" if $verbose;
78
79 is better than
80
81 $verbose && print "Starting analysis\n";
82
83 because the main point isn't whether the user typed -v or not.
84
85 Similarly, just because an operator lets you assume default
86 arguments doesn't mean that you have to make use of the defaults.
87 The defaults are there for lazy systems programmers writing one-
88 shot programs. If you want your program to be readable, consider
89 supplying the argument.
90
91 Along the same lines, just because you CAN omit parentheses in many
92 places doesn't mean that you ought to:
93
94 return print reverse sort num values %array;
95 return print(reverse(sort num (values(%array))));
96
97 When in doubt, parenthesize. At the very least it will let some
98 poor schmuck bounce on the % key in vi.
99
100 Even if you aren't in doubt, consider the mental welfare of the
101 person who has to maintain the code after you, and who will
102 probably put parentheses in the wrong place.
103
104 · Don't go through silly contortions to exit a loop at the top or the
105 bottom, when Perl provides the "last" operator so you can exit in
106 the middle. Just "outdent" it a little to make it more visible:
107
108 LINE:
109 for (;;) {
110 statements;
111 last LINE if $foo;
112 next LINE if /^#/;
113 statements;
114 }
115
116 · Don't be afraid to use loop labels--they're there to enhance
117 readability as well as to allow multilevel loop breaks. See the
118 previous example.
119
120 · Avoid using "grep()" (or "map()") or `backticks` in a void context,
121 that is, when you just throw away their return values. Those
122 functions all have return values, so use them. Otherwise use a
123 "foreach()" loop or the "system()" function instead.
124
125 · For portability, when using features that may not be implemented on
126 every machine, test the construct in an eval to see if it fails.
127 If you know what version or patchlevel a particular feature was
128 implemented, you can test $] ($PERL_VERSION in "English") to see if
129 it will be there. The "Config" module will also let you
130 interrogate values determined by the Configure program when Perl
131 was installed.
132
133 · Choose mnemonic identifiers. If you can't remember what mnemonic
134 means, you've got a problem.
135
136 · While short identifiers like $gotit are probably ok, use
137 underscores to separate words in longer identifiers. It is
138 generally easier to read $var_names_like_this than
139 $VarNamesLikeThis, especially for non-native speakers of English.
140 It's also a simple rule that works consistently with
141 "VAR_NAMES_LIKE_THIS".
142
143 Package names are sometimes an exception to this rule. Perl
144 informally reserves lowercase module names for "pragma" modules
145 like "integer" and "strict". Other modules should begin with a
146 capital letter and use mixed case, but probably without underscores
147 due to limitations in primitive file systems' representations of
148 module names as files that must fit into a few sparse bytes.
149
150 · You may find it helpful to use letter case to indicate the scope or
151 nature of a variable. For example:
152
153 $ALL_CAPS_HERE constants only (beware clashes with perl vars!)
154 $Some_Caps_Here package-wide global/static
155 $no_caps_here function scope my() or local() variables
156
157 Function and method names seem to work best as all lowercase.
158 E.g., "$obj->as_string()".
159
160 You can use a leading underscore to indicate that a variable or
161 function should not be used outside the package that defined it.
162
163 · If you have a really hairy regular expression, use the "/x"
164 modifier and put in some whitespace to make it look a little less
165 like line noise. Don't use slash as a delimiter when your regexp
166 has slashes or backslashes.
167
168 · Use the new "and" and "or" operators to avoid having to
169 parenthesize list operators so much, and to reduce the incidence of
170 punctuation operators like "&&" and "||". Call your subroutines as
171 if they were functions or list operators to avoid excessive
172 ampersands and parentheses.
173
174 · Use here documents instead of repeated "print()" statements.
175
176 · Line up corresponding things vertically, especially if it'd be too
177 long to fit on one line anyway.
178
179 $IDX = $ST_MTIME;
180 $IDX = $ST_ATIME if $opt_u;
181 $IDX = $ST_CTIME if $opt_c;
182 $IDX = $ST_SIZE if $opt_s;
183
184 mkdir $tmpdir, 0700 or die "can't mkdir $tmpdir: $!";
185 chdir($tmpdir) or die "can't chdir $tmpdir: $!";
186 mkdir 'tmp', 0777 or die "can't mkdir $tmpdir/tmp: $!";
187
188 · Always check the return codes of system calls. Good error messages
189 should go to "STDERR", include which program caused the problem,
190 what the failed system call and arguments were, and (VERY
191 IMPORTANT) should contain the standard system error message for
192 what went wrong. Here's a simple but sufficient example:
193
194 opendir(D, $dir) or die "can't opendir $dir: $!";
195
196 · Line up your transliterations when it makes sense:
197
198 tr [abc]
199 [xyz];
200
201 · Think about reusability. Why waste brainpower on a one-shot when
202 you might want to do something like it again? Consider
203 generalizing your code. Consider writing a module or object class.
204 Consider making your code run cleanly with "use strict" and "use
205 warnings" (or -w) in effect. Consider giving away your code.
206 Consider changing your whole world view. Consider... oh, never
207 mind.
208
209 · Try to document your code and use Pod formatting in a consistent
210 way. Here are commonly expected conventions:
211
212 · use "C<>" for function, variable and module names (and more
213 generally anything that can be considered part of code, like
214 filehandles or specific values). Note that function names are
215 considered more readable with parentheses after their name,
216 that is "function()".
217
218 · use "B<>" for commands names like cat or grep.
219
220 · use "F<>" or "C<>" for file names. "F<>" should be the only Pod
221 code for file names, but as most Pod formatters render it as
222 italic, Unix and Windows paths with their slashes and
223 backslashes may be less readable, and better rendered with
224 "C<>".
225
226 · Be consistent.
227
228 · Be nice.
229
230
231
232perl v5.12.4 2011-06-01 PERLSTYLE(1)