File Coverage

blib/lib/Perl/Critic.pm
Criterion Covered Total %
statement 99 102 97.0
branch 23 28 82.1
condition 10 15 66.6
subroutine 24 24 100.0
pod 6 6 100.0
total 162 175 92.5


line stmt bran cond sub pod time code
1             package Perl::Critic;
2              
3 40     40   1827 use 5.010001;
  40         199  
4 40     40   241 use strict;
  40         102  
  40         922  
5 40     40   211 use warnings;
  40         155  
  40         1339  
6              
7 40     40   251 use English qw(-no_match_vars);
  40         110  
  40         278  
8 40     40   14150 use Readonly;
  40         135  
  40         1966  
9              
10 40     40   301 use Exporter 'import';
  40         106  
  40         1399  
11              
12 40     40   254 use File::Spec;
  40         108  
  40         1572  
13 40     40   6884 use List::SomeUtils qw( firstidx );
  40         159547  
  40         2518  
14 40     40   327 use Scalar::Util qw< blessed >;
  40         105  
  40         2047  
15              
16 40     40   14593 use Perl::Critic::Exception::Configuration::Generic;
  40         124  
  40         1945  
17 40     40   21333 use Perl::Critic::Config;
  40         173  
  40         1660  
18 40     40   299 use Perl::Critic::Violation;
  40         100  
  40         1142  
19 40     40   21199 use Perl::Critic::Document;
  40         143  
  40         1541  
20 40     40   17846 use Perl::Critic::Statistics;
  40         135  
  40         37639  
