2 Perl::Critic - Critique Perl source code for best-practices.
7 my $critic = Perl::Critic->new();
8 my @violations = $critic->critique($file);
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.
22 For a command-line interface to Perl::Critic, see the documentation for
23 perlcritic. If you want to integrate Perl::Critic with your build
24 process, Test::Perl::Critic provides an interface that is suitable for
25 test scripts. Also, Test::Perl::Critic::Progressive is useful for
26 gradually applying coding standards to legacy code. For the ultimate
27 convenience (at the expense of some flexibility) see the criticism
30 Win32 and ActivePerl users can find PPM distributions of Perl::Critic at
31 <http://theoryx5.uwinnipeg.ca/ppms/>.
33 If you'd like to try Perl::Critic without installing anything, there is
34 a web-service available at <http://perlcritic.com>. The web-service does
35 not yet support all the configuration features that are available in the
36 native Perl::Critic API, but it should give you a good idea of what it
37 does. You can also invoke the perlcritic web-service from the
38 command-line by doing an HTTP-post, such as one of these:
40 $> POST http://perlcritic.com/perl/critic.pl < MyModule.pm
41 $> lwp-request -m POST http://perlcritic.com/perl/critic.pl < MyModule.pm
42 $> wget -q -O - --post-file=MyModule.pm http://perlcritic.com/perl/critic.pl
44 Please note that the perlcritic web-service is still alpha code. The URL
45 and interface to the service are subject to change.
48 "new( [ -profile => $FILE, -severity => $N, -theme => $string, -include
49 => \@PATTERNS, -exclude => \@PATTERNS, -top => $N, -only => $B,
50 -profile-strictness => $PROFILE_STRICTNESS_{WARN|FATAL|QUIET}, -force =>
51 $B, -verbose => $N ], -color => $B, -criticism-fatal => $B)"
52 "new( -config => Perl::Critic::Config->new() )"
54 Returns a reference to a new Perl::Critic object. Most arguments are
55 just passed directly into Perl::Critic::Config, but I have described
56 them here as well. The default value for all arguments can be
57 defined in your .perlcriticrc file. See the "CONFIGURATION" section
58 for more information about that. All arguments are optional
59 key-value pairs as follows:
61 -profile is a path to a configuration file. If $FILE is not defined,
62 Perl::Critic::Config attempts to find a .perlcriticrc configuration
63 file in the current directory, and then in your home directory.
64 Alternatively, you can set the "PERLCRITIC" environment variable to
65 point to a file in another location. If a configuration file can't
66 be found, or if $FILE is an empty string, then all Policies will be
67 loaded with their default configuration. See "CONFIGURATION" for
70 -severity is the minimum severity level. Only Policy modules that
71 have a severity greater than $N will be applied. Severity values are
72 integers ranging from 1 (least severe) to 5 (most severe). The
73 default is 5. For a given "-profile", decreasing the "-severity"
74 will usually reveal more Policy violations. You can set the default
75 value for this option in your .perlcriticrc file. Users can redefine
76 the severity level for any Policy in their .perlcriticrc file. See
77 "CONFIGURATION" for more information.
79 If it is difficult for you to remember whether severity "5" is the
80 most or least restrictive level, then you can use one of these named
83 SEVERITY NAME ...is equivalent to... SEVERITY NUMBER
84 --------------------------------------------------------
85 -severity => 'gentle' -severity => 5
86 -severity => 'stern' -severity => 4
87 -severity => 'harsh' -severity => 3
88 -severity => 'cruel' -severity => 2
89 -severity => 'brutal' -severity => 1
91 -theme is special expression that determines which Policies to apply
92 based on their respective themes. For example, the following would
93 load only Policies that have a 'bugs' AND 'pbp' theme:
95 my $critic = Perl::Critic->new( -theme => 'bugs && pbp' );
97 Unless the "-severity" option is explicitly given, setting "-theme"
98 silently causes the "-severity" to be set to 1. You can set the
99 default value for this option in your .perlcriticrc file. See the
100 "POLICY THEMES" section for more information about themes.
102 -include is a reference to a list of string @PATTERNS. Policy
103 modules that match at least one "m/$PATTERN/imx" will always be
104 loaded, irrespective of all other settings. For example:
106 my $critic = Perl::Critic->new(-include => ['layout'] -severity => 4);
108 This would cause Perl::Critic to apply all the "CodeLayout::*"
109 Policy modules even though they have a severity level that is less
110 than 4. You can set the default value for this option in your
111 .perlcriticrc file. You can also use "-include" in conjunction with
112 the "-exclude" option. Note that "-exclude" takes precedence over
113 "-include" when a Policy matches both patterns.
115 -exclude is a reference to a list of string @PATTERNS. Policy
116 modules that match at least one "m/$PATTERN/imx" will not be loaded,
117 irrespective of all other settings. For example:
119 my $critic = Perl::Critic->new(-exclude => ['strict'] -severity => 1);
121 This would cause Perl::Critic to not apply the "RequireUseStrict"
122 and "ProhibitNoStrict" Policy modules even though they have a
123 severity level that is greater than 1. You can set the default value
124 for this option in your .perlcriticrc file. You can also use
125 "-exclude" in conjunction with the "-include" option. Note that
126 "-exclude" takes precedence over "-include" when a Policy matches
129 -single-policy is a string "PATTERN". Only one policy that matches
130 "m/$PATTERN/imx" will be used. Policies that do not match will be
131 excluded. This option has precedence over the "-severity", "-theme",
132 "-include", "-exclude", and "-only" options. You can set the default
133 value for this option in your .perlcriticrc file.
135 -top is the maximum number of Violations to return when ranked by
136 their severity levels. This must be a positive integer. Violations
137 are still returned in the order that they occur within the file.
138 Unless the "-severity" option is explicitly given, setting "-top"
139 silently causes the "-severity" to be set to 1. You can set the
140 default value for this option in your .perlcriticrc file.
142 -only is a boolean value. If set to a true value, Perl::Critic will
143 only choose from Policies that are mentioned in the user's profile.
144 If set to a false value (which is the default), then Perl::Critic
145 chooses from all the Policies that it finds at your site. You can
146 set the default value for this option in your .perlcriticrc file.
148 -profile-strictness is an enumerated value, one of
149 "$PROFILE_STRICTNESS_WARN" in Perl::Critic::Utils::Constants (the
150 default), "$PROFILE_STRICTNESS_FATAL" in
151 Perl::Critic::Utils::Constants, and "$PROFILE_STRICTNESS_QUIET" in
152 Perl::Critic::Utils::Constants. If set to
153 "$PROFILE_STRICTNESS_FATAL" in Perl::Critic::Utils::Constants,
154 Perl::Critic will make certain warnings about problems found in a
155 .perlcriticrc or file specified via the -profile option fatal. For
156 example, Perl::Critic normally only "warn"s about profiles referring
157 to non-existent Policies, but this value makes this situation fatal.
158 Correspondingly, "$PROFILE_STRICTNESS_QUIET" in
159 Perl::Critic::Utils::Constants makes Perl::Critic shut up about
162 -force is a boolean value that controls whether Perl::Critic
163 observes the magical "## no critic" pseudo-pragmas in your code. If
164 set to a true value, Perl::Critic will analyze all code. If set to a
165 false value (which is the default) Perl::Critic will ignore code
166 that is tagged with these comments. See "BENDING THE RULES" for more
167 information. You can set the default value for this option in your
170 -verbose can be a positive integer (from 1 to 11), or a literal
171 format specification. See Perl::Critic::Violation for an explanation
172 of format specifications. You can set the default value for this
173 option in your .perlcriticrc file.
175 -color is not used by Perl::Critic but is provided for the benefit
178 -criticism-fatal is not used by Perl::Critic but is provided for the
179 benefit of criticism.
181 -config is a reference to a Perl::Critic::Config object. If you have
182 created your own Config object for some reason, you can pass it in
183 here instead of having Perl::Critic create one for you. Using the
184 "-config" option causes all the other options to be silently
188 "critique( $source_code )"
189 Runs the $source_code through the Perl::Critic engine using all the
190 Policies that have been loaded into this engine. If $source_code is
191 a scalar reference, then it is treated as a string of actual Perl
192 code. If $source_code is a reference to an instance of
193 PPI::Document, then that instance is used directly. Otherwise, it is
194 treated as a path to a local file containing Perl code. This method
195 returns a list of Perl::Critic::Violation objects for each violation
196 of the loaded Policies. The list is sorted in the order that the
197 Violations appear in the code. If there are no violations, this
198 method returns an empty list.
200 "add_policy( -policy => $policy_name, -params => \%param_hash )"
201 Creates a Policy object and loads it into this Critic. If the object
202 cannot be instantiated, it will throw a fatal exception. Otherwise,
203 it returns a reference to this Critic.
205 -policy is the name of a Perl::Critic::Policy subclass module. The
206 'Perl::Critic::Policy' portion of the name can be omitted for
207 brevity. This argument is required.
209 -params is an optional reference to a hash of Policy parameters. The
210 contents of this hash reference will be passed into to the
211 constructor of the Policy module. See the documentation in the
212 relevant Policy module for a description of the arguments it
216 Returns a list containing references to all the Policy objects that
217 have been loaded into this engine. Objects will be in the order that
221 Returns the Perl::Critic::Config object that was created for or
222 given to this Critic.
225 Returns the Perl::Critic::Statistics object that was created for
226 this Critic. The Statistics object accumulates data for all files
227 that are analyzed by this Critic.
230 For those folks who prefer to have a functional interface, The
231 "critique" method can be exported on request and called as a static
232 function. If the first argument is a hashref, its contents are used to
233 construct a new Perl::Critic object internally. The keys of that hash
234 should be the same as those supported by the "Perl::Critic::new" method.
235 Here are some examples:
237 use Perl::Critic qw(critique);
239 # Use default parameters...
240 @violations = critique( $some_file );
242 # Use custom parameters...
243 @violations = critique( {-severity => 2}, $some_file );
246 %> perl -MPerl::Critic=critique -e 'print critique(shift)' some_file.pm
248 None of the other object-methods are currently supported as static
252 Most of the settings for Perl::Critic and each of the Policy modules can
253 be controlled by a configuration file. The default configuration file is
254 called .perlcriticrc. Perl::Critic will look for this file in the
255 current directory first, and then in your home directory. Alternatively,
256 you can set the "PERLCRITIC" environment variable to explicitly point to
257 a different file in another location. If none of these files exist, and
258 the "-profile" option is not given to the constructor, then all the
259 modules that are found in the Perl::Critic::Policy namespace will be
260 loaded with their default configuration.
262 The format of the configuration file is a series of INI-style blocks
263 that contain key-value pairs separated by '='. Comments should start
264 with '#' and can be placed on a separate line or after the name-value
267 Default settings for Perl::Critic itself can be set before the first
268 named block. For example, putting any or all of these at the top of your
269 configuration file will set the default value for the corresponding
270 constructor argument.
272 severity = 3 #Integer or named level
273 only = 1 #Zero or One
274 force = 0 #Zero or One
275 verbose = 4 #Integer or format spec
276 top = 50 #A positive integer
277 theme = (pbp || security) && bugs #A theme expression
278 include = NamingConventions ClassHierarchies #Space-delimited list
279 exclude = Variables Modules::RequirePackage #Space-delimited list
280 criticism-fatal = 1 #Zero or One
281 color = 1 #Zero or One
283 The remainder of the configuration file is a series of blocks like this:
285 [Perl::Critic::Policy::Category::PolicyName]
289 maximum_violations_per_document = 57
293 "Perl::Critic::Policy::Category::PolicyName" is the full name of a
294 module that implements the policy. The Policy modules distributed with
295 Perl::Critic have been grouped into categories according to the table of
296 contents in Damian Conway's book Perl Best Practices. For brevity, you
297 can omit the 'Perl::Critic::Policy' part of the module name.
299 "severity" is the level of importance you wish to assign to the Policy.
300 All Policy modules are defined with a default severity value ranging
301 from 1 (least severe) to 5 (most severe). However, you may disagree with
302 the default severity and choose to give it a higher or lower severity,
303 based on your own coding philosophy. You can set the "severity" to an
304 integer from 1 to 5, or use one of the equivalent names:
306 SEVERITY NAME ...is equivalent to... SEVERITY NUMBER
307 ----------------------------------------------------
314 "set_themes" sets the theme for the Policy and overrides its default
315 theme. The argument is a string of one or more whitespace-delimited
316 alphanumeric words. Themes are case-insensitive. See "POLICY THEMES" for
319 "add_themes" appends to the default themes for this Policy. The argument
320 is a string of one or more whitespace-delimited words. Themes are
321 case-insensitive. See "POLICY THEMES" for more information.
323 "maximum_violations_per_document" limits the number of Violations the
324 Policy will return for a given document. Some Policies have a default
325 limit; see the documentation for the individual Policies to see whether
326 there is one. To force a Policy to not have a limit, specify "no_limit"
327 or the empty string for the value of this parameter.
329 The remaining key-value pairs are configuration parameters that will be
330 passed into the constructor for that Policy. The constructors for most
331 Policy objects do not support arguments, and those that do should have
332 reasonable defaults. See the documentation on the appropriate Policy
333 module for more details.
335 Instead of redefining the severity for a given Policy, you can
336 completely disable a Policy by prepending a '-' to the name of the
337 module in your configuration file. In this manner, the Policy will never
338 be loaded, regardless of the "-severity" given to the Perl::Critic
341 A simple configuration might look like this:
343 #--------------------------------------------------------------
344 # I think these are really important, so always load them
346 [TestingAndDebugging::RequireUseStrict]
349 [TestingAndDebugging::RequireUseWarnings]
352 #--------------------------------------------------------------
353 # I think these are less important, so only load when asked
355 [Variables::ProhibitPackageVars]
358 [ControlStructures::ProhibitPostfixControls]
359 allow = if unless # My custom configuration
360 severity = cruel # Same as "severity = 2"
362 #--------------------------------------------------------------
363 # Give these policies a custom theme. I can activate just
364 # these policies by saying `perlcritic -theme larry`
366 [Modules::RequireFilenameMatchesPackage]
369 [TestingAndDebugging::RequireTestLables]
370 add_themes = larry curly moe
372 #--------------------------------------------------------------
373 # I do not agree with these at all, so never load them
375 [-NamingConventions::ProhibitMixedCaseVars]
376 [-NamingConventions::ProhibitMixedCaseSubs]
378 #--------------------------------------------------------------
379 # For all other Policies, I accept the default severity,
380 # so no additional configuration is required for them.
382 For additional configuration examples, see the perlcriticrc file that is
383 included in this examples directory of this distribution.
385 Damian Conway's own Perl::Critic configuration is also included in this
386 distribution as examples/perlcriticrc-conway.
389 A large number of Policy modules are distributed with Perl::Critic. They
390 are described briefly in the companion document
391 Perl::Critic::PolicySummary and in more detail in the individual modules
392 themselves. Say ""perlcritic -doc PATTERN"" to see the perldoc for all
393 Policy modules that match the regex "m/PATTERN/imx"
395 There are a number of distributions of additional policies on CPAN. If
396 Perl::Critic doesn't contain a policy that you want, some one may have
397 already written it. See the "SEE ALSO" section below for a list of some
398 of these distributions.
401 Each Policy is defined with one or more "themes". Themes can be used to
402 create arbitrary groups of Policies. They are intended to provide an
403 alternative mechanism for selecting your preferred set of Policies. For
404 example, you may wish disable a certain subset of Policies when
405 analyzing test scripts. Conversely, you may wish to enable only a
406 specific subset of Policies when analyzing modules.
408 The Policies that ship with Perl::Critic are have been broken into the
409 following themes. This is just our attempt to provide some basic logical
410 groupings. You are free to invent new themes that suit your needs.
413 --------------------------------------------------------------------------
414 core All policies that ship with Perl::Critic
415 pbp Policies that come directly from "Perl Best Practices"
416 bugs Policies that that prevent or reveal bugs
417 maintenance Policies that affect the long-term health of the code
418 cosmetic Policies that only have a superficial effect
419 complexity Policies that specificaly relate to code complexity
420 security Policies that relate to security issues
421 tests Policies that are specific to test scripts
423 Any Policy may fit into multiple themes. Say "perlcritic -list" to get a
424 listing of all available Policies and the themes that are associated
425 with each one. You can also change the theme for any Policy in your
426 .perlcriticrc file. See the "CONFIGURATION" section for more information
429 Using the "-theme" option, you can create an arbitrarily complex rule
430 that determines which Policies will be loaded. Precedence is the same as
431 regular Perl code, and you can use parentheses to enforce precedence as
432 well. Supported operators are:
434 Operator Altertative Example
435 ----------------------------------------------------------------------------
437 || or 'pbp || (bugs && security)'
438 ! not 'pbp && ! (portability || complexity)'
440 Theme names are case-insensitive. If the "-theme" is set to an empty
441 string, then it evaluates as true all Policies.
444 Perl::Critic takes a hard-line approach to your code: either you comply
445 or you don't. In the real world, it is not always practical (nor even
446 possible) to fully comply with coding standards. In such cases, it is
447 wise to show that you are knowingly violating the standards and that you
448 have a Damn Good Reason (DGR) for doing so.
450 To help with those situations, you can direct Perl::Critic to ignore
451 certain lines or blocks of code by using pseudo-pragmas:
453 require 'LegacyLibaray1.pl'; ## no critic
454 require 'LegacyLibrary2.pl'; ## no critic
456 for my $element (@list) {
460 $foo = ""; #Violates 'ProhibitEmptyQuotes'
461 $barf = bar() if $foo; #Violates 'ProhibitPostfixControls'
462 #Some more evil code...
470 The "## no critic" comments direct Perl::Critic to ignore the remaining
471 lines of code until the end of the current block, or until a ""## use
472 critic"" comment is found (whichever comes first). If the "## no critic"
473 comment is on the same line as a code statement, then only that line of
474 code is overlooked. To direct perlcritic to ignore the "## no critic"
475 comments, use the "-force" option.
477 A bare "## no critic" comment disables all the active Policies. If you
478 wish to disable only specific Policies, add a list of Policy names as
479 arguments, just as you would for the "no strict" or "no warnings"
480 pragmas. For example, this would disable the "ProhibitEmptyQuotes" and
481 "ProhibitPostfixControls" policies until the end of the block or until
482 the next "## use critic" comment (whichever comes first):
484 ## no critic (EmptyQuotes, PostfixControls)
486 # Now exempt from ValuesAndExpressions::ProhibitEmptyQuotes
489 # Now exempt ControlStructures::ProhibitPostfixControls
490 $barf = bar() if $foo;
492 # Still subjected to ValuesAndExpression::RequireNumberSeparators
493 $long_int = 10000000000;
495 Since the Policy names are matched against the "## no critic" arguments
496 as regular expressions, you can abbreviate the Policy names or disable
497 an entire family of Policies in one shot like this:
499 ## no critic (NamingConventions)
501 # Now exempt from NamingConventions::ProhibitMixedCaseVars
502 my $camelHumpVar = 'foo';
504 # Now exempt from NamingConventions::ProhibitMixedCaseSubs
507 The argument list must be enclosed in parentheses and must contain one
508 or more comma-separated barewords (e.g. don't use quotes). The "## no
509 critic" pragmas can be nested, and Policies named by an inner pragma
510 will be disabled along with those already disabled an outer pragma.
512 Some Policies like "Subroutines::ProhibitExcessComplexity" apply to an
513 entire block of code. In those cases, "## no critic" must appear on the
514 line where the violation is reported. For example:
516 sub complicated_function { ## no critic (ProhibitExcessComplexity)
520 Policies such as "Documentation::RequirePodSections" apply to the entire
521 document, in which case violations are reported at line 1. But if the
522 file requires a shebang line, it is impossible to put "## no critic" on
523 the first line of the file. This is a known limitation and it will be
524 addressed in a future release. As a workaround, you can disable the
525 affected policies at the command-line or in your .perlcriticrc file. But
526 beware that this will affect the analysis of all files.
528 Use this feature wisely. "## no critic" should be used in the smallest
529 possible scope, or only on individual lines of code. And you should
530 always be as specific as possible about which policies you want to
531 disable (i.e. never use a bare "## no critic"). If Perl::Critic
532 complains about your code, try and find a compliant solution before
533 resorting to this feature.
535 THE Perl::Critic PHILOSOPHY
536 Coding standards are deeply personal and highly subjective. The goal of
537 Perl::Critic is to help you write code that conforms with a set of best
538 practices. Our primary goal is not to dictate what those practices are,
539 but rather, to implement the practices discovered by others. Ultimately,
540 you make the rules -- Perl::Critic is merely a tool for encouraging
541 consistency. If there is a policy that you think is important or that we
542 have overlooked, we would be very grateful for contributions, or you can
543 simply load your own private set of policies into Perl::Critic.
546 The modular design of Perl::Critic is intended to facilitate the
547 addition of new Policies. You'll need to have some understanding of PPI,
548 but most Policy modules are pretty straightforward and only require
549 about 20 lines of code. Please see the Perl::Critic::DEVELOPER file
550 included in this distribution for a step-by-step demonstration of how to
551 create new Policy modules.
553 If you develop any new Policy modules, feel free to send them to
554 "<thaljef@cpan.org>" and I'll be happy to put them into the Perl::Critic
555 distribution. Or if you would like to work on the Perl::Critic project
556 directly, check out our repository at <http://perlcritic.tigris.org>. To
557 subscribe to our mailing list, send a message to
558 "<dev-subscribe@perlcritic.tigris.org>".
560 The Perl::Critic team is also available for hire. If your organization
561 has its own coding standards, we can create custom Policies to enforce
562 your local guidelines. Or if your code base is prone to a particular
563 defect pattern, we can design Policies that will help you catch those
564 costly defects before they go into production. To discuss your needs
565 with the Perl::Critic team, just contact "<thaljef@cpan.org>".
568 Perl::Critic requires the following modules:
602 The following modules are optional, but recommended for complete
623 CONTACTING THE DEVELOPMENT TEAM
624 You are encouraged to subscribe to the mailing list; send a message to
625 "<users-subscribe@perlcritic.tigris.org>". See also the archives. You
626 can also contact the author at "<thaljef@cpan.org>".
628 At least one member of the development team has started hanging around
629 in <irc://irc.perl.org/#perlcritic>.
632 There are a number of distributions of additional Policies available. A
641 Perl::Critic::StricterSubs
647 These distributions enable you to use Perl::Critic in your unit tests:
651 Test::Perl::Critic::Progressive
653 There are also a couple of distributions that will install all the
654 Perl::Critic related modules known to the development team:
660 If you want to make sure you have absolutely everything, you can use
663 Bundle::Perl::Critic::IncludingOptionalDependencies
665 Task::Perl::Critic::IncludingOptionalDependencies
668 Scrutinizing Perl code is hard for humans, let alone machines. If you
669 find any bugs, particularly false-positives or false-negatives from a
670 Perl::Critic::Policy, please submit them to
671 <http://rt.cpan.org/NoAuth/Bugs.html?Dist=Perl-Critic>. Thanks.
673 Most policies will produce false-negatives if they cannot understand a
674 particular block of code.
677 Adam Kennedy - For creating PPI, the heart and soul of Perl::Critic.
679 Damian Conway - For writing Perl Best Practices, finally :)
681 Chris Dolan - For contributing the best features and Policy modules.
683 Andy Lester - Wise sage and master of all-things-testing.
685 Elliot Shank - The self-proclaimed quality freak.
687 Giuseppe Maxia - For all the great ideas and positive encouragement.
689 and Sharon, my wife - For putting up with my all-night code sessions.
691 Thanks also to the Perl Foundation for providing a grant to support
692 Chris Dolan's project to implement twenty PBP policies.
693 <http://www.perlfoundation.org/april_1_2007_new_grant_awards>
696 Jeffrey Ryan Thalhammer <thaljef@cpan.org>
699 Copyright (c) 2005-2008 Jeffrey Ryan Thalhammer. All rights reserved.
701 This program is free software; you can redistribute it and/or modify it
702 under the same terms as Perl itself. The full text of this license can
703 be found in the LICENSE file included with this module.