Login
Add new policy Variables::ProhibitMatchVars
[gknop/Perl-Critic.git] / lib / Perl / Critic.pm
CommitLineData
aaa8512c
JRT
1#######################################################################
2# $URL$
3# $Date$
4# $Author$
5# $Revision$
6########################################################################
7
59b05e08
JRT
8package Perl::Critic;
9
10use strict;
11use warnings;
12use File::Spec;
13use English qw(-no_match_vars);
14use Perl::Critic::Config;
15use Perl::Critic::Utils;
16use Carp;
17use PPI;
18
9ad4bbe8 19our $VERSION = '0.14';
59b05e08
JRT
20$VERSION = eval $VERSION; ## no critic
21
22#----------------------------------------------------------------------------
dff08b70 23
59b05e08 24sub new {
59b05e08 25 my ( $class, %args ) = @_;
59b05e08 26 my $self = bless {}, $class;
dff08b70 27
1e7b8681
JRT
28 $self->{_force} = $args{-force} || 0;
29 $self->{_config} = $args{-config} || Perl::Critic::Config->new( %args );
59b05e08
JRT
30 return $self;
31}
32
33#----------------------------------------------------------------------------
59b05e08 34
dff08b70
JRT
35sub config {
36 my $self = shift;
37 return $self->{_config};
38}
59b05e08 39
dff08b70 40#----------------------------------------------------------------------------
59b05e08 41
dff08b70
JRT
42sub add_policy {
43 my ( $self, @args ) = @_;
44 #Delegate to Perl::Critic::Config
45 return $self->config()->add_policy( @args );
46}
59b05e08 47
dff08b70
JRT
48#----------------------------------------------------------------------------
49
50sub policies {
51 my $self = shift;
52 #Delegate to Perl::Critic::Config
53 return $self->config()->policies();
59b05e08
JRT
54}
55
56#----------------------------------------------------------------------------
dff08b70 57
59b05e08 58sub critique {
7ed796a7 59
59b05e08
JRT
60 # Here we go!
61 my ( $self, $source_code ) = @_;
62
63 # Parse the code
64 my $doc = PPI::Document->new($source_code);
65
66 # Bail on error
7ed796a7
JRT
67 if ( !defined $doc ) {
68 my $errstr = PPI::Document::errstr();
69 my $file = -f $source_code ? $source_code : 'stdin';
70 die qq{Cannot parse code: $errstr of '$file'\n};
59b05e08
JRT
71 }
72
73 # Pre-index location of each node (for speed)
74 $doc->index_locations();
75
7ed796a7
JRT
76 # keys of hash are line numbers to ignore for violations
77 my %is_line_disabled;
59b05e08
JRT
78
79 # Remove the magic shebang fix
7ed796a7 80 %is_line_disabled = ( %is_line_disabled, _unfix_shebang($doc) );
59b05e08 81
7ed796a7
JRT
82 # Filter exempt code, if desired
83 if ( !$self->{_force} ) {
84 %is_line_disabled = ( %is_line_disabled, _filter_code($doc) );
85 }
1e7b8681 86
7ed796a7
JRT
87 # Run engine, testing each Policy at each element
88 my %types = ( 'PPI::Document' => [$doc],
89 'PPI::Element' => $doc->find('PPI::Element') || [], );
bf159007 90 my @violations;
7ed796a7
JRT
91 my @pols = @{ $self->policies() };
92 @pols || return; #Nothing to do!
93 for my $pol (@pols) {
bf159007 94 for my $type ( $pol->applies_to() ) {
7ed796a7
JRT
95 $types{$type}
96 ||= [ grep { $_->isa($type) } @{ $types{'PPI::Element'} } ];
97 push @violations, grep { !$is_line_disabled{ $_->location->[0] } }
98 map { $pol->violates( $_, $doc ) } @{ $types{$type} };
bf159007
JRT
99 }
100 }
7ed796a7 101 return Perl::Critic::Violation->sort_by_location(@violations);
59b05e08
JRT
102}
103
59b05e08
JRT
104#============================================================================
105#PRIVATE SUBS
106
107sub _filter_code {
108
109 my $doc = shift;
110 my $nodes_ref = $doc->find('PPI::Token::Comment') || return;
111 my $no_critic = qr{\A \s* \#\# \s* no \s+ critic}mx;
112 my $use_critic = qr{\A \s* \#\# \s* use \s+ critic}mx;
113
7ed796a7
JRT
114 my %disabled_lines;
115
59b05e08
JRT
116 PRAGMA:
117 for my $pragma ( grep { $_ =~ $no_critic } @{$nodes_ref} ) {
118
209eb6db
JRT
119 my $parent = $pragma->parent();
120 my $grandparent = $parent ? $parent->parent() : undef;
121 my $sib = $pragma->sprevious_sibling();
122
123 # Handle single-line usage on simple statements
124 if ( $sib && $sib->location->[0] == $pragma->location->[0] ) {
125 $disabled_lines{ $pragma->location->[0] } = 1;
126 next PRAGMA;
127 }
128
129
130 # Handle single-line usage on compound statements
131 if ( ref $parent eq 'PPI::Structure::Block' ) {
132 if ( ref $grandparent eq 'PPI::Statement::Compound' ) {
133 if ( $parent->location->[0] == $pragma->location->[0] ) {
134 $disabled_lines{ $grandparent->location->[0] } = 1;
135 #$disabled_lines{ $parent->location->[0] } = 1;
136 next PRAGMA;
137 }
59b05e08
JRT
138 }
139 }
140
209eb6db
JRT
141
142 # Handle multi-line usage. This is either a "no critic" ..
143 # "use critic" region or a block where "no critic" persists
144 # until the end of the scope. The start is the always the "no
145 # critic" which we already found. So now we have to search
146 # for the end.
7ed796a7
JRT
147
148 my $start = $pragma;
149 my $end = $pragma;
150
59b05e08 151 SIB:
7ed796a7
JRT
152 while ( my $sib = $end->next_sibling() ) {
153 $end = $sib; # keep track of last sibling encountered in this scope
154 last SIB
155 if $sib->isa('PPI::Token::Comment') && $sib =~ $use_critic;
156 }
157
158 # We either found an end or hit the end of the scope.
159 # Flag all intervening lines
160 for my $line ( $start->location->[0] .. $end->location->[0] ) {
161 $disabled_lines{$line} = 1;
59b05e08 162 }
59b05e08 163 }
dff08b70 164
7ed796a7 165 return %disabled_lines;
59b05e08 166}
dff08b70 167
7ed796a7
JRT
168#----------------------------------------------------------------------------
169
59b05e08
JRT
170sub _unfix_shebang {
171
7ed796a7
JRT
172 #When you install a script using ExtUtils::MakeMaker or
173 #Module::Build, it inserts some magical code into the top of the
174 #file (just after the shebang). This code allows people to call
175 #your script using a shell, like `sh my_script`. Unfortunately,
176 #this code causes several Policy violations, so we just remove it.
59b05e08 177
7ed796a7 178 my $doc = shift;
59b05e08
JRT
179 my $first_stmnt = $doc->schild(0) || return;
180
7ed796a7
JRT
181 #Different versions of MakeMaker and Build use slightly differnt
182 #shebang fixing strings. This matches most of the ones I've found
183 #in my own Perl distribution, but it may not be bullet-proof.
59b05e08
JRT
184
185 my $fixin_rx = qr{^eval 'exec .* \$0 \${1\+"\$@"}'\s*[\r\n]\s*if.+;};
7ed796a7
JRT
186 if ( $first_stmnt =~ $fixin_rx ) {
187 my $line = $first_stmnt->location->[0];
188 return ( $line => 1, $line + 1 => 1 );
189 }
dff08b70 190
7ed796a7 191 return;
59b05e08
JRT
192}
193
1941;
195
196#----------------------------------------------------------------------------
197
198__END__
199
200=pod
201
202=head1 NAME
203
6ef8f5d3 204Perl::Critic - Critique Perl source code for best-practices
59b05e08
JRT
205
206=head1 SYNOPSIS
207
208 use Perl::Critic;
6bf9b465
JRT
209 my $file = shift;
210 my $critic = Perl::Critic->new();
211 my @violations = $critic->critique($file);
212 print @violations;
59b05e08
JRT
213
214=head1 DESCRIPTION
215
216Perl::Critic is an extensible framework for creating and applying
217coding standards to Perl source code. Essentially, it is a static
218source code analysis engine. Perl::Critic is distributed with a
219number of L<Perl::Critic::Policy> modules that attempt to enforce
1e7b8681 220various coding guidelines. Most Policy modules are based on Damian
6bf9b465
JRT
221Conway's book B<Perl Best Practices>. You can enable, disable, and
222customize those Polices through the Perl::Critic interface. You can
223also create new Policy modules that suit your own tastes.
59b05e08
JRT
224
225For a convenient command-line interface to Perl::Critic, see the
226documentation for L<perlcritic>. If you want to integrate
1e7b8681 227Perl::Critic with your build process, L<Test::Perl::Critic> provides
0304068a
JRT
228an interface that is suitable for test scripts. For the ultimate
229convenience (at the expense of some flexibility) see the L<criticism>
230pragma.
231
232Win32 and ActvePerl users can find PPM distributions of Perl::Critic
233at L<http://theoryx5.uwinnipeg.ca/ppms/>.
59b05e08
JRT
234
235=head1 CONSTRUCTOR
236
237=over 8
238
e442ceaf 239=item C<new( -profile =E<gt> $FILE, -severity =E<gt> $N, -include =E<gt> \@PATTERNS, -exclude =E<gt> \@PATTERNS, -force =E<gt> 1 )>
59b05e08
JRT
240
241Returns a reference to a new Perl::Critic object. Most arguments are
242just passed directly into L<Perl::Critic::Config>, but I have described
243them here as well. All arguments are optional key-value pairs as
244follows:
245
246B<-profile> is a path to a configuration file. If C<$FILE> is not
247defined, Perl::Critic::Config attempts to find a F<.perlcriticrc>
248configuration file in the current directory, and then in your home
249directory. Alternatively, you can set the C<PERLCRITIC> environment
250variable to point to a file in another location. If a configuration
6bf9b465
JRT
251file can't be found, or if C<$FILE> is an empty string, then all
252Policies will be loaded with their default configuration. See
253L<"CONFIGURATION"> for more information.
1e7b8681
JRT
254
255B<-severity> is the minimum severity level. Only Policy modules that
6bf9b465
JRT
256have a severity greater than C<$N> will be loaded. Severity values
257are integers ranging from 1 (least severe) to 5 (most severe). The
258default is 5. For a given C<-profile>, decreasing the C<-severity>
259will usually result in more Policy violations. Users can redefine the
260severity level for any Policy in their F<.perlcriticrc> file. See
261L<"CONFIGURATION"> for more information.
262
263B<-include> is a reference to a list of string C<@PATTERNS>. Policy
264modules that match at least one C<m/$PATTERN/imx> will always be
265loaded, irrespective of the severity settings. For example:
266
267 my $critic = Perl::Critic->new(-include => ['layout'] -severity => 4);
268
269This would cause Perl::Critic to load all the C<CodeLayout::*> Policy
270modules even though they have a severity level that is less than 4.
271You can use C<-include> in conjunction with the C<-exclude> option.
272Note that C<-exclude> takes precedence over C<-include> when a Policy
273matches both patterns.
274
275B<-exclude> is a reference to a list of string C<@PATTERNS>. Policy
276modules that match at least one C<m/$PATTERN/imx> will not be loaded,
277irrespective of the severity settings. For example:
278
279 my $critic = Perl::Critic->new(-exclude => ['strict'] -severity => 1);
280
281This would cause Perl::Critic to not load the C<RequireUseStrict> and
282C<ProhibitNoStrict> Policy modules even though they have a severity
283level that is greater than 1. You can use C<-exclude> in conjunction
284with the C<-include> option. Note that C<-exclude> takes precedence
285over C<-include> when a Policy matches both patterns.
286
287B<-force> controls whether Perl::Critic observes the magical C<"## no
59b05e08
JRT
288critic"> pseudo-pragmas in your code. If set to a true value,
289Perl::Critic will analyze all code. If set to a false value (which is
6bf9b465 290the default) Perl::Critic will ignore code that is tagged with these
59b05e08
JRT
291comments. See L<"BENDING THE RULES"> for more information.
292
58e3f828 293B<-config> is a reference to a L<Perl::Critic::Config> object. If you
6bf9b465
JRT
294have created your own Config object for some reason, you can pass it
295in here instead of having Perl::Critic create one for you. Using the
54c10e6b 296C<-config> option causes all the other options to be silently ignored.
58e3f828 297
59b05e08
JRT
298=back
299
300=head1 METHODS
301
302=over 8
303
6d9feae6 304=item C<critique( $source_code )>
1e7b8681
JRT
305
306Runs the C<$source_code> through the Perl::Critic engine using all the
307Policies that have been loaded into this engine. If C<$source_code>
308is a scalar reference, then it is treated as string of actual Perl
309code. Otherwise, it is treated as a path to a file containing Perl
310code. Returns a list of L<Perl::Critic::Violation> objects for each
311violation of the loaded Policies. The list is sorted in the order
312that the Violations appear in the code. If there are no violations,
313returns an empty list.
314
a1f26155 315=item C<add_policy( -policy =E<gt> $policy_name, -config =E<gt> \%config_hash )>
59b05e08 316
54c10e6b 317Creates a Policy object and loads it into this Critic. If the object
1e7b8681 318cannot be instantiated, it will throw a warning and return a false
6bf9b465 319value. Otherwise, it returns a reference to this Critic.
59b05e08
JRT
320
321B<-policy> is the name of a L<Perl::Critic::Policy> subclass
322module. The C<'Perl::Critic::Policy'> portion of the name can be
323omitted for brevity. This argument is required.
324
325B<-config> is an optional reference to a hash of Policy configuration
54c10e6b
JRT
326parameters. Note that this is B<not> the same thing as a
327L<Perl::Critic::Config object>. The contents of this hash reference
328will be passed into to the constructor of the Policy module. See the
329documentation in the relevant Policy module for a description of the
330arguments it supports.
59b05e08 331
6d9feae6 332=item C<policies()>
59b05e08
JRT
333
334Returns a list containing references to all the Policy objects that
335have been loaded into this engine. Objects will be in the order that
336they were loaded.
337
6d9feae6 338=item C<config()>
dff08b70 339
54c10e6b
JRT
340Returns the L<Perl::Critic::Config> object that was created for or given
341to this Critic.
dff08b70 342
59b05e08
JRT
343=back
344
345=head1 CONFIGURATION
346
347The default configuration file is called F<.perlcriticrc>.
1e7b8681
JRT
348Perl::Critic will look for this file in the current directory first,
349and then in your home directory. Alternatively, you can set the
350PERLCRITIC environment variable to explicitly point to a different
59b05e08 351file in another location. If none of these files exist, and the
1e7b8681
JRT
352C<-profile> option is not given to the constructor, then all the
353modules that are found in the Perl::Critic::Policy namespace will be
354loaded with their default configuration.
59b05e08 355
6bf9b465
JRT
356The format of the configuration file is a series of INI-style sections
357that contain key-value pairs separated by '='. Comments should start
358with '#' and can be placed on a separate line or after the name-value
359pairs if you desire. The general recipe is a series of blocks like
360this:
59b05e08 361
7ed796a7
JRT
362 [Perl::Critic::Policy::Category::PolicyName]
363 severity = 1
364 arg1 = value1
365 arg2 = value2
59b05e08
JRT
366
367C<Perl::Critic::Policy::Category::PolicyName> is the full name of a
368module that implements the policy. The Policy modules distributed
369with Perl::Critic have been grouped into categories according to the
370table of contents in Damian Conway's book B<Perl Best Practices>. For
b2c7354a 371brevity, you can omit the C<'Perl::Critic::Policy'> part of the
6bf9b465 372module name.
59b05e08 373
1e7b8681
JRT
374C<severity> is the level of importance you wish to assign to the
375Policy. All Policy modules are defined with a default severity value
376ranging from 1 (least severe) to 5 (most severe). However, you may
377disagree with the default severity and choose to give it a higher or
378lower severity, based on your own coding philosophy.
59b05e08
JRT
379
380The remaining key-value pairs are configuration parameters for that
6bf9b465
JRT
381will be passed into the constructor that Policy. The constructors for
382most Policy modules do not support arguments, and those that do should
383have reasonable defaults. See the documentation on the appropriate
384Policy module for more details.
59b05e08 385
6bf9b465
JRT
386Instead of redefining the severity for a given Policy, you can
387completely disable a Policy by prepending a '-' to the name of the
388module in your configuration file. In this manner, the Policy will
389never be loaded, regardless of the C<-severity> given to the
390Perl::Critic constructor.
59b05e08
JRT
391
392A simple configuration might look like this:
393
7ed796a7
JRT
394 #--------------------------------------------------------------
395 # I think these are really important, so always load them
59b05e08 396
3878b20f 397 [TestingAndDebugging::RequireUseStrict]
7ed796a7 398 severity = 5
59b05e08 399
3878b20f 400 [TestingAndDebugging::RequireUseWarnings]
7ed796a7 401 severity = 5
59b05e08 402
7ed796a7
JRT
403 #--------------------------------------------------------------
404 # I think these are less important, so only load when asked
59b05e08 405
7ed796a7
JRT
406 [Variables::ProhibitPackageVars]
407 severity = 2
59b05e08 408
7ed796a7
JRT
409 [ControlStructures::ProhibitPostfixControls]
410 allow = if unless #My custom configuration
411 severity = 2
59b05e08 412
7ed796a7
JRT
413 #--------------------------------------------------------------
414 # I do not agree with these at all, so never load them
59b05e08 415
7ed796a7
JRT
416 [-NamingConventions::ProhibitMixedCaseVars]
417 [-NamingConventions::ProhibitMixedCaseSubs]
59b05e08 418
7ed796a7
JRT
419 #--------------------------------------------------------------
420 # For all other Policies, I accept the default severity,
421 # so no additional configuration is required for them.
1e7b8681 422
8bc162ba 423
6bf9b465
JRT
424A few sample configuration files are included in this distribution
425under the F<t/samples> directory. The F<perlcriticrc.none> file
426demonstrates how to disable Policy modules. The
427F<perlcriticrc.levels> file demonstrates how to redefine the severity
428level for any given Policy module. The F<perlcriticrc.pbp> file
429configures Perl::Critic to load only Policies described in Damian
430Conway's book "Perl Best Practice."
431
59b05e08
JRT
432=head1 THE POLICIES
433
434The following Policy modules are distributed with Perl::Critic. The
435Policy modules have been categorized according to the table of
436contents in Damian Conway's book B<Perl Best Practices>. Since most
437coding standards take the form "do this..." or "don't do that...", I
438have adopted the convention of naming each module C<RequireSomething>
8bc162ba
JRT
439or C<ProhibitSomething>. Each Policy is listed here with it's default
440severity. If you don't agree with the default severity, you can
441change it in your F<.perlcriticrc> file. See the documentation of
442each module for it's specific details.
59b05e08
JRT
443
444=head2 L<Perl::Critic::Policy::BuiltinFunctions::ProhibitLvalueSubstr>
445
8bc162ba 446Use 4-argument C<substr> instead of writing C<substr($foo, 2, 6) = $bar> [Severity 3]
59b05e08
JRT
447
448=head2 L<Perl::Critic::Policy::BuiltinFunctions::ProhibitSleepViaSelect>
449
8bc162ba 450Use L<Time::HiRes> instead of something like C<select(undef, undef, undef, .05)> [Severity 5]
59b05e08
JRT
451
452=head2 L<Perl::Critic::Policy::BuiltinFunctions::ProhibitStringyEval>
453
8bc162ba 454Write C<eval { my $foo; bar($foo) }> instead of C<eval "my $foo; bar($foo);"> [Severity 5]
59b05e08
JRT
455
456=head2 L<Perl::Critic::Policy::BuiltinFunctions::RequireBlockGrep>
457
8bc162ba 458Write C<grep { $_ =~ /$pattern/ } @list> instead of C<grep /$pattern/, @list> [Severity 4]
59b05e08
JRT
459
460=head2 L<Perl::Critic::Policy::BuiltinFunctions::RequireBlockMap>
461
8bc162ba 462Write C<map { $_ =~ /$pattern/ } @list> instead of C<map /$pattern/, @list> [Severity 4]
59b05e08
JRT
463
464=head2 L<Perl::Critic::Policy::BuiltinFunctions::RequireGlobFunction>
465
8bc162ba 466Use C<glob q{*}> instead of <*> [Severity 5]
59b05e08
JRT
467
468=head2 L<Perl::Critic::Policy::ClassHierarchies::ProhibitOneArgBless>
469
8bc162ba 470Write C<bless {}, $class;> instead of just C<bless {};> [Severity 5]
59b05e08
JRT
471
472=head2 L<Perl::Critic::Policy::CodeLayout::ProhibitHardTabs>
473
8bc162ba 474Use spaces instead of tabs. [Severity 3]
59b05e08
JRT
475
476=head2 L<Perl::Critic::Policy::CodeLayout::ProhibitParensWithBuiltins>
477
8bc162ba 478Write C<open $handle, $path> instead of C<open($handle, $path)> [Severity 1]
59b05e08
JRT
479
480=head2 L<Perl::Critic::Policy::CodeLayout::ProhibitQuotedWordLists>
481
8bc162ba 482Write C<qw(foo bar baz)> instead of C<('foo', 'bar', 'baz')> [Severity 2]
59b05e08
JRT
483
484=head2 L<Perl::Critic::Policy::CodeLayout::RequireTidyCode>
485
8bc162ba 486Must run code through L<perltidy>. [Severity 1]
59b05e08
JRT
487
488=head2 L<Perl::Critic::Policy::CodeLayout::RequireTrailingCommas>
489
8bc162ba 490Put a comma at the end of every multi-line list declaration, including the last one. [Severity 1]
59b05e08
JRT
491
492=head2 L<Perl::Critic::Policy::ControlStructures::ProhibitCascadingIfElse>
493
8bc162ba 494Don't write long "if-elsif-elsif-elsif-elsif...else" chains. [Severity 3]
59b05e08
JRT
495
496=head2 L<Perl::Critic::Policy::ControlStructures::ProhibitCStyleForLoops>
497
8bc162ba 498Write C<for(0..20)> instead of C<for($i=0; $i<=20; $i++)> [Severity 2]
59b05e08
JRT
499
500=head2 L<Perl::Critic::Policy::ControlStructures::ProhibitPostfixControls>
501
8bc162ba 502Write C<if($condition){ do_something() }> instead of C<do_something() if $condition> [Severity 2]
59b05e08
JRT
503
504=head2 L<Perl::Critic::Policy::ControlStructures::ProhibitUnlessBlocks>
505
8bc162ba 506Write C<if(! $condition)> instead of C<unless($condition)> [Severity 2]
59b05e08
JRT
507
508=head2 L<Perl::Critic::Policy::ControlStructures::ProhibitUntilBlocks>
509
8bc162ba 510Write C<while(! $condition)> instead of C<until($condition)> [Severity 2]
59b05e08
JRT
511
512=head2 L<Perl::Critic::Policy::InputOutput::ProhibitBacktickOperators>
513
8bc162ba 514Discourage stuff like C<@files = `ls $directory`> [Severity 3]
59b05e08
JRT
515
516=head2 L<Perl::Critic::Policy::InputOutput::ProhibitBarewordFileHandles>
517
8bc162ba 518Write C<open my $fh, q{<}, $filename;> instead of C<open FH, q{<}, $filename;> [Severity 5]
59b05e08
JRT
519
520=head2 L<Perl::Critic::Policy::InputOutput::ProhibitOneArgSelect>
521
8bc162ba 522Never write C<select($fh)> [Severity 4]
59b05e08
JRT
523
524=head2 L<Perl::Critic::Policy::InputOutput::ProhibitTwoArgOpen>
525
8bc162ba 526Write C<open $fh, q{<}, $filename;> instead of C<open $fh, "<$filename";> [Severity 5]
59b05e08
JRT
527
528=head2 L<Perl::Critic::Policy::Miscellanea::RequireRcsKeywords>
529
8bc162ba 530Put source-control keywords in every file. [Severity 2]
59b05e08
JRT
531
532=head2 L<Perl::Critic::Policy::Modules::ProhibitMultiplePackages>
533
8bc162ba 534Put packages (especially subclasses) in separate files. [Severity 4]
59b05e08
JRT
535
536=head2 L<Perl::Critic::Policy::Modules::RequireBarewordIncludes>
537
8bc162ba 538Write C<require Module> instead of C<require 'Module.pm'> [Severity 5]
59b05e08 539
ad77f8eb 540=head2 L<Perl::Critic::Policy::Modules::ProhibitEvilModules>
59b05e08 541
8bc162ba 542Ban modules that aren't blessed by your shop. [Severity 5]
59b05e08
JRT
543
544=head2 L<Perl::Critic::Policy::Modules::RequireExplicitPackage>
545
8bc162ba 546Always make the C<package> explicit. [Severity 4]
59b05e08
JRT
547
548=head2 L<Perl::Critic::Policy::Modules::RequireVersionVar>
549
8bc162ba 550Give every module a C<$VERSION> number. [Severity 2]
59b05e08 551
ad77f8eb 552=head2 L<Perl::Critic::Policy::Modules::RequireEndWithOne>
59b05e08 553
b2c7354a 554End each module with an explicitly C<1;> instead of some funky expression. [Severity 4]
59b05e08 555
ad77f8eb 556=head2 L<Perl::Critic::Policy::NamingConventions::ProhibitAmbiguousNames>
59b05e08 557
8bc162ba 558Don't use vague variable or subroutine names like 'last' or 'record'. [Severity 3]
59b05e08
JRT
559
560=head2 L<Perl::Critic::Policy::NamingConventions::ProhibitMixedCaseSubs>
561
8bc162ba 562Write C<sub my_function{}> instead of C<sub MyFunction{}> [Severity 1]
59b05e08
JRT
563
564=head2 L<Perl::Critic::Policy::NamingConventions::ProhibitMixedCaseVars>
565
8bc162ba 566Write C<$my_variable = 42> instead of C<$MyVariable = 42> [Severity 1]
59b05e08 567
8bc162ba 568=head2 L<Perl::Critic::Policy::References::ProhibitDoubleSigils>
ad77f8eb 569
8bc162ba 570Write C<@{ $array_ref }> instead of C<@$array_ref> [Severity 2]
ad77f8eb 571
8bc162ba 572=head2 L<Perl::Critic::Policy::RegularExpressions::RequireLineBoundaryMatching>
ad77f8eb 573
8bc162ba 574Always use the C</m> modifier with regular expressions. [Severity 3]
ad77f8eb 575
8bc162ba 576=head2 L<Perl::Critic::Policy::RegularExpressions::RequireExtendedFormatting>
ad77f8eb 577
8bc162ba 578Always use the C</x> modifier with regular expressions. [Severity 2]
ad77f8eb
JRT
579
580=head2 L<Perl::Critic::Policy::Subroutines::ProhibitAmpersandSigils>
581
8bc162ba 582Don't call functions with a leading ampersand sigil. [Severity 2]
ad77f8eb 583
59b05e08
JRT
584=head2 L<Perl::Critic::Policy::Subroutines::ProhibitBuiltinHomonyms>
585
8bc162ba 586Don't declare your own C<open> function. [Severity 4]
59b05e08 587
ad77f8eb
JRT
588=head2 L<Perl::Critic::Policy::Subroutines::ProhibitExcessComplexity>
589
8bc162ba 590Minimize complexity by factoring code into smaller subroutines. [Severity 3]
ad77f8eb 591
59b05e08
JRT
592=head2 L<Perl::Critic::Policy::Subroutines::ProhibitExplicitReturnUndef>
593
8bc162ba 594Return failure with bare C<return> instead of C<return undef> [Severity 5]
59b05e08
JRT
595
596=head2 L<Perl::Critic::Policy::Subroutines::ProhibitSubroutinePrototypes>
597
8bc162ba 598Don't write C<sub my_function (@@) {}> [Severity 5]
59b05e08 599
ad77f8eb
JRT
600=head2 L<Perl::Critic::Policy::Subroutines::RequireFinalReturn>
601
8bc162ba 602End every path through a subroutine with an explicit C<return> statement. [Severity 4]
ad77f8eb 603
3878b20f 604=head2 L<Perl::Critic::Policy::TestingAndDebugging::ProhibitNoStrict>
ad77f8eb 605
8bc162ba 606Prohibit various flavors of C<no strict> [Severity 5]
ad77f8eb 607
3878b20f 608=head2 L<Perl::Critic::Policy::TestingAndDebugging::ProhibitNoWarnings>
ad77f8eb 609
8bc162ba 610Prohibit various flavors of C<no warnings> [Severity 4]
ad77f8eb 611
3878b20f 612=head2 L<Perl::Critic::Policy::TestingAndDebugging::RequireUseStrict>
59b05e08 613
8bc162ba 614Always C<use strict> [Severity 5]
59b05e08 615
3878b20f 616=head2 L<Perl::Critic::Policy::TestingAndDebugging::RequireUseWarnings>
59b05e08 617
8bc162ba 618Always C<use warnings> [Severity 4]
59b05e08
JRT
619
620=head2 L<Perl::Critic::Policy::ValuesAndExpressions::ProhibitConstantPragma>
621
8bc162ba 622Don't C< use constant $FOO => 15 > [Severity 4]
59b05e08
JRT
623
624=head2 L<Perl::Critic::Policy::ValuesAndExpressions::ProhibitEmptyQuotes>
625
8bc162ba 626Write C<q{}> instead of C<''> [Severity 2]
59b05e08
JRT
627
628=head2 L<Perl::Critic::Policy::ValuesAndExpressions::ProhibitInterpolationOfLiterals>
629
8bc162ba 630Always use single quotes for literal strings. [Severity 1]
59b05e08
JRT
631
632=head2 L<Perl::Critic::Policy::ValuesAndExpressions::ProhibitLeadingZeros>
633
8bc162ba 634Write C<oct(755)> instead of C<0755> [Severity 5]
59b05e08
JRT
635
636=head2 L<Perl::Critic::Policy::ValuesAndExpressions::ProhibitNoisyQuotes>
637
8bc162ba 638Use C<q{}> or C<qq{}> instead of quotes for awkward-looking strings. [Severity 2]
59b05e08
JRT
639
640=head2 L<Perl::Critic::Policy::ValuesAndExpressions::RequireInterpolationOfMetachars>
641
8bc162ba 642Warns that you might have used single quotes when you really wanted double-quotes. [Severity 1]
59b05e08
JRT
643
644=head2 L<Perl::Critic::Policy::ValuesAndExpressions::RequireNumberSeparators>
645
8bc162ba 646Write C< 141_234_397.0145 > instead of C< 141234397.0145 > [Severity 2]
59b05e08
JRT
647
648=head2 L<Perl::Critic::Policy::ValuesAndExpressions::RequireQuotedHeredocTerminator>
649
8bc162ba 650Write C< print <<'THE_END' > or C< print <<"THE_END" > [Severity 3]
59b05e08
JRT
651
652=head2 L<Perl::Critic::Policy::ValuesAndExpressions::RequireUpperCaseHeredocTerminator>
653
8bc162ba 654Write C< <<'THE_END'; > instead of C< <<'theEnd'; > [Severity 1]
59b05e08
JRT
655
656=head2 L<Perl::Critic::Policy::Variables::ProhibitLocalVars>
657
8bc162ba 658Use C<my> instead of C<local>, except when you have to. [Severity 2]
59b05e08 659
b672fd9e
CD
660=head2 L<Perl::Critic::Policy::Variables::ProhibitMatchVars>
661
662Avoid C<$`>, C<$&>, C<$'> and their English equivalents. [Severity 4]
663
59b05e08
JRT
664=head2 L<Perl::Critic::Policy::Variables::ProhibitPackageVars>
665
8bc162ba 666Eliminate globals declared with C<our> or C<use vars> [Severity 3]
59b05e08
JRT
667
668=head2 L<Perl::Critic::Policy::Variables::ProhibitPunctuationVars>
669
8bc162ba 670Write C<$EVAL_ERROR> instead of C<$@> [Severity 2]
59b05e08
JRT
671
672=head1 BENDING THE RULES
673
59b05e08
JRT
674Perl::Critic takes a hard-line approach to your code: either you
675comply or you don't. In the real world, it is not always practical
676(or even possible) to fully comply with coding standards. In such
677cases, it is wise to show that you are knowingly violating the
678standards and that you have a Damn Good Reason (DGR) for doing so.
679
680To help with those situations, you can direct Perl::Critic to ignore
681certain lines or blocks of code by using pseudo-pragmas:
682
683 require 'LegacyLibaray1.pl'; ## no critic
684 require 'LegacyLibrary2.pl'; ## no critic
685
686 for my $element (@list) {
687
688 ## no critic
689
690 $foo = ""; #Violates 'ProhibitEmptyQuotes'
691 $barf = bar() if $foo; #Violates 'ProhibitPostfixControls'
692 #Some more evil code...
693
694 ## use critic
695
696 #Some good code...
697 do_something($_);
698 }
699
6bf9b465 700The C<"## no critic"> comments direct Perl::Critic to ignore the
59b05e08
JRT
701remaining lines of code until the end of the current block, or until a
702C<"## use critic"> comment is found (whichever comes first). If the
703C<"## no critic"> comment is on the same line as a code statement,
704then only that line of code is overlooked. To direct perlcritic to
705ignore the C<"## no critic"> comments, use the C<-force> option.
706
707Use this feature wisely. C<"## no critic"> should be used in the
708smallest possible scope, or only on individual lines of code. If
709Perl::Critic complains about your code, try and find a compliant
710solution before resorting to this feature.
711
21f4a0d3
JRT
712=head1 IMPORTANT CHANGES
713
714Perl-Critic is evolving rapidly. As such, some of the interfaces have
715changed in ways that are not backward-compatible. This will probably
716concern you only if you're developing L<Perl::Critic::Policy> modules.
717
718=head2 VERSION 0.11
719
720Starting in version 0.11, the internal mechanics of Perl-Critic were
721rewritten so that only one traversal of the PPI document tree is
722required. Unfortunately, this will break any custom Policy modules
723that you might have written for earlier versions. Converting your
724policies to work with the new version is pretty easy and actually
725results in cleaner code. See L<DEVELOPER.pod> for an up-to-date guide
726on creating Policy modules.
727
728=head2 VERSION 0.14
729
730Starting in version 0.14, the interface to L<Perl::Critic::Violation>
731changed. This will also break any custom Policy modules that you
732might have written for ealier modules. See L<DEVELOPER.pod> for an
733up-to-date guide on creating Policy modules.
734
735The notion of "priority" was also replaced with "severity" in version
7360.14. Consequently, the default behavior of Perl::Critic is to only
737load the most "severe" Policy modules, rather than loading all of
738them. This decision was based on user-feedback suggesting that
739Perl-Critic should be less "critical" for new users, and should steer
740them toward gradually increasing the strictness as they adopt better
741coding practices.
742
59b05e08
JRT
743=head1 EXTENDING THE CRITIC
744
745The modular design of Perl::Critic is intended to facilitate the
1e7b8681
JRT
746addition of new Policies. You'll need to have some understanding of
747L<PPI>, but most Policy modules are pretty straightforward and only
5ab86a86
JRT
748require about 20 lines of code. Please see the
749L<Perl::Critic::DEVELOPER> file included in this distribution for a
750step-by-step demonstration of how to create new Policy modules.
59b05e08
JRT
751
752If you develop any new Policy modules, feel free to send them to
753<thaljef@cpan.org> and I'll be happy to put them into the Perl::Critic
d66028df
JRT
754distribution. Or if you'd like to work on the Perl::Critic project
755directly, check out our repository at L<http://perlcritic.tigris.org>.
4d19da19
JRT
756To subscribe to our mailing list, send a message to
757C<dev-subscribe@perlcritic.tigris.org>.
59b05e08 758
59b05e08
JRT
759=head1 PREREQUISITES
760
761Perl::Critic requires the following modules:
762
59b05e08
JRT
763L<Config::Tiny>
764
765L<File::Spec>
766
1e7b8681
JRT
767L<IO::String>
768
59b05e08
JRT
769L<List::Util>
770
771L<List::MoreUtils>
772
1e7b8681
JRT
773L<Module::Pluggable>
774
775L<PPI>
776
59b05e08
JRT
777L<Pod::Usage>
778
779L<Pod::PlainText>
780
59b05e08
JRT
781L<String::Format>
782
783The following modules are optional, but recommended for complete
784testing:
785
786L<Test::Pod>
787
788L<Test::Pod::Coverage>
789
790L<Test::Perl::Critic>
791
792=head1 BUGS
793
794Scrutinizing Perl code is hard for humans, let alone machines. If you
795find any bugs, particularly false-positives or false-negatives from a
796Perl::Critic::Policy, please submit them to
797L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Perl-Critic>. Thanks.
798
799=head1 CREDITS
800
801Adam Kennedy - For creating L<PPI>, the heart and soul of Perl::Critic.
802
803Damian Conway - For writing B<Perl Best Practices>
804
805Giuseppe Maxia - For all the great ideas and enhancements.
806
807Chris Dolan - For numerous bug reports and suggestions.
808
809Sharon, my wife - For putting up with my all-night code sessions
810
811=head1 AUTHOR
812
813Jeffrey Ryan Thalhammer <thaljef@cpan.org>
814
815=head1 COPYRIGHT
816
c3c88e54 817Copyright (c) 2005-2006 Jeffrey Ryan Thalhammer. All rights reserved.
59b05e08
JRT
818
819This program is free software; you can redistribute it and/or modify
820it under the same terms as Perl itself. The full text of this license
821can be found in the LICENSE file included with this module.
822
823=cut