21              
22             #-----------------------------------------------------------------------------
23              
24             our $VERSION = '1.148';
25              
26             Readonly::Array our @EXPORT_OK => qw(critique);
27              
28             #=============================================================================
29             # PUBLIC methods
30              
31             sub new {
32 2731     2731 1 27777 my ( $class, %args ) = @_;
33 2731         7702 my $self = bless {}, $class;
34 2731   66     17149 $self->{_config} = $args{-config} || Perl::Critic::Config->new( %args );
35 2730         12795 $self->{_stats} = Perl::Critic::Statistics->new();
36 2730         8327 return $self;
37             }
38              
39             #-----------------------------------------------------------------------------
40              
41             sub config {
42 14522     14522 1 21728 my $self = shift;
43 14522         45296 return $self->{_config};
44             }
45              
46             #-----------------------------------------------------------------------------
47              
48             sub add_policy {
49 2692     2692 1 7944 my ( $self, @args ) = @_;
50             #Delegate to Perl::Critic::Config
51 2692         8168 return $self->config()->add_policy( @args );
52             }
53              
54             #-----------------------------------------------------------------------------
55              
56             sub policies {
57 2726     2726 1 4685 my $self = shift;
58              
59             #Delegate to Perl::Critic::Config
60 2726         6955 return $self->config()->policies();
61             }
62              
63             #-----------------------------------------------------------------------------
64              
65             sub statistics {
66 2725     2725 1 5531 my $self = shift;
67 2725         13409 return $self->{_stats};
68             }
69              
70             #-----------------------------------------------------------------------------
71              
72             sub critique { ## no critic (ArgUnpacking)
73              
74             #-------------------------------------------------------------------
75             # This subroutine can be called as an object method or as a static
76             # function. In the latter case, the first argument can be a
77             # hashref of configuration parameters that shall be used to create
78             # an object behind the scenes. Note that this object does not
79             # persist. In other words, it is not a singleton. Here are some
80             # of the ways this subroutine might get called:
81             #
82             # #Object style...
83             # $critic->critique( $code );
84             #
85             # #Functional style...
86             # critique( $code );
87             # critique( {}, $code );
88             # critique( {-foo => bar}, $code );
89             #------------------------------------------------------------------
90              
91 2728 100   2728 1 12595 my ( $self, $source_code ) = @_ >= 2 ? @_ : ( {}, $_[0] );
92 2728 100       8005 $self = ref $self eq 'HASH' ? __PACKAGE__->new(%{ $self }) : $self;
  4         27  
93 2728 100       7277 return if not defined $source_code; # If no code, then nothing to do.
94              
95 2726         6724 my $config = $self->config();
96 2726 50 33     16458 my $doc =
97             blessed($source_code) && $source_code->isa('Perl::Critic::Document')
98             ? $source_code
99             : Perl::Critic::Document->new(
100             '-source' => $source_code,
101             '-program-extensions' => [$config->program_extensions_as_regexes()],
102             );
103              
104 2726 100       10135 if ( 0 == $self->policies() ) {
105 2         33 Perl::Critic::Exception::Configuration::Generic->throw(
106             message => 'There are no enabled policies.',
107             )
108             }
109              
110 2724         7952 return $self->_gather_violations($doc);
111             }
112              
113             #=============================================================================
114             # PRIVATE methods
115              
116             sub _gather_violations {
117 2724     2724   6862 my ($self, $doc) = @_;
118              
119             # Disable exempt code lines, if desired
120 2724 100       7454 if ( not $self->config->force() ) {
121 2721         7431 $doc->process_annotations();
122             }
123              
124             # Evaluate each policy
125 2724         9649 my @policies = $self->config->policies();
126 2724         8393 my @ordered_policies = _futz_with_policy_order(@policies);
127 2724         7648 my @violations = map { _critique($_, $doc) } @ordered_policies;
  6991         15131  
128              
129             # Accumulate statistics
130 2724         7800 $self->statistics->accumulate( $doc, \@violations );
131              
132             # If requested, rank violations by their severity and return the top N.
133 2724 50 66     11163 if ( @violations && (my $top = $self->config->top()) ) {
134 0 0       0 my $limit = @violations < $top ? $#violations : $top-1;
135 0         0 @violations = Perl::Critic::Violation::sort_by_severity(@violations);
136 0         0 @violations = ( reverse @violations )[ 0 .. $limit ]; #Slicing...
137             }
138              
139             # Always return violations sorted by location
140 2724         13447 return Perl::Critic::Violation->sort_by_location(@violations);
141             }
142              
143             #=============================================================================
144             # PRIVATE functions
145              
146             sub _critique {
147 6991     6991   12432 my ($policy, $doc) = @_;
148              
149 6991 100       30023 return if not $policy->prepare_to_scan_document($doc);
150              
151 6981         20995 my $maximum_violations = $policy->get_maximum_violations_per_document();
152 6981 50 66     18669 return if defined $maximum_violations && $maximum_violations == 0;
153              
154 6981         10553 my @violations = ();
155              
156             TYPE:
157 6981         36536 for my $type ( $policy->applies_to() ) {
158 10044         14786 my @elements;
159 10044 100       18439 if ($type eq 'PPI::Document') {
160 663         1179 @elements = ($doc);
161             }
162             else {
163 9381 100       12232 @elements = @{ $doc->find($type) || [] };
  9381         21853  
164             }
165              
166             ELEMENT:
167 10044         21135 for my $element (@elements) {
168              
169             # Evaluate the policy on this $element. A policy may
170             # return zero or more violations. We only want the
171             # violations that occur on lines that have not been
172             # disabled.
173              
174             VIOLATION:
175 35506         199722 for my $violation ( $policy->violates( $element, $doc ) ) {
176              
177 3171         11578 my $line = $violation->location()->[0];
178 3171 100       11709 if ( $doc->line_is_disabled_for_policy($line, $policy) ) {
179 133         493 $doc->add_suppressed_violation($violation);
180 133         446 next VIOLATION;
181             }
182              
183 3038         5884 push @violations, $violation;
184 3038 100 100     10308 last TYPE if defined $maximum_violations and @violations >= $maximum_violations;
185             }
186             }
187             }
188              
189 6981         36795 return @violations;
190             }
191              
192             #-----------------------------------------------------------------------------
193              
194             sub _futz_with_policy_order {
195             # The ProhibitUselessNoCritic policy is another special policy. It
196             # deals with the violations that *other* Policies produce. Therefore
197             # it needs to be run *after* all the other Policies. TODO: find
198             # a way for Policies to express an ordering preference somehow.
199              
200 2724     2724   5730 my @policy_objects = @_;
201 2724         4881 my $magical_policy_name = 'Perl::Critic::Policy::Miscellanea::ProhibitUselessNoCritic';
202 2724     6910   17427 my $idx = firstidx {ref $_ eq $magical_policy_name} @policy_objects;
  6910         16380  
203 2724         10367 push @policy_objects, splice @policy_objects, $idx, 1;
204 2724         6901 return @policy_objects;
205             }
206              
207             #-----------------------------------------------------------------------------
208              
209             1;
210              
211              
212              
213             __END__
214              
215             =pod
216              
217             =encoding utf8
218              
219             =for stopwords DGR INI-style API -params pbp refactored ActivePerl ben Jore
220             Dolan's Twitter Alexandr Ciornii Ciornii's downloadable O'Regan
221             Hukins Omer Gazit Zacks Howarth Walde Rolsky Jakub Wilk Trosien Creenan
222             Balhatchet Paaske Tørholm Raspass Tonkin Katz Berndt Sergey Gabor Szabo
223             Knop Eldridge Steinbrunner Kimmel Guillaume Aubert Anirvan Chatterjee
224             Rinaldo Ollis Etheridge Brømsø Slaven Rezić Szymon Nieznański
225             Oschwald Mita Amory Meltzer Grechkin Bernhard Schmalhofer TOYAMA Nao Wyant
226             Tadeusz Sośnierz Isaac Gittins Novakovic
227              
228             =head1 NAME
229              
230             Perl::Critic - Critique Perl source code for best-practices.
231              
232              
233             =head1 SYNOPSIS
234              
235             use Perl::Critic;
236             my $file = shift;
237             my $critic = Perl::Critic->new();
238             my @violations = $critic->critique($file);
239             print @violations;
240              
241              
242             =head1 DESCRIPTION
243              
244             Perl::Critic is an extensible framework for creating and applying coding
245             standards to Perl source code. Essentially, it is a static source code
246             analysis engine. Perl::Critic is distributed with a number of
247             L<Perl::Critic::Policy> modules that attempt to enforce various coding
248             guidelines. Most Policy modules are based on Damian Conway's book B<Perl Best
249             Practices>. However, Perl::Critic is B<not> limited to PBP and will even
250             support Policies that contradict Conway. You can enable, disable, and
251             customize those Polices through the Perl::Critic interface. You can also
252             create new Policy modules that suit your own tastes.
253              
254             For a command-line interface to Perl::Critic, see the documentation for
255             L<perlcritic>. If you want to integrate Perl::Critic with your build process,
256             L<Test::Perl::Critic> provides an interface that is suitable for test
257             programs. Also, L<Test::Perl::Critic::Progressive> is useful for gradually
258             applying coding standards to legacy code. For the ultimate convenience (at
259             the expense of some flexibility) see the L<criticism> pragma.
260              
261             If you'd like to try L<Perl::Critic> without installing anything, there is a
262             web-service available at L<http://perlcritic.com>. The web-service does not
263             yet support all the configuration features that are available in the native
264             Perl::Critic API, but it should give you a good idea of what it does.
265              
266             Also, ActivePerl includes a very slick graphical interface to Perl-Critic
267             called C<perlcritic-gui>. You can get a free community edition of ActivePerl
268             from L<http://www.activestate.com>.
269              
270              
271             =head1 PREREQUISITES
272              
273             Perl::Critic runs on Perl back to Perl 5.10.1. It relies on the L<PPI>
274             module to do the heavy work of parsing Perl.
275              
276              
277             =head1 INTERFACE SUPPORT
278              
279             The C<Perl::Critic> module is considered to be a public class. Any
280             changes to its interface will go through a deprecation cycle.
281              
282              
283             =head1 CONSTRUCTOR
284              
285             =over
286              
287             =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, -pager => $string, -allow-unsafe => $B, -criticism-fatal => $B) >>
288              
289             =item C<< new() >>
290              
291             Returns a reference to a new Perl::Critic object. Most arguments are just
292             passed directly into L<Perl::Critic::Config>, but I have described them here
293             as well. The default value for all arguments can be defined in your
294             F<.perlcriticrc> file. See the L<"CONFIGURATION"> section for more
295             information about that. All arguments are optional key-value pairs as
296             follows:
297              
298             B<-profile> is a path to a configuration file. If C<$FILE> is not defined,
299             Perl::Critic::Config attempts to find a F<.perlcriticrc> configuration file in
300             the current directory, and then in your home directory. Alternatively, you
301             can set the C<PERLCRITIC> environment variable to point to a file in another
302             location. If a configuration file can't be found, or if C<$FILE> is an empty
303             string, then all Policies will be loaded with their default configuration.
304             See L<"CONFIGURATION"> for more information.
305              
306             B<-severity> is the minimum severity level. Only Policy modules that have a
307             severity greater than C<$N> will be applied. Severity values are integers
308             ranging from 1 (least severe violations) to 5 (most severe violations). The
309             default is 5. For a given C<-profile>, decreasing the C<-severity> will
310             usually reveal more Policy violations. You can set the default value for this
311             option in your F<.perlcriticrc> file. Users can redefine the severity level
312             for any Policy in their F<.perlcriticrc> file. See L<"CONFIGURATION"> for
313             more information.
314              
315             If it is difficult for you to remember whether severity "5" is the most or
316             least restrictive level, then you can use one of these named values:
317              
318             SEVERITY NAME ...is equivalent to... SEVERITY NUMBER
319             --------------------------------------------------------
320             -severity => 'gentle' -severity => 5
321             -severity => 'stern' -severity => 4
322             -severity => 'harsh' -severity => 3
323             -severity => 'cruel' -severity => 2
324             -severity => 'brutal' -severity => 1
325              
326             The names reflect how severely the code is criticized: a C<gentle> criticism
327             reports only the most severe violations, and so on down to a C<brutal>
328             criticism which reports even the most minor violations.
329              
330             B<-theme> is special expression that determines which Policies to apply based
331             on their respective themes. For example, the following would load only
332             Policies that have a 'bugs' AND 'pbp' theme:
333              
334             my $critic = Perl::Critic->new( -theme => 'bugs && pbp' );
335              
336             Unless the C<-severity> option is explicitly given, setting C<-theme> silently
337             causes the C<-severity> to be set to 1. You can set the default value for
338             this option in your F<.perlcriticrc> file. See the L<"POLICY THEMES"> section
339             for more information about themes.
340              
341              
342             B<-include> is a reference to a list of string C<@PATTERNS>. Policy modules
343             that match at least one C<m/$PATTERN/ixms> will always be loaded, irrespective
344             of all other settings. For example:
345              
346             my $critic = Perl::Critic->new(-include => ['layout'], -severity => 4);
347              
348             This would cause Perl::Critic to apply all the C<CodeLayout::*> Policy modules
349             even though they have a severity level that is less than 4. You can set the
350             default value for this option in your F<.perlcriticrc> file. You can also use
351             C<-include> in conjunction with the C<-exclude> option. Note that C<-exclude>
352             takes precedence over C<-include> when a Policy matches both patterns.
353              
354             B<-exclude> is a reference to a list of string C<@PATTERNS>. Policy modules
355             that match at least one C<m/$PATTERN/ixms> will not be loaded, irrespective of
356             all other settings. For example:
357              
358             my $critic = Perl::Critic->new(-exclude => ['strict'], -severity => 1);
359              
360             This would cause Perl::Critic to not apply the C<RequireUseStrict> and
361             C<ProhibitNoStrict> Policy modules even though they have a severity level that
362             is greater than 1. You can set the default value for this option in your
363             F<.perlcriticrc> file. You can also use C<-exclude> in conjunction with the
364             C<-include> option. Note that C<-exclude> takes precedence over C<-include>
365             when a Policy matches both patterns.
366              
367             B<-single-policy> is a string C<PATTERN>. Only one policy that matches
368             C<m/$PATTERN/ixms> will be used. Policies that do not match will be excluded.
369             This option has precedence over the C<-severity>, C<-theme>, C<-include>,
370             C<-exclude>, and C<-only> options. You can set the default value for this
371             option in your F<.perlcriticrc> file.
372              
373             B<-top> is the maximum number of Violations to return when ranked by their
374             severity levels. This must be a positive integer. Violations are still
375             returned in the order that they occur within the file. Unless the C<-severity>
376             option is explicitly given, setting C<-top> silently causes the C<-severity>
377             to be set to 1. You can set the default value for this option in your
378             F<.perlcriticrc> file.
379              
380             B<-only> is a boolean value. If set to a true value, Perl::Critic will only
381             choose from Policies that are mentioned in the user's profile. If set to a
382             false value (which is the default), then Perl::Critic chooses from all the
383             Policies that it finds at your site. You can set the default value for this
384             option in your F<.perlcriticrc> file.
385              
386             B<-profile-strictness> is an enumerated value, one of
387             L<Perl::Critic::Utils::Constants/"$PROFILE_STRICTNESS_WARN"> (the default),
388             L<Perl::Critic::Utils::Constants/"$PROFILE_STRICTNESS_FATAL">, and
389             L<Perl::Critic::Utils::Constants/"$PROFILE_STRICTNESS_QUIET">. If set to
390             L<Perl::Critic::Utils::Constants/"$PROFILE_STRICTNESS_FATAL">, Perl::Critic
391             will make certain warnings about problems found in a F<.perlcriticrc> or file
392             specified via the B<-profile> option fatal. For example, Perl::Critic normally
393             only C<warn>s about profiles referring to non-existent Policies, but this
394             value makes this situation fatal. Correspondingly,
395             L<Perl::Critic::Utils::Constants/"$PROFILE_STRICTNESS_QUIET"> makes
396             Perl::Critic shut up about these things.
397              
398             B<-force> is a boolean value that controls whether Perl::Critic observes the
399             magical C<"## no critic"> annotations in your code. If set to a true value,
400             Perl::Critic will analyze all code. If set to a false value (which is the
401             default) Perl::Critic will ignore code that is tagged with these annotations.
402             See L<"BENDING THE RULES"> for more information. You can set the default
403             value for this option in your F<.perlcriticrc> file.
404              
405             B<-verbose> can be a positive integer (from 1 to 11), or a literal format
406             specification. See L<Perl::Critic::Violation|Perl::Critic::Violation> for an
407             explanation of format specifications. You can set the default value for this
408             option in your F<.perlcriticrc> file.
409              
410             B<-unsafe> directs Perl::Critic to allow the use of Policies that are marked
411             as "unsafe" by the author. Such policies may compile untrusted code or do
412             other nefarious things.
413              
414             B<-color> and B<-pager> are not used by Perl::Critic but is provided for the
415             benefit of L<perlcritic|perlcritic>.
416              
417             B<-criticism-fatal> is not used by Perl::Critic but is provided for the
418             benefit of L<criticism|criticism>.
419              
420             B<-color-severity-highest>, B<-color-severity-high>, B<-color-severity-
421             medium>, B<-color-severity-low>, and B<-color-severity-lowest> are not used by
422             Perl::Critic, but are provided for the benefit of L<perlcritic|perlcritic>.
423             Each is set to the Term::ANSIColor color specification to be used to display
424             violations of the corresponding severity.
425              
426             B<-files-with-violations> and B<-files-without-violations> are not used by
427             Perl::Critic, but are provided for the benefit of L<perlcritic|perlcritic>, to
428             cause only the relevant filenames to be displayed.
429              
430             =back
431              
432              
433             =head1 METHODS
434              
435             =over
436              
437             =item C<critique( $source_code )>
438              
439             Runs the C<$source_code> through the Perl::Critic engine using all the
440             Policies that have been loaded into this engine. If C<$source_code> is a
441             scalar reference, then it is treated as a string of actual Perl code. If
442             C<$source_code> is a reference to an instance of L<PPI::Document>, then that
443             instance is used directly. Otherwise, it is treated as a path to a local file
444             containing Perl code. This method returns a list of
445             L<Perl::Critic::Violation> objects for each violation of the loaded Policies.
446             The list is sorted in the order that the Violations appear in the code. If
447             there are no violations, this method returns an empty list.
448              
449             =item C<< add_policy( -policy => $policy_name, -params => \%param_hash ) >>
450              
451             Creates a Policy object and loads it into this Critic. If the object cannot
452             be instantiated, it will throw a fatal exception. Otherwise, it returns a
453             reference to this Critic.
454              
455             B<-policy> is the name of a L<Perl::Critic::Policy> subclass module. The
456             C<'Perl::Critic::Policy'> portion of the name can be omitted for brevity.
457             This argument is required.
458              
459             B<-params> is an optional reference to a hash of Policy parameters. The
460             contents of this hash reference will be passed into to the constructor of the
461             Policy module. See the documentation in the relevant Policy module for a
462             description of the arguments it supports.
463              
464             =item C< policies() >
465              
466             Returns a list containing references to all the Policy objects that have been
467             loaded into this engine. Objects will be in the order that they were loaded.
468              
469             =item C< config() >
470              
471             Returns the L<Perl::Critic::Config> object that was created for or given to
472             this Critic.
473              
474             =item C< statistics() >
475              
476             Returns the L<Perl::Critic::Statistics> object that was created for this
477             Critic. The Statistics object accumulates data for all files that are
478             analyzed by this Critic.
479              
480             =back
481              
482              
483             =head1 FUNCTIONAL INTERFACE
484              
485             For those folks who prefer to have a functional interface, The C<critique>
486             method can be exported on request and called as a static function. If the
487             first argument is a hashref, its contents are used to construct a new
488             Perl::Critic object internally. The keys of that hash should be the same as
489             those supported by the C<Perl::Critic::new()> method. Here are some examples:
490              
491             use Perl::Critic qw(critique);
492              
493             # Use default parameters...
494             @violations = critique( $some_file );
495              
496             # Use custom parameters...
497             @violations = critique( {-severity => 2}, $some_file );
498              
499             # As a one-liner
500             %> perl -MPerl::Critic=critique -e 'print critique(shift)' some_file.pm
501              
502             None of the other object-methods are currently supported as static
503             functions. Sorry.
504              
505              
506             =head1 CONFIGURATION
507              
508             Most of the settings for Perl::Critic and each of the Policy modules can be
509             controlled by a configuration file. The default configuration file is called
510             F<.perlcriticrc>. Perl::Critic will look for this file in the current
511             directory first, and then in your home directory. Alternatively, you can set
512             the C<PERLCRITIC> environment variable to explicitly point to a different file
513             in another location. If none of these files exist, and the C<-profile> option
514             is not given to the constructor, then all the modules that are found in the
515             Perl::Critic::Policy namespace will be loaded with their default
516             configuration.
517              
518             The format of the configuration file is a series of INI-style blocks that
519             contain key-value pairs separated by '='. Comments should start with '#' and
520             can be placed on a separate line or after the name-value pairs if you desire.
521              
522             Default settings for Perl::Critic itself can be set B<before the first named
523             block.> For example, putting any or all of these at the top of your
524             configuration file will set the default value for the corresponding
525             constructor argument.
526              
527             severity = 3 #Integer or named level
528             only = 1 #Zero or One
529             force = 0 #Zero or One
530             verbose = 4 #Integer or format spec
531             top = 50 #A positive integer
532             theme = (pbp || security) && bugs #A theme expression
533             include = NamingConventions ClassHierarchies #Space-delimited list
534             exclude = Variables Modules::RequirePackage #Space-delimited list
535             criticism-fatal = 1 #Zero or One
536             color = 1 #Zero or One
537             allow-unsafe = 1 #Zero or One
538             pager = less #pager to pipe output to
539              
540             The remainder of the configuration file is a series of blocks like this:
541              
542             [Perl::Critic::Policy::Category::PolicyName]
543             severity = 1
544             set_themes = foo bar
545             add_themes = baz
546             maximum_violations_per_document = 57
547             arg1 = value1
548             arg2 = value2
549              
550             C<Perl::Critic::Policy::Category::PolicyName> is the full name of a module
551             that implements the policy. The Policy modules distributed with Perl::Critic
552             have been grouped into categories according to the table of contents in Damian
553             Conway's book B<Perl Best Practices>. For brevity, you can omit the
554             C<'Perl::Critic::Policy'> part of the module name.
555              
556             C<severity> is the level of importance you wish to assign to the Policy. All
557             Policy modules are defined with a default severity value ranging from 1 (least
558             severe) to 5 (most severe). However, you may disagree with the default
559             severity and choose to give it a higher or lower severity, based on your own
560             coding philosophy. You can set the C<severity> to an integer from 1 to 5, or
561             use one of the equivalent names:
562              
563             SEVERITY NAME ...is equivalent to... SEVERITY NUMBER
564             ----------------------------------------------------
565             gentle 5
566             stern 4
567             harsh 3
568             cruel 2
569             brutal 1
570              
571             The names reflect how severely the code is criticized: a C<gentle> criticism
572             reports only the most severe violations, and so on down to a C<brutal>
573             criticism which reports even the most minor violations.
574              
575             C<set_themes> sets the theme for the Policy and overrides its default theme.
576             The argument is a string of one or more whitespace-delimited alphanumeric
577             words. Themes are case-insensitive. See L<"POLICY THEMES"> for more
578             information.
579              
580             C<add_themes> appends to the default themes for this Policy. The argument is
581             a string of one or more whitespace-delimited words. Themes are case-
582             insensitive. See L<"POLICY THEMES"> for more information.
583              
584             C<maximum_violations_per_document> limits the number of Violations the Policy
585             will return for a given document. Some Policies have a default limit; see the
586             documentation for the individual Policies to see whether there is one. To
587             force a Policy to not have a limit, specify "no_limit" or the empty string for
588             the value of this parameter.
589              
590             The remaining key-value pairs are configuration parameters that will be passed
591             into the constructor for that Policy. The constructors for most Policy
592             objects do not support arguments, and those that do should have reasonable
593             defaults. See the documentation on the appropriate Policy module for more
594             details.
595              
596             Instead of redefining the severity for a given Policy, you can completely
597             disable a Policy by prepending a '-' to the name of the module in your
598             configuration file. In this manner, the Policy will never be loaded,
599             regardless of the C<-severity> given to the Perl::Critic constructor.
600              
601             A simple configuration might look like this:
602              
603             #--------------------------------------------------------------
604             # I think these are really important, so always load them
605              
606             [TestingAndDebugging::RequireUseStrict]
607             severity = 5
608              
609             [TestingAndDebugging::RequireUseWarnings]
610             severity = 5
611              
612             #--------------------------------------------------------------
613             # I think these are less important, so only load when asked
614              
615             [Variables::ProhibitPackageVars]
616             severity = 2
617              
618             [ControlStructures::ProhibitPostfixControls]
619             allow = if unless # My custom configuration
620             severity = cruel # Same as "severity = 2"
621              
622             #--------------------------------------------------------------
623             # Give these policies a custom theme. I can activate just
624             # these policies by saying `perlcritic -theme larry`
625              
626             [Modules::RequireFilenameMatchesPackage]
627             add_themes = larry
628              
629             [TestingAndDebugging::RequireTestLabels]
630             add_themes = larry curly moe
631              
632             #--------------------------------------------------------------
633             # I do not agree with these at all, so never load them
634              
635             [-NamingConventions::Capitalization]
636             [-ValuesAndExpressions::ProhibitMagicNumbers]
637              
638             #--------------------------------------------------------------
639             # For all other Policies, I accept the default severity,
640             # so no additional configuration is required for them.
641              
642             For additional configuration examples, see the F<perlcriticrc> file that is
643             included in this F<examples> directory of this distribution.
644              
645             Damian Conway's own Perl::Critic configuration is also included in this
646             distribution as F<examples/perlcriticrc-conway>.
647              
648              
649             =head1 THE POLICIES
650              
651             A large number of Policy modules are distributed with Perl::Critic. They are
652             described briefly in the companion document L<Perl::Critic::PolicySummary> and
653             in more detail in the individual modules themselves. Say C<"perlcritic -doc
654             PATTERN"> to see the perldoc for all Policy modules that match the regex
655             C<m/PATTERN/ixms>
656              
657             There are a number of distributions of additional policies on CPAN. If
658             L<Perl::Critic> doesn't contain a policy that you want, some one may have
659             already written it. See the L</"SEE ALSO"> section below for a list of some
660             of these distributions.
661              
662              
663             =head1 POLICY THEMES
664              
665             Each Policy is defined with one or more "themes". Themes can be used to
666             create arbitrary groups of Policies. They are intended to provide an
667             alternative mechanism for selecting your preferred set of Policies. For
668             example, you may wish disable a certain subset of Policies when analyzing test
669             programs. Conversely, you may wish to enable only a specific subset of
670             Policies when analyzing modules.
671              
672             The Policies that ship with Perl::Critic have been broken into the following
673             themes. This is just our attempt to provide some basic logical groupings.
674             You are free to invent new themes that suit your needs.
675              
676             THEME DESCRIPTION
677             --------------------------------------------------------------------------
678             core All policies that ship with Perl::Critic
679             pbp Policies that come directly from "Perl Best Practices"
680             bugs Policies that that prevent or reveal bugs
681             certrec Policies that CERT recommends
682             certrule Policies that CERT considers rules
683             maintenance Policies that affect the long-term health of the code
684             cosmetic Policies that only have a superficial effect
685             complexity Policies that specifically relate to code complexity
686             security Policies that relate to security issues
687             tests Policies that are specific to test programs
688              
689              
690             Any Policy may fit into multiple themes. Say C<"perlcritic -list"> to get a
691             listing of all available Policies and the themes that are associated with each
692             one. You can also change the theme for any Policy in your F<.perlcriticrc>
693             file. See the L<"CONFIGURATION"> section for more information about that.
694              
695             Using the C<-theme> option, you can create an arbitrarily complex rule that
696             determines which Policies will be loaded. Precedence is the same as regular
697             Perl code, and you can use parentheses to enforce precedence as well.
698             Supported operators are:
699              
700             Operator Alternative Example
701             -----------------------------------------------------------------
702             && and 'pbp && core'
703             || or 'pbp || (bugs && security)'
704             ! not 'pbp && ! (portability || complexity)'
705              
706             Theme names are case-insensitive. If the C<-theme> is set to an empty string,
707             then it evaluates as true all Policies.
708              
709              
710             =head1 BENDING THE RULES
711              
712             Perl::Critic takes a hard-line approach to your code: either you comply or you
713             don't. In the real world, it is not always practical (nor even possible) to
714             fully comply with coding standards. In such cases, it is wise to show that
715             you are knowingly violating the standards and that you have a Damn Good Reason
716             (DGR) for doing so.
717              
718             To help with those situations, you can direct Perl::Critic to ignore certain
719             lines or blocks of code by using annotations:
720              
721             require 'LegacyLibaray1.pl'; ## no critic
722             require 'LegacyLibrary2.pl'; ## no critic
723              
724             for my $element (@list) {
725              
726             ## no critic
727              
728             $foo = ""; #Violates 'ProhibitEmptyQuotes'
729             $barf = bar() if $foo; #Violates 'ProhibitPostfixControls'
730             #Some more evil code...
731              
732             ## use critic
733              
734             #Some good code...
735             do_something($_);
736             }
737              
738             The C<"## no critic"> annotations direct Perl::Critic to ignore the remaining
739             lines of code until a C<"## use critic"> annotation is found. If the C<"## no
740             critic"> annotation is on the same line as a code statement, then only that
741             line of code is overlooked. To direct perlcritic to ignore the C<"## no
742             critic"> annotations, use the C<--force> option.
743              
744             A bare C<"## no critic"> annotation disables all the active Policies. If you
745             wish to disable only specific Policies, add a list of Policy names as
746             arguments, just as you would for the C<"no strict"> or C<"no warnings">
747             pragmas. For example, this would disable the C<ProhibitEmptyQuotes> and
748             C<ProhibitPostfixControls> policies until the end of the block or until the
749             next C<"## use critic"> annotation (whichever comes first):
750              
751             ## no critic (EmptyQuotes, PostfixControls)
752              
753             # Now exempt from ValuesAndExpressions::ProhibitEmptyQuotes
754             $foo = "";
755              
756             # Now exempt ControlStructures::ProhibitPostfixControls
757             $barf = bar() if $foo;
758              
759             # Still subjected to ValuesAndExpression::RequireNumberSeparators
760             $long_int = 10000000000;
761              
762             Since the Policy names are matched against the C<"## no critic"> arguments as
763             regular expressions, you can abbreviate the Policy names or disable an entire
764             family of Policies in one shot like this:
765              
766             ## no critic (NamingConventions)
767              
768             # Now exempt from NamingConventions::Capitalization
769             my $camelHumpVar = 'foo';
770              
771             # Now exempt from NamingConventions::Capitalization
772             sub camelHumpSub {}
773              
774             The argument list must be enclosed in parentheses or brackets and must contain
775             one or more comma-separated barewords (e.g. don't use quotes).
776             The C<"## no critic"> annotations can be nested, and Policies named by an inner
777             annotation will be disabled along with those already disabled an outer
778             annotation.
779              
780             Some Policies like C<Subroutines::ProhibitExcessComplexity> apply to an entire
781             block of code. In those cases, the C<"## no critic"> annotation must appear
782             on the line where the violation is reported. For example:
783              
784             sub complicated_function { ## no critic (ProhibitExcessComplexity)
785             # Your code here...
786             }
787              
788             Policies such as C<Documentation::RequirePodSections> apply to the entire
789             document, in which case violations are reported at line 1.
790              
791             Use this feature wisely. C<"## no critic"> annotations should be used in the
792             smallest possible scope, or only on individual lines of code. And you should
793             always be as specific as possible about which Policies you want to disable
794             (i.e. never use a bare C<"## no critic">). If Perl::Critic complains about
795             your code, try and find a compliant solution before resorting to this feature.
796              
797              
798             =head1 THE L<Perl::Critic> PHILOSOPHY
799              
800             Coding standards are deeply personal and highly subjective. The goal of
801             Perl::Critic is to help you write code that conforms with a set of best
802             practices. Our primary goal is not to dictate what those practices are, but
803             rather, to implement the practices discovered by others. Ultimately, you make
804             the rules -- Perl::Critic is merely a tool for encouraging consistency. If
805             there is a policy that you think is important or that we have overlooked, we
806             would be very grateful for contributions, or you can simply load your own
807             private set of policies into Perl::Critic.
808              
809              
810             =head1 EXTENDING THE CRITIC
811              
812             The modular design of Perl::Critic is intended to facilitate the addition of
813             new Policies. You'll need to have some understanding of L<PPI>, but most
814             Policy modules are pretty straightforward and only require about 20 lines of
815             code. Please see the L<Perl::Critic::DEVELOPER> file included in this
816             distribution for a step-by-step demonstration of how to create new Policy
817             modules.
818              
819             If you develop any new Policy modules, feel free to send them to C<<
820             <team@perlcritic.com> >> and I'll be happy to consider putting them into the
821             Perl::Critic distribution. Or if you would like to work on the Perl::Critic
822             project directly, you can fork our repository at
823             L<https://github.com/Perl-Critic/Perl-Critic.git>.
824              
825             The Perl::Critic team is also available for hire. If your organization has
826             its own coding standards, we can create custom Policies to enforce your local
827             guidelines. Or if your code base is prone to a particular defect pattern, we
828             can design Policies that will help you catch those costly defects B<before>
829             they go into production. To discuss your needs with the Perl::Critic team,
830             just contact C<< <team@perlcritic.com> >>.
831              
832              
833             =head1 PREREQUISITES
834              
835             Perl::Critic requires the following modules:
836              
837             L<B::Keywords>
838              
839             L<Config::Tiny>
840              
841             L<Exception::Class>
842              
843             L<File::Spec>
844              
845             L<File::Spec::Unix>
846              
847             L<File::Which>
848              
849             L<List::SomeUtils>
850              
851             L<List::Util>
852              
853             L<Module::Pluggable>
854              
855             L<Perl::Tidy>
856              
857             L<Pod::Spell>
858              
859             L<PPI|PPI>
860              
861             L<Pod::PlainText>
862              
863             L<Pod::Select>
864              
865             L<Pod::Usage>
866              
867             L<Readonly>
868              
869             L<Scalar::Util>
870              
871             L<String::Format>
872              
873             L<Term::ANSIColor>
874              
875             L<Text::ParseWords>
876              
877             L<version|version>
878              
879              
880             =head1 CONTACTING THE DEVELOPMENT TEAM
881              
882             You are encouraged to subscribe to the public mailing list at
883             L<https://groups.google.com/d/forum/perl-critic>.
884             At least one member of the development team is usually hanging around
885             in L<irc://irc.perl.org/#perlcritic> and you can follow Perl::Critic on
886             Twitter, at L<https://twitter.com/perlcritic>.
887              
888              
889             =head1 SEE ALSO
890              
891             There are a number of distributions of additional Policies available. A few
892             are listed here:
893              
894             L<Perl::Critic::More>
895              
896             L<Perl::Critic::Bangs>
897              
898             L<Perl::Critic::Lax>
899              
900             L<Perl::Critic::StricterSubs>
901              
902             L<Perl::Critic::Swift>
903              
904             L<Perl::Critic::Tics>
905              
906             These distributions enable you to use Perl::Critic in your unit tests:
907              
908             L<Test::Perl::Critic>
909              
910             L<Test::Perl::Critic::Progressive>
911              
912             There is also a distribution that will install all the Perl::Critic related
913             modules known to the development team:
914              
915             L<Task::Perl::Critic>
916              
917              
918             =head1 BUGS
919              
920             Scrutinizing Perl code is hard for humans, let alone machines. If you find
921             any bugs, particularly false-positives or false-negatives from a
922             Perl::Critic::Policy, please submit them at
923             L<https://github.com/Perl-Critic/Perl-Critic/issues>. Thanks.
924              
925             =head1 CREDITS
926              
927             Adam Kennedy - For creating L<PPI>, the heart and soul of L<Perl::Critic>.
928              
929             Damian Conway - For writing B<Perl Best Practices>, finally :)
930              
931             Chris Dolan - For contributing the best features and Policy modules.
932              
933             Andy Lester - Wise sage and master of all-things-testing.
934              
935             Elliot Shank - The self-proclaimed quality freak.
936              
937             Giuseppe Maxia - For all the great ideas and positive encouragement.
938              
939             and Sharon, my wife - For putting up with my all-night code sessions.
940              
941             Thanks also to the Perl Foundation for providing a grant to support Chris
942             Dolan's project to implement twenty PBP policies.
943             L<http://www.perlfoundation.org/april_1_2007_new_grant_awards>
944              
945             Thanks also to this incomplete laundry list of folks who have contributed
946             to Perl::Critic in some way:
947             Chris Novakovic,
948             Isaac Gittins,
949             Tadeusz Sośnierz,
950             Tom Wyant,
951             TOYAMA Nao,
952             Bernhard Schmalhofer,
953             Amory Meltzer,
954             Andrew Grechkin,
955             Daniel Mita,
956             Gregory Oschwald,
957             Mike O'Regan,
958             Tom Hukins,
959             Omer Gazit,
960             Evan Zacks,
961             Paul Howarth,
962             Sawyer X,
963             Christian Walde,
964             Dave Rolsky,
965             Jakub Wilk,
966             Roy Ivy III,
967             Oliver Trosien,
968             Glenn Fowler,
969             Matt Creenan,
970             Alex Balhatchet,
971             Sebastian Paaske Tørholm,
972             Stuart A Johnston,
973             Dan Book,
974             Steven Humphrey,
975             James Raspass,
976             Nick Tonkin,
977             Harrison Katz,
978             Douglas Sims,
979             Mark Fowler,
980             Alan Berndt,
981             Neil Bowers,
982             Sergey Romanov,
983             Gabor Szabo,
984             Graham Knop,
985             Mike Eldridge,
986             David Steinbrunner,
987             Kirk Kimmel,
988             Guillaume Aubert,
989             Dave Cross,
990             Anirvan Chatterjee,
991             Todd Rinaldo,
992             Graham Ollis,
993             Karen Etheridge,
994             Jonas Brømsø,
995             Olaf Alders,
996             Jim Keenan,
997             Slaven Rezić,
998             Szymon Nieznański.
999              
1000              
1001             =head1 AUTHOR
1002              
1003             Jeffrey Ryan Thalhammer <jeff@imaginative-software.com>
1004              
1005              
1006             =head1 COPYRIGHT
1007              
1008             Copyright (c) 2005-2022 Imaginative Software Systems. All rights reserved.
1009              
1010             This program is free software; you can redistribute it and/or modify it under
1011             the same terms as Perl itself. The full text of this license can be found in
1012             the LICENSE file included with this module.
1013              
1014             =cut
1015              
1016             ##############################################################################
1017             # Local Variables:
1018             # mode: cperl
1019             # cperl-indent-level: 4
1020             # fill-column: 78
1021             # indent-tabs-mode: nil
1022             # c-indentation-style: bsd
1023             # End:
1024             # ex: set ts=8 sts=4 sw=4 tw=78 ft=perl expandtab shiftround :