1PERLMODSTYLE(1) Perl Programmers Reference Guide PERLMODSTYLE(1)
2
3
4
6 perlmodstyle - Perl module style guide
7
9 This document attempts to describe the Perl Community's "best practice"
10 for writing Perl modules. It extends the recommendations found in
11 perlstyle , which should be considered required reading before reading
12 this document.
13
14 While this document is intended to be useful to all module authors, it
15 is particularly aimed at authors who wish to publish their modules on
16 CPAN.
17
18 The focus is on elements of style which are visible to the users of a
19 module, rather than those parts which are only seen by the module's
20 developers. However, many of the guidelines presented in this document
21 can be extrapolated and applied successfully to a module's internals.
22
23 This document differs from perlnewmod in that it is a style guide
24 rather than a tutorial on creating CPAN modules. It provides a
25 checklist against which modules can be compared to determine whether
26 they conform to best practice, without necessarily describing in detail
27 how to achieve this.
28
29 All the advice contained in this document has been gleaned from
30 extensive conversations with experienced CPAN authors and users. Every
31 piece of advice given here is the result of previous mistakes. This
32 information is here to help you avoid the same mistakes and the extra
33 work that would inevitably be required to fix them.
34
35 The first section of this document provides an itemized checklist;
36 subsequent sections provide a more detailed discussion of the items on
37 the list. The final section, "Common Pitfalls", describes some of the
38 most popular mistakes made by CPAN authors.
39
41 For more detail on each item in this checklist, see below.
42
43 Before you start
44 • Don't re-invent the wheel
45
46 • Patch, extend or subclass an existing module where possible
47
48 • Do one thing and do it well
49
50 • Choose an appropriate name
51
52 • Get feedback before publishing
53
54 The API
55 • API should be understandable by the average programmer
56
57 • Simple methods for simple tasks
58
59 • Separate functionality from output
60
61 • Consistent naming of subroutines or methods
62
63 • Use named parameters (a hash or hashref) when there are more than
64 two parameters
65
66 Stability
67 • Ensure your module works under "use strict" and "-w"
68
69 • Stable modules should maintain backwards compatibility
70
71 Documentation
72 • Write documentation in POD
73
74 • Document purpose, scope and target applications
75
76 • Document each publicly accessible method or subroutine, including
77 params and return values
78
79 • Give examples of use in your documentation
80
81 • Provide a README file and perhaps also release notes, changelog,
82 etc
83
84 • Provide links to further information (URL, email)
85
86 Release considerations
87 • Specify pre-requisites in Makefile.PL or Build.PL
88
89 • Specify Perl version requirements with "use"
90
91 • Include tests with your module
92
93 • Choose a sensible and consistent version numbering scheme (X.YY is
94 the common Perl module numbering scheme)
95
96 • Increment the version number for every change, no matter how small
97
98 • Package the module using "make dist"
99
100 • Choose an appropriate license (GPL/Artistic is a good default)
101
103 Try not to launch headlong into developing your module without spending
104 some time thinking first. A little forethought may save you a vast
105 amount of effort later on.
106
107 Has it been done before?
108 You may not even need to write the module. Check whether it's already
109 been done in Perl, and avoid re-inventing the wheel unless you have a
110 good reason.
111
112 Good places to look for pre-existing modules include MetaCPAN
113 <https://metacpan.org> and PrePAN <http://prepan.org> and asking on
114 "module-authors@perl.org"
115 (<https://lists.perl.org/list/module-authors.html>).
116
117 If an existing module almost does what you want, consider writing a
118 patch, writing a subclass, or otherwise extending the existing module
119 rather than rewriting it.
120
121 Do one thing and do it well
122 At the risk of stating the obvious, modules are intended to be modular.
123 A Perl developer should be able to use modules to put together the
124 building blocks of their application. However, it's important that the
125 blocks are the right shape, and that the developer shouldn't have to
126 use a big block when all they need is a small one.
127
128 Your module should have a clearly defined scope which is no longer than
129 a single sentence. Can your module be broken down into a family of
130 related modules?
131
132 Bad example:
133
134 "FooBar.pm provides an implementation of the FOO protocol and the
135 related BAR standard."
136
137 Good example:
138
139 "Foo.pm provides an implementation of the FOO protocol. Bar.pm
140 implements the related BAR protocol."
141
142 This means that if a developer only needs a module for the BAR
143 standard, they should not be forced to install libraries for FOO as
144 well.
145
146 What's in a name?
147 Make sure you choose an appropriate name for your module early on.
148 This will help people find and remember your module, and make
149 programming with your module more intuitive.
150
151 When naming your module, consider the following:
152
153 • Be descriptive (i.e. accurately describes the purpose of the
154 module).
155
156 • Be consistent with existing modules.
157
158 • Reflect the functionality of the module, not the implementation.
159
160 • Avoid starting a new top-level hierarchy, especially if a suitable
161 hierarchy already exists under which you could place your module.
162
163 Get feedback before publishing
164 If you have never uploaded a module to CPAN before (and even if you
165 have), you are strongly encouraged to get feedback on PrePAN
166 <http://prepan.org>. PrePAN is a site dedicated to discussing ideas
167 for CPAN modules with other Perl developers and is a great resource for
168 new (and experienced) Perl developers.
169
170 You should also try to get feedback from people who are already
171 familiar with the module's application domain and the CPAN naming
172 system. Authors of similar modules, or modules with similar names, may
173 be a good place to start, as are community sites like Perl Monks
174 <https://www.perlmonks.org>.
175
177 Considerations for module design and coding:
178
179 To OO or not to OO?
180 Your module may be object oriented (OO) or not, or it may have both
181 kinds of interfaces available. There are pros and cons of each
182 technique, which should be considered when you design your API.
183
184 In Perl Best Practices (copyright 2004, Published by O'Reilly Media,
185 Inc.), Damian Conway provides a list of criteria to use when deciding
186 if OO is the right fit for your problem:
187
188 • The system being designed is large, or is likely to become large.
189
190 • The data can be aggregated into obvious structures, especially if
191 there's a large amount of data in each aggregate.
192
193 • The various types of data aggregate form a natural hierarchy that
194 facilitates the use of inheritance and polymorphism.
195
196 • You have a piece of data on which many different operations are
197 applied.
198
199 • You need to perform the same general operations on related types of
200 data, but with slight variations depending on the specific type of
201 data the operations are applied to.
202
203 • It's likely you'll have to add new data types later.
204
205 • The typical interactions between pieces of data are best
206 represented by operators.
207
208 • The implementation of individual components of the system is likely
209 to change over time.
210
211 • The system design is already object-oriented.
212
213 • Large numbers of other programmers will be using your code modules.
214
215 Think carefully about whether OO is appropriate for your module.
216 Gratuitous object orientation results in complex APIs which are
217 difficult for the average module user to understand or use.
218
219 Designing your API
220 Your interfaces should be understandable by an average Perl programmer.
221 The following guidelines may help you judge whether your API is
222 sufficiently straightforward:
223
224 Write simple routines to do simple things.
225 It's better to have numerous simple routines than a few monolithic
226 ones. If your routine changes its behaviour significantly based on
227 its arguments, it's a sign that you should have two (or more)
228 separate routines.
229
230 Separate functionality from output.
231 Return your results in the most generic form possible and allow the
232 user to choose how to use them. The most generic form possible is
233 usually a Perl data structure which can then be used to generate a
234 text report, HTML, XML, a database query, or whatever else your
235 users require.
236
237 If your routine iterates through some kind of list (such as a list
238 of files, or records in a database) you may consider providing a
239 callback so that users can manipulate each element of the list in
240 turn. File::Find provides an example of this with its
241 "find(\&wanted, $dir)" syntax.
242
243 Provide sensible shortcuts and defaults.
244 Don't require every module user to jump through the same hoops to
245 achieve a simple result. You can always include optional
246 parameters or routines for more complex or non-standard behaviour.
247 If most of your users have to type a few almost identical lines of
248 code when they start using your module, it's a sign that you should
249 have made that behaviour a default. Another good indicator that
250 you should use defaults is if most of your users call your routines
251 with the same arguments.
252
253 Naming conventions
254 Your naming should be consistent. For instance, it's better to
255 have:
256
257 display_day();
258 display_week();
259 display_year();
260
261 than
262
263 display_day();
264 week_display();
265 show_year();
266
267 This applies equally to method names, parameter names, and anything
268 else which is visible to the user (and most things that aren't!)
269
270 Parameter passing
271 Use named parameters. It's easier to use a hash like this:
272
273 $obj->do_something(
274 name => "wibble",
275 type => "text",
276 size => 1024,
277 );
278
279 ... than to have a long list of unnamed parameters like this:
280
281 $obj->do_something("wibble", "text", 1024);
282
283 While the list of arguments might work fine for one, two or even
284 three arguments, any more arguments become hard for the module user
285 to remember, and hard for the module author to manage. If you want
286 to add a new parameter you will have to add it to the end of the
287 list for backward compatibility, and this will probably make your
288 list order unintuitive. Also, if many elements may be undefined
289 you may see the following unattractive method calls:
290
291 $obj->do_something(undef, undef, undef, undef, undef, 1024);
292
293 Provide sensible defaults for parameters which have them. Don't
294 make your users specify parameters which will almost always be the
295 same.
296
297 The issue of whether to pass the arguments in a hash or a hashref
298 is largely a matter of personal style.
299
300 The use of hash keys starting with a hyphen ("-name") or entirely
301 in upper case ("NAME") is a relic of older versions of Perl in
302 which ordinary lower case strings were not handled correctly by the
303 "=>" operator. While some modules retain uppercase or hyphenated
304 argument keys for historical reasons or as a matter of personal
305 style, most new modules should use simple lower case keys.
306 Whatever you choose, be consistent!
307
308 Strictness and warnings
309 Your module should run successfully under the strict pragma and should
310 run without generating any warnings. Your module should also handle
311 taint-checking where appropriate, though this can cause difficulties in
312 many cases.
313
314 Backwards compatibility
315 Modules which are "stable" should not break backwards compatibility
316 without at least a long transition phase and a major change in version
317 number.
318
319 Error handling and messages
320 When your module encounters an error it should do one or more of:
321
322 • Return an undefined value.
323
324 • set $Module::errstr or similar ("errstr" is a common name used by
325 DBI and other popular modules; if you choose something else, be
326 sure to document it clearly).
327
328 • "warn()" or "carp()" a message to STDERR.
329
330 • "croak()" only when your module absolutely cannot figure out what
331 to do. ("croak()" is a better version of "die()" for use within
332 modules, which reports its errors from the perspective of the
333 caller. See Carp for details of "croak()", "carp()" and other
334 useful routines.)
335
336 • As an alternative to the above, you may prefer to throw exceptions
337 using the Error module.
338
339 Configurable error handling can be very useful to your users. Consider
340 offering a choice of levels for warning and debug messages, an option
341 to send messages to a separate file, a way to specify an error-handling
342 routine, or other such features. Be sure to default all these options
343 to the commonest use.
344
346 POD
347 Your module should include documentation aimed at Perl developers. You
348 should use Perl's "plain old documentation" (POD) for your general
349 technical documentation, though you may wish to write additional
350 documentation (white papers, tutorials, etc) in some other format. You
351 need to cover the following subjects:
352
353 • A synopsis of the common uses of the module
354
355 • The purpose, scope and target applications of your module
356
357 • Use of each publicly accessible method or subroutine, including
358 parameters and return values
359
360 • Examples of use
361
362 • Sources of further information
363
364 • A contact email address for the author/maintainer
365
366 The level of detail in Perl module documentation generally goes from
367 less detailed to more detailed. Your SYNOPSIS section should contain a
368 minimal example of use (perhaps as little as one line of code; skip the
369 unusual use cases or anything not needed by most users); the
370 DESCRIPTION should describe your module in broad terms, generally in
371 just a few paragraphs; more detail of the module's routines or methods,
372 lengthy code examples, or other in-depth material should be given in
373 subsequent sections.
374
375 Ideally, someone who's slightly familiar with your module should be
376 able to refresh their memory without hitting "page down". As your
377 reader continues through the document, they should receive a
378 progressively greater amount of knowledge.
379
380 The recommended order of sections in Perl module documentation is:
381
382 • NAME
383
384 • SYNOPSIS
385
386 • DESCRIPTION
387
388 • One or more sections or subsections giving greater detail of
389 available methods and routines and any other relevant information.
390
391 • BUGS/CAVEATS/etc
392
393 • AUTHOR
394
395 • SEE ALSO
396
397 • COPYRIGHT and LICENSE
398
399 Keep your documentation near the code it documents ("inline"
400 documentation). Include POD for a given method right above that
401 method's subroutine. This makes it easier to keep the documentation up
402 to date, and avoids having to document each piece of code twice (once
403 in POD and once in comments).
404
405 README, INSTALL, release notes, changelogs
406 Your module should also include a README file describing the module and
407 giving pointers to further information (website, author email).
408
409 An INSTALL file should be included, and should contain simple
410 installation instructions. When using ExtUtils::MakeMaker this will
411 usually be:
412
413 perl Makefile.PL
414 make
415 make test
416 make install
417
418 When using Module::Build, this will usually be:
419
420 perl Build.PL
421 perl Build
422 perl Build test
423 perl Build install
424
425 Release notes or changelogs should be produced for each release of your
426 software describing user-visible changes to your module, in terms
427 relevant to the user.
428
429 Unless you have good reasons for using some other format (for example,
430 a format used within your company), the convention is to name your
431 changelog file "Changes", and to follow the simple format described in
432 CPAN::Changes::Spec.
433
435 Version numbering
436 Version numbers should indicate at least major and minor releases, and
437 possibly sub-minor releases. A major release is one in which most of
438 the functionality has changed, or in which major new functionality is
439 added. A minor release is one in which a small amount of functionality
440 has been added or changed. Sub-minor version numbers are usually used
441 for changes which do not affect functionality, such as documentation
442 patches.
443
444 The most common CPAN version numbering scheme looks like this:
445
446 1.00, 1.10, 1.11, 1.20, 1.30, 1.31, 1.32
447
448 A correct CPAN version number is a floating point number with at least
449 2 digits after the decimal. You can test whether it conforms to CPAN
450 by using
451
452 perl -MExtUtils::MakeMaker -le 'print MM->parse_version(shift)' \
453 'Foo.pm'
454
455 If you want to release a 'beta' or 'alpha' version of a module but
456 don't want CPAN.pm to list it as most recent use an '_' after the
457 regular version number followed by at least 2 digits, eg. 1.20_01. If
458 you do this, the following idiom is recommended:
459
460 our $VERSION = "1.12_01"; # so CPAN distribution will have
461 # right filename
462 our $XS_VERSION = $VERSION; # only needed if you have XS code
463 $VERSION = eval $VERSION; # so "use Module 0.002" won't warn on
464 # underscore
465
466 With that trick MakeMaker will only read the first line and thus read
467 the underscore, while the perl interpreter will evaluate the $VERSION
468 and convert the string into a number. Later operations that treat
469 $VERSION as a number will then be able to do so without provoking a
470 warning about $VERSION not being a number.
471
472 Never release anything (even a one-word documentation patch) without
473 incrementing the number. Even a one-word documentation patch should
474 result in a change in version at the sub-minor level.
475
476 Once picked, it is important to stick to your version scheme, without
477 reducing the number of digits. This is because "downstream" packagers,
478 such as the FreeBSD ports system, interpret the version numbers in
479 various ways. If you change the number of digits in your version
480 scheme, you can confuse these systems so they get the versions of your
481 module out of order, which is obviously bad.
482
483 Pre-requisites
484 Module authors should carefully consider whether to rely on other
485 modules, and which modules to rely on.
486
487 Most importantly, choose modules which are as stable as possible. In
488 order of preference:
489
490 • Core Perl modules
491
492 • Stable CPAN modules
493
494 • Unstable CPAN modules
495
496 • Modules not available from CPAN
497
498 Specify version requirements for other Perl modules in the pre-
499 requisites in your Makefile.PL or Build.PL.
500
501 Be sure to specify Perl version requirements both in Makefile.PL or
502 Build.PL and with "require 5.6.1" or similar. See the section on "use
503 VERSION" of "require" in perlfunc for details.
504
505 Testing
506 All modules should be tested before distribution (using "make
507 disttest"), and the tests should also be available to people installing
508 the modules (using "make test"). For Module::Build you would use the
509 "make test" equivalent "perl Build test".
510
511 The importance of these tests is proportional to the alleged stability
512 of a module. A module which purports to be stable or which hopes to
513 achieve wide use should adhere to as strict a testing regime as
514 possible.
515
516 Useful modules to help you write tests (with minimum impact on your
517 development process or your time) include Test::Simple, Carp::Assert
518 and Test::Inline. For more sophisticated test suites there are
519 Test::More and Test::MockObject.
520
521 Packaging
522 Modules should be packaged using one of the standard packaging tools.
523 Currently you have the choice between ExtUtils::MakeMaker and the more
524 platform independent Module::Build, allowing modules to be installed in
525 a consistent manner. When using ExtUtils::MakeMaker, you can use "make
526 dist" to create your package. Tools exist to help you to build your
527 module in a MakeMaker-friendly style. These include
528 ExtUtils::ModuleMaker and h2xs. See also perlnewmod.
529
530 Licensing
531 Make sure that your module has a license, and that the full text of it
532 is included in the distribution (unless it's a common one and the terms
533 of the license don't require you to include it).
534
535 If you don't know what license to use, dual licensing under the GPL and
536 Artistic licenses (the same as Perl itself) is a good idea. See
537 perlgpl and perlartistic.
538
540 Reinventing the wheel
541 There are certain application spaces which are already very, very well
542 served by CPAN. One example is templating systems, another is date and
543 time modules, and there are many more. While it is a rite of passage
544 to write your own version of these things, please consider carefully
545 whether the Perl world really needs you to publish it.
546
547 Trying to do too much
548 Your module will be part of a developer's toolkit. It will not, in
549 itself, form the entire toolkit. It's tempting to add extra features
550 until your code is a monolithic system rather than a set of modular
551 building blocks.
552
553 Inappropriate documentation
554 Don't fall into the trap of writing for the wrong audience. Your
555 primary audience is a reasonably experienced developer with at least a
556 moderate understanding of your module's application domain, who's just
557 downloaded your module and wants to start using it as quickly as
558 possible.
559
560 Tutorials, end-user documentation, research papers, FAQs etc are not
561 appropriate in a module's main documentation. If you really want to
562 write these, include them as sub-documents such as
563 "My::Module::Tutorial" or "My::Module::FAQ" and provide a link in the
564 SEE ALSO section of the main documentation.
565
567 perlstyle
568 General Perl style guide
569
570 perlnewmod
571 How to create a new module
572
573 perlpod
574 POD documentation
575
576 podchecker
577 Verifies your POD's correctness
578
579 Packaging Tools
580 ExtUtils::MakeMaker, Module::Build
581
582 Testing tools
583 Test::Simple, Test::Inline, Carp::Assert, Test::More,
584 Test::MockObject
585
586 <https://pause.perl.org/>
587 Perl Authors Upload Server. Contains links to information for
588 module authors.
589
590 Any good book on software engineering
591
593 Kirrily "Skud" Robert <skud@cpan.org>
594
595
596
597perl v5.34.1 2022-03-15 PERLMODSTYLE(1)