blib/lib/Perl/Critic.pm

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