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 sev‐
65 eral 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 argu‐
86 ments doesn't mean that you have to make use of the defaults. The
87 defaults are there for lazy systems programmers writing one-shot
88 programs. If you want your program to be readable, consider sup‐
89 plying 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 proba‐
102 bly 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 read‐
117 ability as well as to allow multilevel loop breaks. See the previ‐
118 ous 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 func‐
122 tions all have return values, so use them. Otherwise use a "fore‐
123 ach()" 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 interro‐
130 gate values determined by the Configure program when Perl was
131 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 under‐
137 scores to separate words in longer identifiers. It is generally
138 easier to read $var_names_like_this than $VarNamesLikeThis, espe‐
139 cially for non-native speakers of English. It's also a simple rule
140 that works consistently with "VAR_NAMES_LIKE_THIS".
141
142 Package names are sometimes an exception to this rule. Perl infor‐
143 mally reserves lowercase module names for "pragma" modules like
144 "integer" and "strict". Other modules should begin with a capital
145 letter and use mixed case, but probably without underscores due to
146 limitations in primitive file systems' representations of module
147 names as files that must fit into a few sparse bytes.
148
149 · You may find it helpful to use letter case to indicate the scope or
150 nature of a variable. For example:
151
152 $ALL_CAPS_HERE constants only (beware clashes with perl vars!)
153 $Some_Caps_Here package-wide global/static
154 $no_caps_here function scope my() or local() variables
155
156 Function and method names seem to work best as all lowercase.
157 E.g., "$obj->as_string()".
158
159 You can use a leading underscore to indicate that a variable or
160 function should not be used outside the package that defined it.
161
162 · If you have a really hairy regular expression, use the "/x" modi‐
163 fier and put in some whitespace to make it look a little less like
164 line noise. Don't use slash as a delimiter when your regexp has
165 slashes or backslashes.
166
167 · Use the new "and" and "or" operators to avoid having to parenthe‐
168 size list operators so much, and to reduce the incidence of punctu‐
169 ation operators like "&&" and "⎪⎪". Call your subroutines as if
170 they were functions or list operators to avoid excessive ampersands
171 and parentheses.
172
173 · Use here documents instead of repeated "print()" statements.
174
175 · Line up corresponding things vertically, especially if it'd be too
176 long to fit on one line anyway.
177
178 $IDX = $ST_MTIME;
179 $IDX = $ST_ATIME if $opt_u;
180 $IDX = $ST_CTIME if $opt_c;
181 $IDX = $ST_SIZE if $opt_s;
182
183 mkdir $tmpdir, 0700 or die "can't mkdir $tmpdir: $!";
184 chdir($tmpdir) or die "can't chdir $tmpdir: $!";
185 mkdir 'tmp', 0777 or die "can't mkdir $tmpdir/tmp: $!";
186
187 · Always check the return codes of system calls. Good error messages
188 should go to "STDERR", include which program caused the problem,
189 what the failed system call and arguments were, and (VERY IMPOR‐
190 TANT) should contain the standard system error message for what
191 went wrong. Here's a simple but sufficient example:
192
193 opendir(D, $dir) or die "can't opendir $dir: $!";
194
195 · Line up your transliterations when it makes sense:
196
197 tr [abc]
198 [xyz];
199
200 · Think about reusability. Why waste brainpower on a one-shot when
201 you might want to do something like it again? Consider generaliz‐
202 ing your code. Consider writing a module or object class. Con‐
203 sider making your code run cleanly with "use strict" and "use warn‐
204 ings" (or -w) in effect. Consider giving away your code. Consider
205 changing your whole world view. Consider... oh, never mind.
206
207 · Try to document your code and use Pod formatting in a consistent
208 way. Here are commonly expected conventions:
209
210 · use "C<>" for function, variable and module names (and more
211 generally anything that can be considered part of code, like
212 filehandles or specific values). Note that function names are
213 considered more readable with parentheses after their name,
214 that is "function()".
215
216 · use "B<>" for commands names like cat or grep.
217
218 · use "F<>" or "C<>" for file names. "F<>" should be the only Pod
219 code for file names, but as most Pod formatters render it as
220 italic, Unix and Windows paths with their slashes and back‐
221 slashes may be less readable, and better rendered with "C<>".
222
223 · Be consistent.
224
225 · Be nice.
226
227
228
229perl v5.8.8 2006-01-07 PERLSTYLE(1)