File Coverage

blib/lib/Perl/Critic.pm
Criterion Covered Total %
statement 93 96 96.8
branch 24 28 85.7
condition 10 15 66.6
subroutine 22 22 100.0
pod 6 6 100.0
total 155 167 92.8


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