1PERLSTYLE(1)           Perl Programmers Reference Guide           PERLSTYLE(1)
2
3
4

NAME

6       perlstyle - Perl style guide
7

DESCRIPTION

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