Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

PerlBestPractices

ReferenceGuide
CodeLayout
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. Brace and parenthesize in K&R style. Separate your control keywords from the following opening bracket. Dont separate subroutine or variable names from the following opening bracket. Dont use unnecessary parentheses for builtins and honorary builtins. Separate complex keys or indices from their surrounding brackets. Use whitespace to help binary operators stand out from their operands. Place a semicolon after every statement. Place a comma after every value in a multiline list. Use 78-column lines. Use four-column indentation levels. Indent with spaces, not tabs. Never place two statements on the same line. Code in paragraphs. Dont cuddle an else. Align corresponding items vertically. Break long expressions before an operator. Factor out long expressions in the middle of statements. Always break a long expression at the operator of the lowest possible precedence. Break long assignments before the assignment operator. Format cascaded ternary operators in columns. Parenthesize long lists. Enforce your chosen layout style mechanically.

39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50.

Use underscores to improve the readability of long numbers. Lay out multiline strings over multiple lines. Use a heredoc when a multiline string exceeds two lines. Use a theredoc when a heredoc would compromise your indentation. Make every heredoc terminator a single uppercase identifier with a standard prefix. When introducing a heredoc, quote the terminator. Dont use barewords. Reserve => for pairs. Dont use commas to sequence statements. Dont mix high- and low-precedence booleans. Parenthesize every raw list. Use table-lookup to test for membership in lists of strings; use any() for membership of lists of anything else.

Documentation
85. 86. 87. 88. 89. 90. 91. 92. 93. 94. 95. 96. 97. 98. Distinguish user documentation from technical documentation. Create standard POD templates for modules and applications. Extend and customize your standard POD templates. Put user documentation in source files. Keep all user documentation in a single place within your source file. Place POD as close as possible to the end of the file. Subdivide your technical documentation appropriately. Use block templates for major comments. Use full-line comments to explain the algorithm. Use end-of-line comments to point out subtleties and oddities. Comment anything that has puzzled or tricked you. Consider whether its better to rewrite than to comment. Use invisible POD sections for longer technical discussions. Check the spelling, syntax, and sanity of your documentation.

Variables
51. 52. 53. 54. 55. 56. 57. 58. 59. 60. 61. 62. Avoid using non-lexical variables. Dont use package variables in your own development. If youre forced to modify a package variable, localize it. Initialize any variable you localize. use English for the less familiar punctuation variables. If youre forced to modify a punctuation variable, localize it. Dont use the regex match variables. Beware of any modification via $_. Use negative indices when counting from the end of an array. Take advantage of hash and array slicing. Use a tabular layout for slices. Factor large key or index lists out of their slices.

BuiltinFunctions
99. 100. 101. 102. 103. 104. 105. 106. 107. 108. 109. 110. 111. 112. Dont recompute sort keys inside a sort. Use reverse to reverse a list. Use scalar reverse to reverse a scalar. Use unpack to extract fixed-width fields. Use split to extract simple variable-width fields. Use Text::CSV_XS to extract complex variable-width fields. Avoid string eval. Consider building your sorting routines with Sort::Maker. Use 4-arg substr instead of lvalue substr. Make appropriate use of lvalue values. Use glob, not <>. Avoid a raw select for non-integer sleeps. Always use a block with a map and grep. Use the non-builtin builtins.

ControlStructures
63. 64. 65. 66. 67. 68. 69. 70. 71. 72. 73. 74. 75. 76. 77. 78. 79. 80. 81. 82. 83. 84. Use block if, not postfix if. Reserve postfix if for flow-of-control statements. Dont use postfix unless, for, while, or until. Dont use unless or until at all. Avoid C-style for statements. Avoid subscripting arrays or hashes within loops. Never subscript more than once in a loop. Use named lexicals as explicit for loop iterators. Always declare a for loop iterator variable with my. Use map instead of for when generating new lists from old. Use grep and first instead of for when searching for values in a list. Use for instead of map when transforming a list in place. Use a subroutine call to factor out complex list transformations. Never modify $_ in a list function. Avoid cascading an if. Use table look-up in preference to cascaded equality tests. When producing a value, use tabular ternaries. Dont use dowhile loops. Reject as many iterations as possible, as early as possible. Dont contort loop structures just to consolidate control. Use for and redo instead of an irregularly counted while. Label every loop that is exited explicitly, and use the label with every next, last, or redo.

