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