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