1 ##############################################################################
2 # $URL: http://perlcritic.tigris.org/svn/perlcritic/trunk/Perl-Critic/lib/Perl/Critic.pm $
3 # $Date: 2008-07-03 10:19:10 -0500 (Thu, 03 Jul 2008) $
6 ##############################################################################
14 use English qw(-no_match_vars);
17 use base qw(Exporter);
20 use Scalar::Util qw(blessed);
23 use PPI::Document::File;
25 use Perl::Critic::Exception::Configuration::Generic;
26 use Perl::Critic::Exception::Parse qw{ throw_parse };
27 use Perl::Critic::Config;
28 use Perl::Critic::Violation;
29 use Perl::Critic::Document;
30 use Perl::Critic::Statistics;
31 use Perl::Critic::Utils qw{ :characters };
33 #-----------------------------------------------------------------------------
35 our $VERSION = '1.088';
37 Readonly::Array our @EXPORT_OK => qw(critique);
39 #-----------------------------------------------------------------------------
42 my ( $class, %args ) = @_;
43 my $self = bless {}, $class;
44 $self->{_config} = $args{-config} || Perl::Critic::Config->new( %args );
45 $self->{_stats} = Perl::Critic::Statistics->new();
49 #-----------------------------------------------------------------------------
53 return $self->{_config};
56 #-----------------------------------------------------------------------------
59 my ( $self, @args ) = @_;
60 #Delegate to Perl::Critic::Config
61 return $self->config()->add_policy( @args );
64 #-----------------------------------------------------------------------------
69 #Delegate to Perl::Critic::Config
70 return $self->config()->policies();
73 #-----------------------------------------------------------------------------
77 return $self->{_stats};
80 #-----------------------------------------------------------------------------
82 sub critique { ##no critic (ArgUnpacking)
84 #-------------------------------------------------------------------
85 # This subroutine can be called as an object method or as a static
86 # function. In the latter case, the first argument can be a
87 # hashref of configuration parameters that shall be used to create
88 # an object behind the scenes. Note that this object does not
89 # persist. In other words, it is not a singleton. Here are some
90 # of the ways this subroutine might get called:
93 # $critic->critique( $code );
95 # #Functional style...
97 # critique( {}, $code );
98 # critique( {-foo => bar}, $code );
99 #------------------------------------------------------------------
101 my ( $self, $source_code ) = @_ >= 2 ? @_ : ( {}, $_[0] );
102 $self = ref $self eq 'HASH' ? __PACKAGE__->new(%{ $self }) : $self;
103 return if not defined $source_code; # If no code, then nothing to do.
105 my $doc = $self->_create_perl_critic_document($source_code);
107 if ( 0 == $self->policies() ) {
108 Perl::Critic::Exception::Configuration::Generic->throw(
109 message => 'There are no enabled policies.',
113 return $self->_gather_violations($doc);
116 #=============================================================================
119 sub _create_perl_critic_document {
120 my ($self, $source_code) = @_;
122 # $source_code can be a file name, or a reference to a
123 # PPI::Document, or a reference to a scalar containing source
124 # code. In the last case, PPI handles the translation for us.
126 my $doc = _is_ppi_doc( $source_code ) ? $source_code
127 : ref $source_code ? PPI::Document->new($source_code)
128 : PPI::Document::File->new($source_code);
131 if ( not defined $doc ) {
132 my $errstr = PPI::Document::errstr();
133 my $file = ref $source_code ? undef : $source_code;
135 message => qq<Can't parse code: $errstr>,
139 # Pre-index location of each node (for speed)
140 $doc->index_locations();
142 # Wrap the doc in a caching layer
143 return Perl::Critic::Document->new($doc);
146 #-----------------------------------------------------------------------------
148 sub _gather_violations {
149 my ($self, $doc) = @_;
151 # Disable the magic shebang fix
152 my %is_line_disabled = _unfix_shebang($doc);
154 # Filter exempt code, if desired
155 if ( not $self->config->force() ) {
156 my @site_policies = $self->config->site_policy_names();
157 %is_line_disabled = ( %is_line_disabled,
158 _filter_code($doc, @site_policies) );
161 # Evaluate each policy
162 my @policies = $self->config->policies();
164 map { _critique( $_, $doc, \%is_line_disabled) } @policies;
166 # Accumulate statistics
167 $self->statistics->accumulate( $doc, \@violations );
169 # If requested, rank violations by their severity and return the top N.
170 if ( @violations && (my $top = $self->config->top()) ) {
171 my $limit = @violations < $top ? $#violations : $top-1;
172 @violations = Perl::Critic::Violation::sort_by_severity(@violations);
173 @violations = ( reverse @violations )[ 0 .. $limit ]; #Slicing...
176 # Always return violations sorted by location
177 return Perl::Critic::Violation->sort_by_location(@violations);
180 #-----------------------------------------------------------------------------
184 return blessed($ref) && $ref->isa('PPI::Document');
187 #-----------------------------------------------------------------------------
191 my ($policy, $doc, $is_line_disabled) = @_;
193 my $maximum_violations = $policy->get_maximum_violations_per_document();
195 if (defined $maximum_violations && $maximum_violations == 0) {
199 my $policy_name = $policy->get_long_name();
202 for my $type ( $policy->applies_to() ) {
205 for my $element ( @{ $doc->find($type) || [] } ) {
207 # Evaluate the policy on this $element. A policy may
208 # return zero or more violations. We only want the
209 # violations that occur on lines that have not been
213 for my $violation ( $policy->violates( $element, $doc ) ) {
214 my $line = $violation->location()->[0];
215 if (exists $is_line_disabled->{$line}) {
216 next VIOLATION if $is_line_disabled->{$line}->{$policy_name};
217 next VIOLATION if $is_line_disabled->{$line}->{ALL};
220 push @violations, $violation;
222 defined $maximum_violations
223 and @violations >= $maximum_violations
234 #-----------------------------------------------------------------------------
238 my ($doc, @site_policies)= @_;
240 my $nodes_ref = $doc->find('PPI::Token::Comment') || return;
243 _filter_shebang_line($nodes_ref, \%disabled_lines, \@site_policies);
244 _filter_other_lines($nodes_ref, \%disabled_lines, \@site_policies);
245 return %disabled_lines;
248 sub _filter_shebang_line {
249 my ($nodes_ref, $disabled_lines, $site_policies) = @_;
251 my $shebang_no_critic = qr{\A [#]! .*? [#][#] \s* no \s+ critic}mx;
253 # Special case for the very beginning of the file: allow "##no critic" after the shebang
254 if (0 < @{$nodes_ref}) {
255 my $loc = $nodes_ref->[0]->location;
256 if (1 == $loc->[0] && 1 == $loc->[1] && $nodes_ref->[0] =~ $shebang_no_critic) {
257 my $pragma = shift @{$nodes_ref};
258 for my $policy (_parse_nocritic_import($pragma, $site_policies)) {
259 $disabled_lines->{ 1 }->{$policy} = 1;
266 sub _filter_other_lines {
267 my ($nodes_ref, $disabled_lines, $site_policies) = @_;
269 my $no_critic = qr{\A \s* [#][#] \s* no \s+ critic}mx;
270 my $use_critic = qr{\A \s* [#][#] \s* use \s+ critic}mx;
273 for my $pragma ( grep { $_ =~ $no_critic } @{$nodes_ref} ) {
275 # Parse out the list of Policy names after the
276 # 'no critic' pragma. I'm thinking of this just
277 # like a an C<import> argument for real pragmas.
278 my @no_policies = _parse_nocritic_import($pragma, $site_policies);
280 # Grab surrounding nodes to determine the context.
281 # This determines whether the pragma applies to
282 # the current line or the block that follows.
283 my $parent = $pragma->parent();
284 my $grandparent = $parent ? $parent->parent() : undef;
285 my $sib = $pragma->sprevious_sibling();
288 # Handle single-line usage on simple statements
289 if ( $sib && $sib->location->[0] == $pragma->location->[0] ) {
290 my $line = $pragma->location->[0];
291 for my $policy ( @no_policies ) {
292 $disabled_lines->{ $line }->{$policy} = 1;
298 # Handle single-line usage on compound statements
299 if ( ref $parent eq 'PPI::Structure::Block' ) {
300 if ( ref $grandparent eq 'PPI::Statement::Compound'
301 || ref $grandparent eq 'PPI::Statement::Sub' ) {
302 if ( $parent->location->[0] == $pragma->location->[0] ) {
303 my $line = $grandparent->location->[0];
304 for my $policy ( @no_policies ) {
305 $disabled_lines->{ $line }->{$policy} = 1;
313 # Handle multi-line usage. This is either a "no critic" ..
314 # "use critic" region or a block where "no critic" persists
315 # until the end of the scope. The start is the always the "no
316 # critic" which we already found. So now we have to search
323 while ( my $sib = $end->next_sibling() ) {
324 $end = $sib; # keep track of last sibling encountered in this scope
326 if $sib->isa('PPI::Token::Comment') && $sib =~ $use_critic;
329 # We either found an end or hit the end of the scope.
330 # Flag all intervening lines
331 for my $line ( $start->location->[0] .. $end->location->[0] ) {
332 for my $policy ( @no_policies ) {
333 $disabled_lines->{ $line }->{$policy} = 1;
341 #-----------------------------------------------------------------------------
343 sub _parse_nocritic_import {
345 my ($pragma, $site_policies) = @_;
347 my $module = qr{ [\w:]+ }mx;
348 my $delim = qr{ \s* [,\s] \s* }mx;
349 my $qw = qr{ (?: qw )? }mx;
350 my $qualifier = qr{ $qw [(]? \s* ( $module (?: $delim $module)* ) \s* [)]? }mx;
351 my $no_critic = qr{ \#\# \s* no \s+ critic \s* $qualifier }mx; ##no critic(EscapedMetacharacters)
353 if ( my ($module_list) = $pragma =~ $no_critic ) {
354 my @modules = split $delim, $module_list;
356 # Compose the specified modules into a regex alternation. Wrap each
357 # in a no-capturing group to permit "|" in the modules specification
358 # (backward compatibility)
359 my $re = join q{|}, map {"(?:$_)"} @modules;
360 return grep {m/$re/imx} @{$site_policies};
363 # Default to disabling ALL policies.
367 #-----------------------------------------------------------------------------
370 # When you install a script using ExtUtils::MakeMaker or Module::Build, it
371 # inserts some magical code into the top of the file (just after the
372 # shebang). This code allows people to call your script using a shell,
373 # like `sh my_script`. Unfortunately, this code causes several Policy
374 # violations, so we just disable it as if a "## no critic" comment had
378 my $first_stmnt = $doc->schild(0) || return;
380 # Different versions of MakeMaker and Build use slightly differnt shebang
381 # fixing strings. This matches most of the ones I've found in my own Perl
382 # distribution, but it may not be bullet-proof.
384 my $fixin_rx = qr{^eval 'exec .* \$0 \${1\+"\$@"}'\s*[\r\n]\s*if.+;}m; ##no critic(RequireExtendedFormatting)
385 if ( $first_stmnt =~ $fixin_rx ) {
386 my $line = $first_stmnt->location()->[0];
387 return ( $line => {ALL => 1}, $line + 1 => {ALL => 1} );
390 #No magic shebang was found!
394 #-----------------------------------------------------------------------------
398 #-----------------------------------------------------------------------------
404 =for stopwords DGR INI-style API -params pbp refactored ActivePerl
409 Perl::Critic - Critique Perl source code for best-practices.
416 my $critic = Perl::Critic->new();
417 my @violations = $critic->critique($file);
423 Perl::Critic is an extensible framework for creating and applying coding
424 standards to Perl source code. Essentially, it is a static source code
425 analysis engine. Perl::Critic is distributed with a number of
426 L<Perl::Critic::Policy> modules that attempt to enforce various coding
427 guidelines. Most Policy modules are based on Damian Conway's book B<Perl Best
428 Practices>. However, Perl::Critic is B<not> limited to PBP and will even
429 support Policies that contradict Conway. You can enable, disable, and
430 customize those Polices through the Perl::Critic interface. You can also
431 create new Policy modules that suit your own tastes.
433 For a command-line interface to Perl::Critic, see the documentation for
434 L<perlcritic>. If you want to integrate Perl::Critic with your build process,
435 L<Test::Perl::Critic> provides an interface that is suitable for test scripts.
436 Also, L<Test::Perl::Critic::Progressive> is useful for gradually applying
437 coding standards to legacy code. For the ultimate convenience (at the expense
438 of some flexibility) see the L<criticism> pragma.
440 Win32 and ActivePerl users can find PPM distributions of Perl::Critic at
441 L<http://theoryx5.uwinnipeg.ca/ppms/>.
443 If you'd like to try L<Perl::Critic> without installing anything, there is a
444 web-service available at L<http://perlcritic.com>. The web-service does not
445 yet support all the configuration features that are available in the native
446 Perl::Critic API, but it should give you a good idea of what it does. You can
447 also invoke the perlcritic web-service from the command-line by doing an
448 HTTP-post, such as one of these:
450 $> POST http://perlcritic.com/perl/critic.pl < MyModule.pm
451 $> lwp-request -m POST http://perlcritic.com/perl/critic.pl < MyModule.pm
452 $> wget -q -O - --post-file=MyModule.pm http://perlcritic.com/perl/critic.pl
454 Please note that the perlcritic web-service is still alpha code. The URL and
455 interface to the service are subject to change.
462 =item C<< new( [ -profile => $FILE, -severity => $N, -theme => $string, -include => \@PATTERNS, -exclude => \@PATTERNS, -top => $N, -only => $B, -profile-strictness => $PROFILE_STRICTNESS_{WARN|FATAL|QUIET}, -force => $B, -verbose => $N ], -color => $B, -criticism-fatal => $B) >>
464 =item C<< new( -config => Perl::Critic::Config->new() ) >>
468 Returns a reference to a new Perl::Critic object. Most arguments are just
469 passed directly into L<Perl::Critic::Config>, but I have described them here
470 as well. The default value for all arguments can be defined in your
471 F<.perlcriticrc> file. See the L<"CONFIGURATION"> section for more
472 information about that. All arguments are optional key-value pairs as
475 B<-profile> is a path to a configuration file. If C<$FILE> is not defined,
476 Perl::Critic::Config attempts to find a F<.perlcriticrc> configuration file in
477 the current directory, and then in your home directory. Alternatively, you
478 can set the C<PERLCRITIC> environment variable to point to a file in another
479 location. If a configuration file can't be found, or if C<$FILE> is an empty
480 string, then all Policies will be loaded with their default configuration.
481 See L<"CONFIGURATION"> for more information.
483 B<-severity> is the minimum severity level. Only Policy modules that have a
484 severity greater than C<$N> will be applied. Severity values are integers
485 ranging from 1 (least severe) to 5 (most severe). The default is 5. For a
486 given C<-profile>, decreasing the C<-severity> will usually reveal more Policy
487 violations. You can set the default value for this option in your
488 F<.perlcriticrc> file. Users can redefine the severity level for any Policy
489 in their F<.perlcriticrc> file. See L<"CONFIGURATION"> for more information.
491 If it is difficult for you to remember whether severity "5" is the most or
492 least restrictive level, then you can use one of these named values:
494 SEVERITY NAME ...is equivalent to... SEVERITY NUMBER
495 --------------------------------------------------------
496 -severity => 'gentle' -severity => 5
497 -severity => 'stern' -severity => 4
498 -severity => 'harsh' -severity => 3
499 -severity => 'cruel' -severity => 2
500 -severity => 'brutal' -severity => 1
502 B<-theme> is special expression that determines which Policies to apply based
503 on their respective themes. For example, the following would load only
504 Policies that have a 'bugs' AND 'pbp' theme:
506 my $critic = Perl::Critic->new( -theme => 'bugs && pbp' );
508 Unless the C<-severity> option is explicitly given, setting C<-theme> silently
509 causes the C<-severity> to be set to 1. You can set the default value for
510 this option in your F<.perlcriticrc> file. See the L<"POLICY THEMES"> section
511 for more information about themes.
514 B<-include> is a reference to a list of string C<@PATTERNS>. Policy modules
515 that match at least one C<m/$PATTERN/imx> will always be loaded, irrespective
516 of all other settings. For example:
518 my $critic = Perl::Critic->new(-include => ['layout'] -severity => 4);
520 This would cause Perl::Critic to apply all the C<CodeLayout::*> Policy modules
521 even though they have a severity level that is less than 4. You can set the
522 default value for this option in your F<.perlcriticrc> file. You can also use
523 C<-include> in conjunction with the C<-exclude> option. Note that C<-exclude>
524 takes precedence over C<-include> when a Policy matches both patterns.
526 B<-exclude> is a reference to a list of string C<@PATTERNS>. Policy modules
527 that match at least one C<m/$PATTERN/imx> will not be loaded, irrespective of
528 all other settings. For example:
530 my $critic = Perl::Critic->new(-exclude => ['strict'] -severity => 1);
532 This would cause Perl::Critic to not apply the C<RequireUseStrict> and
533 C<ProhibitNoStrict> Policy modules even though they have a severity level that
534 is greater than 1. You can set the default value for this option in your
535 F<.perlcriticrc> file. You can also use C<-exclude> in conjunction with the
536 C<-include> option. Note that C<-exclude> takes precedence over C<-include>
537 when a Policy matches both patterns.
539 B<-single-policy> is a string C<PATTERN>. Only one policy that matches
540 C<m/$PATTERN/imx> will be used. Policies that do not match will be excluded.
541 This option has precedence over the C<-severity>, C<-theme>, C<-include>,
542 C<-exclude>, and C<-only> options. You can set the default value for this
543 option in your F<.perlcriticrc> file.
545 B<-top> is the maximum number of Violations to return when ranked by their
546 severity levels. This must be a positive integer. Violations are still
547 returned in the order that they occur within the file. Unless the
548 C<-severity> option is explicitly given, setting C<-top> silently causes the
549 C<-severity> to be set to 1. You can set the default value for this option in
550 your F<.perlcriticrc> file.
552 B<-only> is a boolean value. If set to a true value, Perl::Critic will only
553 choose from Policies that are mentioned in the user's profile. If set to a
554 false value (which is the default), then Perl::Critic chooses from all the
555 Policies that it finds at your site. You can set the default value for this
556 option in your F<.perlcriticrc> file.
558 B<-profile-strictness> is an enumerated value, one of
559 L<Perl::Critic::Utils::Constants/"$PROFILE_STRICTNESS_WARN"> (the
561 L<Perl::Critic::Utils::Constants/"$PROFILE_STRICTNESS_FATAL">, and
562 L<Perl::Critic::Utils::Constants/"$PROFILE_STRICTNESS_QUIET">. If set
563 to L<Perl::Critic::Utils::Constants/"$PROFILE_STRICTNESS_FATAL">,
564 Perl::Critic will make certain warnings about problems found in a
565 F<.perlcriticrc> or file specified via the B<-profile> option fatal.
566 For example, Perl::Critic normally only C<warn>s about profiles
567 referring to non-existent Policies, but this value makes this
568 situation fatal. Correspondingly,
569 L<Perl::Critic::Utils::Constants/"$PROFILE_STRICTNESS_QUIET"> makes
570 Perl::Critic shut up about these things.
572 B<-force> is a boolean value that controls whether Perl::Critic observes the
573 magical C<"## no critic"> pseudo-pragmas in your code. If set to a true
574 value, Perl::Critic will analyze all code. If set to a false value (which is
575 the default) Perl::Critic will ignore code that is tagged with these comments.
576 See L<"BENDING THE RULES"> for more information. You can set the default
577 value for this option in your F<.perlcriticrc> file.
579 B<-verbose> can be a positive integer (from 1 to 11), or a literal format
580 specification. See L<Perl::Critic::Violation> for an explanation of format
581 specifications. You can set the default value for this option in your
582 F<.perlcriticrc> file.
584 B<-color> is not used by Perl::Critic but is provided for the benefit of
587 B<-criticism-fatal> is not used by Perl::Critic but is provided for the
588 benefit of L<criticism>.
590 B<-config> is a reference to a L<Perl::Critic::Config> object. If you have
591 created your own Config object for some reason, you can pass it in here
592 instead of having Perl::Critic create one for you. Using the C<-config>
593 option causes all the other options to be silently ignored.
602 =item C<critique( $source_code )>
604 Runs the C<$source_code> through the Perl::Critic engine using all the
605 Policies that have been loaded into this engine. If C<$source_code> is a
606 scalar reference, then it is treated as a string of actual Perl code. If
607 C<$source_code> is a reference to an instance of L<PPI::Document>, then that
608 instance is used directly. Otherwise, it is treated as a path to a local file
609 containing Perl code. This method returns a list of
610 L<Perl::Critic::Violation> objects for each violation of the loaded Policies.
611 The list is sorted in the order that the Violations appear in the code. If
612 there are no violations, this method returns an empty list.
614 =item C<< add_policy( -policy => $policy_name, -params => \%param_hash ) >>
616 Creates a Policy object and loads it into this Critic. If the object cannot
617 be instantiated, it will throw a fatal exception. Otherwise, it returns a
618 reference to this Critic.
620 B<-policy> is the name of a L<Perl::Critic::Policy> subclass module. The
621 C<'Perl::Critic::Policy'> portion of the name can be omitted for brevity.
622 This argument is required.
624 B<-params> is an optional reference to a hash of Policy parameters. The
625 contents of this hash reference will be passed into to the constructor of the
626 Policy module. See the documentation in the relevant Policy module for a
627 description of the arguments it supports.
629 =item C< policies() >
631 Returns a list containing references to all the Policy objects that have been
632 loaded into this engine. Objects will be in the order that they were loaded.
636 Returns the L<Perl::Critic::Config> object that was created for or given
639 =item C< statistics() >
641 Returns the L<Perl::Critic::Statistics> object that was created for this
642 Critic. The Statistics object accumulates data for all files that are
643 analyzed by this Critic.
648 =head1 FUNCTIONAL INTERFACE
650 For those folks who prefer to have a functional interface, The C<critique>
651 method can be exported on request and called as a static function. If the
652 first argument is a hashref, its contents are used to construct a new
653 Perl::Critic object internally. The keys of that hash should be the same as
654 those supported by the C<Perl::Critic::new> method. Here are some examples:
656 use Perl::Critic qw(critique);
658 # Use default parameters...
659 @violations = critique( $some_file );
661 # Use custom parameters...
662 @violations = critique( {-severity => 2}, $some_file );
665 %> perl -MPerl::Critic=critique -e 'print critique(shift)' some_file.pm
667 None of the other object-methods are currently supported as static
673 Most of the settings for Perl::Critic and each of the Policy modules can be
674 controlled by a configuration file. The default configuration file is called
675 F<.perlcriticrc>. Perl::Critic will look for this file in the current
676 directory first, and then in your home directory. Alternatively, you can set
677 the C<PERLCRITIC> environment variable to explicitly point to a different file
678 in another location. If none of these files exist, and the C<-profile> option
679 is not given to the constructor, then all the modules that are found in the
680 Perl::Critic::Policy namespace will be loaded with their default
683 The format of the configuration file is a series of INI-style blocks that
684 contain key-value pairs separated by '='. Comments should start with '#' and
685 can be placed on a separate line or after the name-value pairs if you desire.
687 Default settings for Perl::Critic itself can be set B<before the first named
688 block.> For example, putting any or all of these at the top of your
689 configuration file will set the default value for the corresponding
690 constructor argument.
692 severity = 3 #Integer or named level
693 only = 1 #Zero or One
694 force = 0 #Zero or One
695 verbose = 4 #Integer or format spec
696 top = 50 #A positive integer
697 theme = (pbp || security) && bugs #A theme expression
698 include = NamingConventions ClassHierarchies #Space-delimited list
699 exclude = Variables Modules::RequirePackage #Space-delimited list
700 criticism-fatal = 1 #Zero or One
701 color = 1 #Zero or One
703 The remainder of the configuration file is a series of blocks like this:
705 [Perl::Critic::Policy::Category::PolicyName]
709 maximum_violations_per_document = 57
713 C<Perl::Critic::Policy::Category::PolicyName> is the full name of a module
714 that implements the policy. The Policy modules distributed with Perl::Critic
715 have been grouped into categories according to the table of contents in Damian
716 Conway's book B<Perl Best Practices>. For brevity, you can omit the
717 C<'Perl::Critic::Policy'> part of the module name.
719 C<severity> is the level of importance you wish to assign to the Policy. All
720 Policy modules are defined with a default severity value ranging from 1 (least
721 severe) to 5 (most severe). However, you may disagree with the default
722 severity and choose to give it a higher or lower severity, based on your own
723 coding philosophy. You can set the C<severity> to an integer from 1 to 5, or
724 use one of the equivalent names:
726 SEVERITY NAME ...is equivalent to... SEVERITY NUMBER
727 ----------------------------------------------------
734 C<set_themes> sets the theme for the Policy and overrides its default theme.
735 The argument is a string of one or more whitespace-delimited alphanumeric
736 words. Themes are case-insensitive. See L<"POLICY THEMES"> for more
739 C<add_themes> appends to the default themes for this Policy. The argument is
740 a string of one or more whitespace-delimited words. Themes are
741 case-insensitive. See L<"POLICY THEMES"> for more information.
743 C<maximum_violations_per_document> limits the number of Violations the Policy
744 will return for a given document. Some Policies have a default limit; see the
745 documentation for the individual Policies to see whether there is one. To
746 force a Policy to not have a limit, specify "no_limit" or the empty string for
747 the value of this parameter.
749 The remaining key-value pairs are configuration parameters that will be passed
750 into the constructor for that Policy. The constructors for most Policy
751 objects do not support arguments, and those that do should have reasonable
752 defaults. See the documentation on the appropriate Policy module for more
755 Instead of redefining the severity for a given Policy, you can completely
756 disable a Policy by prepending a '-' to the name of the module in your
757 configuration file. In this manner, the Policy will never be loaded,
758 regardless of the C<-severity> given to the Perl::Critic constructor.
760 A simple configuration might look like this:
762 #--------------------------------------------------------------
763 # I think these are really important, so always load them
765 [TestingAndDebugging::RequireUseStrict]
768 [TestingAndDebugging::RequireUseWarnings]
771 #--------------------------------------------------------------
772 # I think these are less important, so only load when asked
774 [Variables::ProhibitPackageVars]
777 [ControlStructures::ProhibitPostfixControls]
778 allow = if unless # My custom configuration
779 severity = cruel # Same as "severity = 2"
781 #--------------------------------------------------------------
782 # Give these policies a custom theme. I can activate just
783 # these policies by saying `perlcritic -theme larry`
785 [Modules::RequireFilenameMatchesPackage]
788 [TestingAndDebugging::RequireTestLables]
789 add_themes = larry curly moe
791 #--------------------------------------------------------------
792 # I do not agree with these at all, so never load them
794 [-NamingConventions::ProhibitMixedCaseVars]
795 [-NamingConventions::ProhibitMixedCaseSubs]
797 #--------------------------------------------------------------
798 # For all other Policies, I accept the default severity,
799 # so no additional configuration is required for them.
801 For additional configuration examples, see the F<perlcriticrc> file
802 that is included in this F<examples> directory of this distribution.
804 Damian Conway's own Perl::Critic configuration is also included in this
805 distribution as F<examples/perlcriticrc-conway>.
810 A large number of Policy modules are distributed with Perl::Critic. They are
811 described briefly in the companion document L<Perl::Critic::PolicySummary> and
812 in more detail in the individual modules themselves. Say C<"perlcritic -doc
813 PATTERN"> to see the perldoc for all Policy modules that match the regex
816 There are a number of distributions of additional policies on CPAN. If
817 L<Perl::Critic> doesn't contain a policy that you want, some one may have
818 already written it. See the L</"SEE ALSO"> section below for a list of some
819 of these distributions.
824 Each Policy is defined with one or more "themes". Themes can be used to
825 create arbitrary groups of Policies. They are intended to provide an
826 alternative mechanism for selecting your preferred set of Policies. For
827 example, you may wish disable a certain subset of Policies when analyzing test
828 scripts. Conversely, you may wish to enable only a specific subset of
829 Policies when analyzing modules.
831 The Policies that ship with Perl::Critic are have been broken into the
832 following themes. This is just our attempt to provide some basic logical
833 groupings. You are free to invent new themes that suit your needs.
836 --------------------------------------------------------------------------
837 core All policies that ship with Perl::Critic
838 pbp Policies that come directly from "Perl Best Practices"
839 bugs Policies that that prevent or reveal bugs
840 maintenance Policies that affect the long-term health of the code
841 cosmetic Policies that only have a superficial effect
842 complexity Policies that specificaly relate to code complexity
843 security Policies that relate to security issues
844 tests Policies that are specific to test scripts
847 Any Policy may fit into multiple themes. Say C<"perlcritic -list"> to get a
848 listing of all available Policies and the themes that are associated with each
849 one. You can also change the theme for any Policy in your F<.perlcriticrc>
850 file. See the L<"CONFIGURATION"> section for more information about that.
852 Using the C<-theme> option, you can create an arbitrarily complex rule that
853 determines which Policies will be loaded. Precedence is the same as regular
854 Perl code, and you can use parentheses to enforce precedence as well.
855 Supported operators are:
857 Operator Altertative Example
858 ----------------------------------------------------------------------------
860 || or 'pbp || (bugs && security)'
861 ! not 'pbp && ! (portability || complexity)'
863 Theme names are case-insensitive. If the C<-theme> is set to an empty string,
864 then it evaluates as true all Policies.
867 =head1 BENDING THE RULES
869 Perl::Critic takes a hard-line approach to your code: either you comply or you
870 don't. In the real world, it is not always practical (nor even possible) to
871 fully comply with coding standards. In such cases, it is wise to show that
872 you are knowingly violating the standards and that you have a Damn Good Reason
875 To help with those situations, you can direct Perl::Critic to ignore certain
876 lines or blocks of code by using pseudo-pragmas:
878 require 'LegacyLibaray1.pl'; ## no critic
879 require 'LegacyLibrary2.pl'; ## no critic
881 for my $element (@list) {
885 $foo = ""; #Violates 'ProhibitEmptyQuotes'
886 $barf = bar() if $foo; #Violates 'ProhibitPostfixControls'
887 #Some more evil code...
895 The C<"## no critic"> comments direct Perl::Critic to ignore the remaining
896 lines of code until the end of the current block, or until a C<"## use
897 critic"> comment is found (whichever comes first). If the C<"## no critic">
898 comment is on the same line as a code statement, then only that line of code
899 is overlooked. To direct perlcritic to ignore the C<"## no critic"> comments,
900 use the C<-force> option.
902 A bare C<"## no critic"> comment disables all the active Policies. If you
903 wish to disable only specific Policies, add a list of Policy names as
904 arguments, just as you would for the C<"no strict"> or C<"no warnings">
905 pragmas. For example, this would disable the C<ProhibitEmptyQuotes> and
906 C<ProhibitPostfixControls> policies until the end of the block or until the
907 next C<"## use critic"> comment (whichever comes first):
909 ## no critic (EmptyQuotes, PostfixControls)
911 # Now exempt from ValuesAndExpressions::ProhibitEmptyQuotes
914 # Now exempt ControlStructures::ProhibitPostfixControls
915 $barf = bar() if $foo;
917 # Still subjected to ValuesAndExpression::RequireNumberSeparators
918 $long_int = 10000000000;
920 Since the Policy names are matched against the C<"## no critic"> arguments as
921 regular expressions, you can abbreviate the Policy names or disable an entire
922 family of Policies in one shot like this:
924 ## no critic (NamingConventions)
926 # Now exempt from NamingConventions::ProhibitMixedCaseVars
927 my $camelHumpVar = 'foo';
929 # Now exempt from NamingConventions::ProhibitMixedCaseSubs
932 The argument list must be enclosed in parentheses and must contain one or more
933 comma-separated barewords (e.g. don't use quotes). The C<"## no critic">
934 pragmas can be nested, and Policies named by an inner pragma will be disabled
935 along with those already disabled an outer pragma.
937 Some Policies like C<Subroutines::ProhibitExcessComplexity> apply to an entire
938 block of code. In those cases, C<"## no critic"> must appear on the line
939 where the violation is reported. For example:
941 sub complicated_function { ## no critic (ProhibitExcessComplexity)
945 Policies such as C<Documentation::RequirePodSections> apply to the entire
946 document, in which case violations are reported at line 1. But if the file
947 requires a shebang line, it is impossible to put C<"## no critic"> on the
948 first line of the file. This is a known limitation and it will be addressed
949 in a future release. As a workaround, you can disable the affected policies
950 at the command-line or in your F<.perlcriticrc> file. But beware that this
951 will affect the analysis of B<all> files.
953 Use this feature wisely. C<"## no critic"> should be used in the smallest
954 possible scope, or only on individual lines of code. And you should always be
955 as specific as possible about which policies you want to disable (i.e. never
956 use a bare C<"## no critic">). If Perl::Critic complains about your code, try
957 and find a compliant solution before resorting to this feature.
960 =head1 THE L<Perl::Critic> PHILOSOPHY
962 Coding standards are deeply personal and highly subjective. The goal of
963 Perl::Critic is to help you write code that conforms with a set of best
964 practices. Our primary goal is not to dictate what those practices are, but
965 rather, to implement the practices discovered by others. Ultimately, you make
966 the rules -- Perl::Critic is merely a tool for encouraging consistency. If
967 there is a policy that you think is important or that we have overlooked, we
968 would be very grateful for contributions, or you can simply load your own
969 private set of policies into Perl::Critic.
972 =head1 EXTENDING THE CRITIC
974 The modular design of Perl::Critic is intended to facilitate the addition of
975 new Policies. You'll need to have some understanding of L<PPI>, but most
976 Policy modules are pretty straightforward and only require about 20 lines of
977 code. Please see the L<Perl::Critic::DEVELOPER> file included in this
978 distribution for a step-by-step demonstration of how to create new Policy
981 If you develop any new Policy modules, feel free to send them to C<<
982 <thaljef@cpan.org> >> and I'll be happy to put them into the Perl::Critic
983 distribution. Or if you would like to work on the Perl::Critic project
984 directly, check out our repository at L<http://perlcritic.tigris.org>. To
985 subscribe to our mailing list, send a message to C<<
986 <dev-subscribe@perlcritic.tigris.org> >>.
988 The Perl::Critic team is also available for hire. If your organization has
989 its own coding standards, we can create custom Policies to enforce your local
990 guidelines. Or if your code base is prone to a particular defect pattern, we
991 can design Policies that will help you catch those costly defects B<before>
992 they go into production. To discuss your needs with the Perl::Critic team,
993 just contact C<< <thaljef@cpan.org> >>.
998 Perl::Critic requires the following modules:
1016 L<Module::Pluggable>
1033 The following modules are optional, but recommended for complete
1050 L<Test::Pod::Coverage>
1055 =head1 CONTACTING THE DEVELOPMENT TEAM
1057 You are encouraged to subscribe to the mailing list; send a message to
1058 C<< <users-subscribe@perlcritic.tigris.org> >>. See also
1059 L<the archives|http://perlcritic.tigris.org/servlets/SummarizeList?listName=users>.
1060 You can also contact the author at C<< <thaljef@cpan.org> >>.
1062 At least one member of the development team has started hanging around in
1063 L<irc://irc.perl.org/#perlcritic>.
1068 There are a number of distributions of additional Policies available. A few
1071 L<Perl::Critic::More>
1073 L<Perl::Critic::Bangs>
1075 L<Perl::Critic::Lax>
1077 L<Perl::Critic::StricterSubs>
1079 L<Perl::Critic::Swift>
1081 L<Perl::Critic::Tics>
1083 These distributions enable you to use Perl::Critic in your unit tests:
1085 L<Test::Perl::Critic>
1087 L<Test::Perl::Critic::Progressive>
1089 There are also a couple of distributions that will install all the
1090 Perl::Critic related modules known to the development team:
1092 L<Bundle::Perl::Critic>
1094 L<Task::Perl::Critic>
1096 If you want to make sure you have absolutely everything, you can use these:
1098 L<Bundle::Perl::Critic::IncludingOptionalDependencies>
1100 L<Task::Perl::Critic::IncludingOptionalDependencies>
1105 Scrutinizing Perl code is hard for humans, let alone machines. If you find
1106 any bugs, particularly false-positives or false-negatives from a
1107 Perl::Critic::Policy, please submit them to
1108 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Perl-Critic>. Thanks.
1110 Most policies will produce false-negatives if they cannot understand a
1111 particular block of code.
1116 Adam Kennedy - For creating L<PPI>, the heart and soul of L<Perl::Critic>.
1118 Damian Conway - For writing B<Perl Best Practices>, finally :)
1120 Chris Dolan - For contributing the best features and Policy modules.
1122 Andy Lester - Wise sage and master of all-things-testing.
1124 Elliot Shank - The self-proclaimed quality freak.
1126 Giuseppe Maxia - For all the great ideas and positive encouragement.
1128 and Sharon, my wife - For putting up with my all-night code sessions.
1130 Thanks also to the Perl Foundation for providing a grant to support Chris
1131 Dolan's project to implement twenty PBP policies.
1132 L<http://www.perlfoundation.org/april_1_2007_new_grant_awards>
1137 Jeffrey Ryan Thalhammer <thaljef@cpan.org>
1142 Copyright (c) 2005-2008 Jeffrey Ryan Thalhammer. All rights reserved.
1144 This program is free software; you can redistribute it and/or modify it under
1145 the same terms as Perl itself. The full text of this license can be found in
1146 the LICENSE file included with this module.
1150 ##############################################################################
1153 # cperl-indent-level: 4
1155 # indent-tabs-mode: nil
1156 # c-indentation-style: bsd
1158 # ex: set ts=8 sts=4 sw=4 tw=78 ft=perl expandtab shiftround :