Subroutines
113. 114. 115. 116. 117. 118. 119. 120. 121. 122. 123. 124. Call subroutines with parentheses but without a leading &. Dont give subroutines the same names as built-in functions. Always unpack @_ first. Use a hash of named arguments for any subroutine that has more than three parameters. Use definedness or existence to test for missing arguments. Resolve any default argument values as soon as @_ is unpacked. Always return scalar in scalar returns. Make list-returning subroutines return the obvious value in scalar context. When there is no obvious scalar context return value, consider Contextual::Return instead. Dont use subroutine prototypes. Always return via an explicit return. Use a bare return to return failure.

NamingConventions
23. 24. 25. 26. 27. 28. 29. 30. 31. 32. Use grammatical templates when forming identifiers. Name booleans after their associated test. Mark variables that store references with a _ref suffix. Name arrays in the plural and hashes in the singular. Use underscores to separate words in multiword identifiers. Distinguish different program components by case. Abbr idents by prefx. Abbreviate only when the meaning remains unambiguous. Avoid using inherently ambiguous words in names. Prefix for internal use only subroutines with an underscore.

ValuesandExpressions
33. Use interpolating string delimiters only for strings that actually interpolate. 34. Dont use "" or '' for an empty string. 35. Dont write one-character strings in visually ambiguous ways. 36. Use named character escapes instead of numeric escapes. 37. Use named constants, but dont use constant. 38. Dont pad decimal numbers with leading zeros.

I/O
125. Dont use bareword filehandles. 126. Use indirect filehandles. 127. If you have to use a package filehandle, localize it first.

128. Use either the IO::File module or the three-argument form of open. 129. Never open, close, or print to a file without checking the outcome. 130. Close filehandles explicitly, and as soon as possible. 131. Use while (<>), not for (<>). 132. Prefer line-based I/O to slurping. 133. Slurp a filehandle with a do block for purity. 134. Slurp a stream with Perl6::Slurp for power and simplicity. 135. Avoid using *STDIN, unless you really mean it. 136. Always put filehandles in braces within any print statement. 137. Always prompt for interactive input. 138. Dont reinvent the standard test for interactivity. 139. Use the IO::Prompt module for prompting. 140. Always convey the progress of long non-interactive operations within interactive applications. 141. Consider using the Smart::Comments module to automate your progress indicators. 142. Avoid a raw select when setting autoflushes.

172. 173. 174. 175. 176. 177. 178. 179. 180. 181. 182. 183. 184.

Make failed builtins throw exceptions too. Make failures fatal in all contexts. Be careful when testing for failure of the system builtin. Throw exceptions on all failures, including recoverable ones. Have exceptions report from the caller's location, not from the place where they were thrown. Compose error messages in the recipients dialect. Document every error message in the recipients dialect. Use exception objects whenever failure data needs to be conveyed to a handler. Use exception objects when error messages may change. Use exception objects when two or more exceptions are related. Catch exception objects in most-derived-first order. Build exception classes automatically. Unpack the exception variable in extended exception handlers.

215. 216. 217. 218.

Have attributes initialized and verified automatically. Specify coercions as :STRINGIFY, :NUMERIFY, and :BOOLIFY methods. Use :CUMULATIVE methods instead of SUPER:: calls. Dont use AUTOLOAD().

Modules
219. Design the modules interface first. 220. Place original code inline. Place duplicated code in a subroutine. Place duplicated subroutines in a module. 221. Use three-part version numbers. 222. Enforce your version requirements programmatically. 223. Export judiciously and, where possible, only by request. 224. Consider exporting declaratively. 225. Never make variables part of a modules interface. 226. Build new module frameworks automatically. 227. Use core modules wherever possible. 228. Use CPAN modules where feasible.

CommandLineProcessing
185. Enforce a single consistent command-line structure. 186. Adhere to a standard set of conventions in your command-line syntax. 187. Standardize your meta-options. 188. Allow the same filename to be specified for both input and output. 189. Standardize on a single approach to command-line processing. 190. Ensure that your interface, run-time messages, and documentation remain consistent. 191. Factor out common command-line interface components into a shared module.

