Login
Regenerated META and MANIFEST
[gknop/Perl-Critic.git] / README
CommitLineData
b9e35135
JRT
1NAME
2 Perl::Critic - Critique Perl source code for best-practices
3
4SYNOPSIS
5 use Perl::Critic;
6 my $file = shift;
7 my $critic = Perl::Critic->new();
8 my @violations = $critic->critique($file);
9 print @violations;
10
11DESCRIPTION
12 Perl::Critic is an extensible framework for creating and applying coding
13 standards to Perl source code. Essentially, it is a static source code
14 analysis engine. Perl::Critic is distributed with a number of
15 Perl::Critic::Policy modules that attempt to enforce various coding
16 guidelines. Most Policy modules are based on Damian Conway's book Perl
17 Best Practices. However, Perl::Critic is not limited to PBP and will
18 even support Policies that contradict Conway. You can enable, disable,
19 and customize those Polices through the Perl::Critic interface. You can
20 also create new Policy modules that suit your own tastes.
21
22 For a convenient command-line interface to Perl::Critic, see the
23 documentation for perlcritic. If you want to integrate Perl::Critic with
24 your build process, Test::Perl::Critic provides an interface that is
25 suitable for test scripts. For the ultimate convenience (at the expense
26 of some flexibility) see the criticism pragma.
27
28 Win32 and ActivePerl users can find PPM distributions of Perl::Critic at
29 <http://theoryx5.uwinnipeg.ca/ppms/>.
30
31 If you'd like to try Perl::Critic before you install it, there is a
32 web-service available at <http://perlcritic.com>. The web-service does
33 not yet support all the configuration features that are available in the
34 native Perl::Critic API, but it should give you a good idea of what it
35 does.
36
37CONSTRUCTOR
38 "new( -profile => $FILE, -severity => $N, -include => \@PATTERNS,
39 -exclude => \@PATTERNS, -top => N, -force => 1 )"
40 Returns a reference to a new Perl::Critic object. Most arguments
41 are just passed directly into Perl::Critic::Config, but I have
42 described them here as well. All arguments are optional
43 key-value pairs as follows:
44
45 -profile is a path to a configuration file. If $FILE is not
46 defined, Perl::Critic::Config attempts to find a .perlcriticrc
47 configuration file in the current directory, and then in your
48 home directory. Alternatively, you can set the "PERLCRITIC"
49 environment variable to point to a file in another location. If
50 a configuration file can't be found, or if $FILE is an empty
51 string, then all Policies will be loaded with their default
52 configuration. See "CONFIGURATION" for more information.
53
54 -severity is the minimum severity level. Only Policy modules
55 that have a severity greater than $N will be loaded. Severity
56 values are integers ranging from 1 (least severe) to 5 (most
57 severe). The default is 5. For a given "-profile", decreasing
58 the "-severity" will usually result in more Policy violations.
59 Users can redefine the severity level for any Policy in their
60 .perlcriticrc file. See "CONFIGURATION" for more information.
61
62 -include is a reference to a list of string @PATTERNS. Policy
63 modules that match at least one "m/$PATTERN/imx" will always be
64 loaded, irrespective of the severity settings. For example:
65
66 my $critic = Perl::Critic->new(-include => ['layout'] -severity => 4);
67
68 This would cause Perl::Critic to load all the "CodeLayout::*"
69 Policy modules even though they have a severity level that is
70 less than 4. You can use "-include" in conjunction with the
71 "-exclude" option. Note that "-exclude" takes precedence over
72 "-include" when a Policy matches both patterns.
73
74 -exclude is a reference to a list of string @PATTERNS. Policy
75 modules that match at least one "m/$PATTERN/imx" will not be
76 loaded, irrespective of the severity settings. For example:
77
78 my $critic = Perl::Critic->new(-exclude => ['strict'] -severity => 1);
79
80 This would cause Perl::Critic to not load the "RequireUseStrict"
81 and "ProhibitNoStrict" Policy modules even though they have a
82 severity level that is greater than 1. You can use "-exclude" in
83 conjunction with the "-include" option. Note that "-exclude"
84 takes precedence over "-include" when a Policy matches both
85 patterns.
86
87 -top is the maximum number of Violations to return when ranked
88 by their severity levels. Violations are still returned in the
89 order that they occur within the file. This must be a positive
90 integer
91
92 -force controls whether Perl::Critic observes the magical ""##
93 no critic"" pseudo-pragmas in your code. If set to a true value,
94 Perl::Critic will analyze all code. If set to a false value
95 (which is the default) Perl::Critic will ignore code that is
96 tagged with these comments. See "BENDING THE RULES" for more
97 information.
98
99 -config is a reference to a Perl::Critic::Config object. If you
100 have created your own Config object for some reason, you can
101 pass it in here instead of having Perl::Critic create one for
102 you. Using the "-config" option causes all the other options to
103 be silently ignored.
104
105METHODS
106 "critique( $source_code )"
107 Runs the $source_code through the Perl::Critic engine using all
108 the Policies that have been loaded into this engine. If
109 $source_code is a scalar reference, then it is treated as string
110 of actual Perl code. If $source_code is a reference to an
111 instance of PPI::Document, then that instance is used directly.
112 Otherwise, it is treated as a path to a local file containing
113 Perl code. This method Returns a list of Perl::Critic::Violation
114 objects for each violation of the loaded Policies. The list is
115 sorted in the order that the Violations appear in the code. If
116 there are no violations, this method returns an empty list.
117
118 "add_policy( -policy => $policy_name, -config => \%config_hash )"
119 Creates a Policy object and loads it into this Critic. If the
120 object cannot be instantiated, it will throw a warning and
121 return a false value. Otherwise, it returns a reference to this
122 Critic.
123
124 -policy is the name of a Perl::Critic::Policy subclass module.
125 The 'Perl::Critic::Policy' portion of the name can be omitted
126 for brevity. This argument is required.
127
128 -config is an optional reference to a hash of Policy
129 configuration parameters. Note that this is not the same thing
130 as a Perl::Critic::Config object. The contents of this hash
131 reference will be passed into to the constructor of the Policy
132 module. See the documentation in the relevant Policy module for
133 a description of the arguments it supports.
134
135 "policies()"
136 Returns a list containing references to all the Policy objects
137 that have been loaded into this engine. Objects will be in the
138 order that they were loaded.
139
140 "config()"
141 Returns the Perl::Critic::Config object that was created for or
142 given to this Critic.
143
144FUNCTIONAL INTERFACE
145 For those folks who prefer to have a functional interface, The
146 "critique" method can be exported on request and called as a static
147 function. If the first argument is a hashref, its contents are used to
148 construct a new Perl::Critic object internally. The keys of that hash
149 should be the same as those supported by the "Perl::Critic::new" method.
150 Here are some examples:
151
152 use Perl::Critic qw(critique);
153
154 # Use default parameters...
155 @violations = critique( $some_file );
156
157 # Use custom parameters...
158 @violations = critique( {-severity => 2}, $some_file );
159
160 # As a one-liner
161 %> perl -MPerl::Critic=critique -e 'print critique(shift)' some_file.pm
162
163 None of the other object-methods are currently supported as static
164 functions. Sorry.
165
166CONFIGURATION
167 The default configuration file is called .perlcriticrc. Perl::Critic
168 will look for this file in the current directory first, and then in your
169 home directory. Alternatively, you can set the "PERLCRITIC" environment
170 variable to explicitly point to a different file in another location. If
171 none of these files exist, and the "-profile" option is not given to the
172 constructor, then all the modules that are found in the
173 Perl::Critic::Policy namespace will be loaded with their default
174 configuration.
175
176 The format of the configuration file is a series of INI-style sections
177 that contain key-value pairs separated by '='. Comments should start
178 with '#' and can be placed on a separate line or after the name-value
179 pairs if you desire. The general recipe is a series of blocks like this:
180
181 [Perl::Critic::Policy::Category::PolicyName]
182 severity = 1
183 arg1 = value1
184 arg2 = value2
185
186 "Perl::Critic::Policy::Category::PolicyName" is the full name of a
187 module that implements the policy. The Policy modules distributed with
188 Perl::Critic have been grouped into categories according to the table of
189 contents in Damian Conway's book Perl Best Practices. For brevity, you
190 can omit the 'Perl::Critic::Policy' part of the module name.
191
192 "severity" is the level of importance you wish to assign to the Policy.
193 All Policy modules are defined with a default severity value ranging
194 from 1 (least severe) to 5 (most severe). However, you may disagree with
195 the default severity and choose to give it a higher or lower severity,
196 based on your own coding philosophy.
197
198 The remaining key-value pairs are configuration parameters that will be
199 passed into the constructor for that Policy. The constructors for most
200 Policy objects do not support arguments, and those that do should have
201 reasonable defaults. See the documentation on the appropriate Policy
202 module for more details.
203
204 Instead of redefining the severity for a given Policy, you can
205 completely disable a Policy by prepending a '-' to the name of the
206 module in your configuration file. In this manner, the Policy will never
207 be loaded, regardless of the "-severity" given to the Perl::Critic
208 constructor.
209
210 A simple configuration might look like this:
211
212 #--------------------------------------------------------------
213 # I think these are really important, so always load them
214
215 [TestingAndDebugging::RequireUseStrict]
216 severity = 5
217
218 [TestingAndDebugging::RequireUseWarnings]
219 severity = 5
220
221 #--------------------------------------------------------------
222 # I think these are less important, so only load when asked
223
224 [Variables::ProhibitPackageVars]
225 severity = 2
226
227 [ControlStructures::ProhibitPostfixControls]
228 allow = if unless #My custom configuration
229 severity = 2
230
231 #--------------------------------------------------------------
232 # I do not agree with these at all, so never load them
233
234 [-NamingConventions::ProhibitMixedCaseVars]
235 [-NamingConventions::ProhibitMixedCaseSubs]
236
237 #--------------------------------------------------------------
238 # For all other Policies, I accept the default severity,
239 # so no additional configuration is required for them.
240
241 A few sample configuration files are included in this distribution under
242 the t/samples directory. The perlcriticrc.none file demonstrates how to
243 disable Policy modules. The perlcriticrc.levels file demonstrates how to
244 redefine the severity level for any given Policy module. The
245 perlcriticrc.pbp file configures Perl::Critic to load only Policies
246 described in Damian Conway's book "Perl Best Practice."
247
248THE POLICIES
249 A large number of Policy modules are distributed with Perl::Critic. They
250 are described briefly in the companion document
251 Perl::Critic::PolicySummary and in more detail in the individual modules
252 themselves.
253
254BENDING THE RULES
255 Perl::Critic takes a hard-line approach to your code: either you comply
256 or you don't. In the real world, it is not always practical (nor even
257 possible) to fully comply with coding standards. In such cases, it is
258 wise to show that you are knowingly violating the standards and that you
259 have a Damn Good Reason (DGR) for doing so.
260
261 To help with those situations, you can direct Perl::Critic to ignore
262 certain lines or blocks of code by using pseudo-pragmas:
263
264 require 'LegacyLibaray1.pl'; ## no critic
265 require 'LegacyLibrary2.pl'; ## no critic
266
267 for my $element (@list) {
268
269 ## no critic
270
271 $foo = ""; #Violates 'ProhibitEmptyQuotes'
272 $barf = bar() if $foo; #Violates 'ProhibitPostfixControls'
273 #Some more evil code...
274
275 ## use critic
276
277 #Some good code...
278 do_something($_);
279 }
280
281 The "## no critic" comments direct Perl::Critic to ignore the remaining
282 lines of code until the end of the current block, or until a "## use
283 critic" comment is found (whichever comes first). If the "## no critic"
284 comment is on the same line as a code statement, then only that line of
285 code is overlooked. To direct perlcritic to ignore the "## no critic"
286 comments, use the "-force" option.
287
288 A bare "## no critic" comment disables all the active Policies. If you
289 wish to disable only specific Policies, add a list of Policy names as
290 arguments, just as you would for the "no strict" or ""no warnings""
291 pragmas. For example, this would disable the "ProhibitEmptyQuotes" and
292 "ProhibitPostfixControls" policies until the end of the block or until
293 the next "## use critic" comment (whichever comes first):
294
295 ## no critic (EmptyQuotes, PostfixControls)
296
297 $foo = ""; #Now exempt from ValuesAndExpressions::ProhibitEmptyQuotes
298 $barf = bar() if $foo; #Now exempt ControlStructures::ProhibitPostfixControls
299 $long_int = 10000000000; #Still subjected to ValuesAndExpression::RequireNumberSeparators
300
301 Since the Policy names are matched against the arguments as regular
302 expressions, you can abbreviate the Policy names or disable an entire
303 family of Policies in one shot like this:
304
305 ## no critic (NamingConventions)
306
307 my $camelHumpVar = 'foo'; #Now exempt from NamingConventions::ProhibitMixedCaseVars
308 sub camelHumpSub {} #Now exempt from NamingConventions::ProhibitMixedCaseSubs
309
310 The argument list must be enclosed in parens and must contain one or
311 more comma-separated barewords (e.g. don't use quotes). The ""## no
312 critic"" pragmas can be nested, and Policies named by an inner pragma
313 will be disabled along with those already disabled an outer pragma.
314
315 Use this feature wisely. "## no critic" should be used in the smallest
316 possible scope, or only on individual lines of code. And you should
317 always be as specific as possible about which policies you want to
318 disable (i.e. never use a bare "## no critic"). If Perl::Critic
319 complains about your code, try and find a compliant solution before
320 resorting to this feature.
321
322IMPORTANT CHANGES
323 Perl-Critic is evolving rapidly, so some of the interfaces have changed
324 in ways that are not backward-compatible. If you have been using an
325 older version of Perl-Critic and/or you have been developing custom
326 Policy modules, please read this section carefully.
327
328 VERSION 0.16
329 Starting in version 0.16, you can add a list Policy names as arguments
330 to the "## no critic" pseudo-pragma. This feature allows you to disable
331 specific policies. So if you have been in the habit of adding additional
332 words after "no critic", then those words might cause unexpected
333 results. If you want to append other stuff to the ""## no critic""
334 comment, then terminate the pseudo-pragma with a semi-colon, and then
335 start another comment. For example:
336
337 #This may not work as expected.
338 $email = 'foo@bar.com'; ## no critic for literal '@'
339
340 #This will work.
341 $email = 'foo@bar.com'; ## no critic; #for literal '@'
342
343 #This is even better.
344 $email = 'foo@bar.com'; ## no critic (RequireInterpolation);
345
346 VERSION 0.14
347 Starting in version 0.14, the interface to Perl::Critic::Violation
348 changed. This will also break any custom Policy modules that you might
349 have written for earlier modules. See Perl::Critic::DEVELOPER for an
350 up-to-date guide on creating Policy modules.
351
352 The notion of "priority" was also replaced with "severity" in version
353 0.14. Consequently, the default behavior of Perl::Critic is to only load
354 the most "severe" Policy modules, rather than loading all of them. This
355 decision was based on user-feedback suggesting that Perl-Critic should
356 be less critical for new users, and should steer them toward gradually
357 increasing the strictness as they progressively adopt better coding
358 practices.
359
360 VERSION 0.11
361 Starting in version 0.11, the internal mechanics of Perl-Critic were
362 rewritten so that only one traversal of the PPI document tree is
363 required. Unfortunately, this will break any custom Policy modules that
364 you might have written for earlier versions. Converting your policies to
365 work with the new version is pretty easy and actually results in cleaner
366 code. See Perl::Critic::DEVELOPER for an up-to-date guide on creating
367 Policy modules.
368
369THE Perl::Critic PHILOSOPHY
370 Coding standards are deeply personal and highly subjective. The
371 goal of Perl::Critic is to help you write code that conforms with a
372 set of best practices. Our primary goal is not to dictate what
373 those practices are, but rather, to implement the practices
374 discovered by others. Ultimately, you make the rules --
375 Perl::Critic is merely a tool for encouraging consistency. If there
376 is a policy that you think is important or that we have overlooked,
377 we would be very grateful for contributions, or you can simply load
378 your own private set of policies into Perl::Critic.
379
380EXTENDING THE CRITIC
381 The modular design of Perl::Critic is intended to facilitate the
382 addition of new Policies. You'll need to have some understanding of PPI,
383 but most Policy modules are pretty straightforward and only require
384 about 20 lines of code. Please see the Perl::Critic::DEVELOPER file
385 included in this distribution for a step-by-step demonstration of how to
386 create new Policy modules.
387
388 If you develop any new Policy modules, feel free to send them to
389 "thaljef@cpan.org" and I'll be happy to put them into the Perl::Critic
390 distribution. Or if you'd like to work on the Perl::Critic project
391 directly, check out our repository at <http://perlcritic.tigris.org>. To
392 subscribe to our mailing list, send a message to
393 "dev-subscribe@perlcritic.tigris.org".
394
395PREREQUISITES
396 Perl::Critic requires the following modules:
397
398 Config::Tiny
399
400 File::Spec
401
402 IO::String
403
404 List::Util
405
406 List::MoreUtils
407
408 Module::Pluggable
409
410 PPI
411
412 Pod::Usage
413
414 Pod::PlainText
415
416 Scalar::Util
417
418 String::Format
419
420 The following modules are optional, but recommended for complete
421 testing:
422
423 Test::Pod
424
425 Test::Pod::Coverage
426
427BUGS
428 Scrutinizing Perl code is hard for humans, let alone machines. If you
429 find any bugs, particularly false-positives or false-negatives from a
430 Perl::Critic::Policy, please submit them to
431 <http://rt.cpan.org/NoAuth/Bugs.html?Dist=Perl-Critic>. Thanks.
432
433CREDITS
434 Adam Kennedy - For creating PPI, the heart and soul of Perl::Critic.
435
436 Damian Conway - For writing Perl Best Practices, finally :)
437
438 Chris Dolan - For contributing the best features and Policy modules.
439
440 Giuseppe Maxia - For all the great ideas and positive encouragement.
441
442 and Sharon, my wife - For putting up with my all-night code sessions.
443
444AUTHOR
445 Jeffrey Ryan Thalhammer <thaljef@cpan.org>
446
447COPYRIGHT
448 Copyright (c) 2005-2006 Jeffrey Ryan Thalhammer. All rights reserved.
449
450 This program is free software; you can redistribute it and/or modify it
451 under the same terms as Perl itself. The full text of this license can
452 be found in the LICENSE file included with this module.
453