References
143. Wherever possible, dereference with arrows. 144. Where prefix dereferencing is unavoidable, put braces around the reference. 145. Never use symbolic references. 146. Use weaken to prevent circular data structures from leaking memory.

TestingandDebugging
229. 230. 231. 232. 233. 234. 235. 236. 237. 238. Write the test cases first. Standardize your tests with Test::Simple or Test::More. Standardize your test suites with Test::Harness. Write test cases that fail. Test both the likely and the unlikely. Add new test cases before you start debugging. Always use strict. Always turn on warnings explicitly. Never assume that a warning-free compilation implies correctness. Turn off strictures or warnings explicitly, selectively, and in the smallest possible scope. 239. Learn at least a subset of the perl debugger. 240. Use serialized warnings when debugging manually. 241. Consider using smart comments when debugging, rather than warn statements.

RegularExpressions
147. 148. 149. 150. 151. 152. 153. 154. 155. 156. 157. 158. 159. 160. 161. 162. 163. 164. 165. 166. 167. 168. 169. 170. Always use the /x flag. Always use the /m flag. Use \A and \z as string boundary anchors. Use \z, not \Z, to indicate end of string. Always use the /s flag. Consider mandating the Regexp::Autoflags module. Use m{} in preference to // in multiline regexes. Dont use any delimiters other than // or m{}. Prefer singular character classes to escaped metacharacters. Prefer named characters to escaped metacharacters. Prefer properties to enumerated character classes. Consider matching arbitrary whitespace, rather than specific whitespace characters. Be specific when matching as much as possible. Use capturing parentheses only when you intend to capture. Use the numeric capture variables only when youre sure that the preceding match succeeded. Always give captured substrings proper names. Tokenize input using the /gc flag. Build regular expressions from tables. Build complex regular expressions from simpler pieces. Consider using Regexp::Common instead of writing your own regexes. Always use character classes instead of single-character alternations. Factor out common affixes from alternations. Prevent useless backtracking. Prefer fixed-string eq comparisons to fixed-pattern regex matches.

Objects
192. 193. 194. 195. 196. 197. 198. 199. 200. 201. 202. 203. 204. 205. 206. Make object orientation a choice, not a default. Choose object orientation using appropriate criteria. Dont use pseudohashes. Dont use restricted hashes. Always use fully encapsulated objects. Give every constructor the same standard name. Dont let a constructor clone objects. Always provide a destructor for every inside-out class. When creating methods, follow the general guidelines for subroutines. Provide separate read and write accessors. Dont use lvalue accessors. Dont use the indirect object syntax. Provide an optimal interface, rather than a minimal one. Overload only the isomorphic operators of algebraic classes. Always consider overloading the boolean, numeric, and string coercions of objects.

Miscellanea
242. Use a revision control system. 243. Integrate non-Perl code into your applications via the Inline:: modules. 244. Keep your configuration language uncomplicated. 245. Dont use formats. 246. Dont tie variables or filehandles. 247. Dont be clever. 248. If you must rely on cleverness, encapsulate it. 249. Dont optimize code benchmark it. 250. Dont optimize data structures measure them. 251. Look for opportunities to use caches. 252. Automate your subroutine caching. 253. Benchmark any caching strategy you use. 254. Dont optimize applications profile them. 255. Be careful to preserve semantics when refactoring syntax.
Perl Best Practices Reference Guide version 1.01.00. Perl Best Practices by Damian Conway 2005 OReilly Media Inc., All rights reserved. Reference Guide by Johan Vromans 2006 Squirrel Consultancy, All rights reserved.

ClassHierarchies
207. 208. 209. 210. 211. 212. 213. 214. Dont manipulate the list of base classes directly. Use distributed encapsulated objects. Never use the one-argument form of bless. Pass constructor arguments as labeled values, using a hash reference. Distinguish arguments for base classes by class name as well. Separate your construction, initialization, and destruction processes. Build the standard class infrastructure automatically. Use Class::Std to automate the deallocation of attribute data.

ErrorHandling
171. Throw exceptions instead of returning special values or setting flags.

You might also like