Login
Add new policy Variables::ProhibitMatchVars
[gknop/Perl-Critic.git] / bin / perlcritic
CommitLineData
59b05e08
JRT
1#!/usr/bin/perl
2
3915361f
JRT
3#######################################################################
4# $URL$
5# $Date$
6# $Author$
7# $Revision$
8########################################################################
9
59b05e08
JRT
10package main;
11
12use strict;
13use warnings;
14use Pod::Usage;
01625a50 15use File::Spec;
59b05e08
JRT
16use Getopt::Long;
17use English qw(-no_match_vars);
18use Perl::Critic::Utils;
59b05e08 19
db1213c6
JRT
20our $VERSION = 0.14;
21$VERSION = eval $VERSION; ## no critic
22
23#----------------------------------------------------------------------------
24# Globals
59b05e08 25
af1acfa2
JRT
26my %options = ();
27my @files = ();
28my $violations = [];
29my $status = undef;
59b05e08 30
db1213c6 31#-----------------------------------------------------------------------------
af1acfa2
JRT
32# Begin script. Only execute if not in a test harness
33
34if ( !$ENV{HARNESS_ACTIVE} ) {
35 %options = get_options();
36 @files = get_input(@ARGV);
37 $violations = critique(\%options, @files);
38 $status = $violations ? 2 : 0;
39 exit $status;
40}
59b05e08 41
db1213c6 42#-----------------------------------------------------------------------------
59b05e08
JRT
43# Begin subroutines
44
45sub get_options {
46
47 my %opts = ();
8bc162ba
JRT
48 my @opt_specs = qw(severity=i profile=s noprofile verbose=s force
49 help|? man Version Safari top:i 5 4 3 2 1 include=s@ exclude=s@);
59b05e08
JRT
50
51 Getopt::Long::Configure('no_ignore_case');
01625a50 52 GetOptions( \%opts, @opt_specs ) || pod2usage(); #Exits
59b05e08 53
01625a50
JRT
54 if ( $opts{help} ) { pod2usage( -verbose => 0 ) } #Exits
55 if ( $opts{man} ) { pod2usage( -verbose => 2 ) } #Exits
56 if ( $opts{Version} ) { print "$VERSION\n"; exit 0; } #Exits
59b05e08
JRT
57
58 #Sanity checks
59 if ( $opts{noprofile} && $opts{profile} ) {
60 my $msg = 'Cannot use -noprofile with -profile';
01625a50 61 pod2usage( -exitstatus => 1, -message => $msg ); #Exits
59b05e08
JRT
62 }
63
64 #Warn users who might forget that -verbose requires a value
65 if ( $opts{verbose} && $opts{verbose} !~ m{ (?: \d+ | %[fmlcdp] ) }mx ) {
6bf9b465
JRT
66 warn qq{Warning: -verbose argument '$opts{verbose}' looks odd.\n};
67 warn qq{Perhaps you meant to say '-verbose 3 $opts{verbose}'\n};
68 }
69
70 #Warn if -top is negative. They might have meant it as a severity
71 if ( $opts{top} && $opts{top} < 0 ) {
72 warn qq{Warning: -top argument '$opts{top}' is negative.\n};
73 warn qq{Perhaps you meant to say '$opts{top} -top'.\n};
d2843fb4
JRT
74 }
75
76 #Convert severity shortcut options. If multiple shortcuts
77 #are given, the lowest one wins, and -severity is ignored.
78 for ( 1 .. 5 ) {
8dd73375 79 if ( exists $opts{$_} ) {
d2843fb4
JRT
80 $opts{severity} = $_;
81 last;
82 }
59b05e08
JRT
83 }
84
efd06fc2
JRT
85 #If -top is specified, default the severity level to 1, unless an
86 #explicit severity is defined. This provides us flexibility to
87 #report top-offenders across just some or all of the severity levels.
af1acfa2
JRT
88 #We also default the -top count to twenty if non is given
89 if ( exists $opts{top} ) {
90 $opts{severity} ||= 1;
91 $opts{top} ||= 20;
92 }
e9273e97
JRT
93
94 #Override profile, if -noprofile is specified
af1acfa2
JRT
95 if ( exists $opts{noprofile} ) {
96 $opts{profile} = $EMPTY;
97 }
59b05e08 98
b1503201
JRT
99 #I've adopted the convention of using key-value pairs for
100 #arguments to most functions. And to increase legibility,
101 #I have also adopted the familiar command-line practice
102 #of denoting argument names with a leading dash (-).
103 my %dashed_opts = map { ( "-$_" => $opts{$_} ) } keys %opts;
104 return %dashed_opts;
59b05e08
JRT
105}
106
db1213c6 107#-----------------------------------------------------------------------------
1e7b8681 108
59b05e08
JRT
109sub get_input {
110
d2843fb4 111 if (@_) {
59b05e08 112
dfbe98be
JRT
113 for ( grep { ! -e $_ } @_ ) {
114 my $msg = qq{No such file or directory: '$_'};
115 pod2usage( -exitstatus => 1, -message => $msg, -verbose => 0);
116 }
117
8b76ab78
JRT
118 #Reading code from files or dirs. If argument is a file,
119 #then we process it as-is (even though it may not actually
120 #be Perl code). If argument is a directory, recursively
121 #search the directory for files that look like Perl code.
122 return map { -d $_ ? all_code_files($_) : $_ } @_;
59b05e08
JRT
123 }
124 else {
125
126 #Reading code from STDIN
127 my $code_string = do { local $RS; <STDIN> }; #Slurping
128 $code_string =~ m{ \S+ }mx || die 'Nothing to critique';
129 return \$code_string; #Convert to SCALAR ref for PPI
130 }
131}
132
db1213c6 133#-----------------------------------------------------------------------------
1e7b8681 134
59b05e08 135sub critique {
1e7b8681 136
d2843fb4 137 my ( $config, @files ) = @_;
59b05e08
JRT
138 my $count = 0;
139
db1213c6
JRT
140 # Perl::Critic has lots of dependencies, so loading is delayed
141 # until it is really needed. This hack reduces startup time for
142 # doing other things like getting the version number or dumping
143 # the man page. Arguably, those things are pretty rare, but hey,
144 # why not save a few seconds if you can.
145
146 eval {
f563053e 147
db1213c6
JRT
148 require Perl::Critic;
149 my $critic = Perl::Critic->new( %{$config} );
150
151 for my $file (@files) {
152 my @violations = $critic->critique($file);
153 render_report( $file, $config, @violations );
154 $count += scalar @violations;
155 }
156 };
157
158 die $EVAL_ERROR if $EVAL_ERROR;
59b05e08
JRT
159 return $count;
160}
161
db1213c6 162#------------------------------------------------------------------------------
59b05e08 163
7f2081ac
JRT
164sub render_report {
165
d2843fb4 166 my ( $file, $config, @violations ) = @_;
7f2081ac 167
59b05e08 168 $file = -f $file ? $file : 'stdin';
4d19da19 169 my $default_verbosity = @files > 1 ? 3 : 2; #@files is global!
b1503201 170 my $verbosity = $config->{-verbose} || $default_verbosity;
af1acfa2 171 my $top = $config->{-top};
1e7b8681 172
2bfd3a79
JRT
173 if( ! @violations ){
174 print "$file source OK\n";
175 return;
176 }
177
1e7b8681 178 my %FORMAT_OF = (
d2843fb4 179 1 => "%f:%l:%c:%m\n",
4d19da19
JRT
180 2 => "%m at line %l, column %c. %e. (Severity: %s)\n",
181 3 => "%f: %m at line %l, column %c. %e. (Severity: %s)\n",
182 4 => "%m near '%r'. (Severity: %s)\n",
183 5 => "%f: %m near '%r'. (Severity: %s)\n",
184 6 => "%m at line %l, column %c near '%r'. %e. (Severity: %s)\n",
185 7 => "%f: %m at line %l, column %c near '%r'. %e. (Severity: %s)\n",
186 8 => "[%p] %m at line %l, column %c near '%r'. %e. (Severity: %s)\n",
187 9 => "[%p] %m at line %l, column %c near '%r'. %e. (Severity: %s)\n%d\n",
59b05e08
JRT
188 );
189
d2843fb4
JRT
190 my $fmt =
191 $verbosity =~ m{ \A [+-]? \d+ \z }mx
192 ? ( $FORMAT_OF{ abs $verbosity } || $FORMAT_OF{2} )
193 : _interpolate($verbosity);
db1213c6
JRT
194 $fmt =~ s{\%f}{$file}mxg; #HACK! Violation objects don't know the file
195
59b05e08 196
db1213c6 197 no warnings 'once'; ## no critic
b7a569d9 198 local $Perl::Critic::Violation::FORMAT = $fmt;
7f2081ac 199
d2843fb4 200 if ( defined $top ) {
8dd73375
JRT
201 my $limit = @violations < $top ? $#violations : $top-1;
202 my @ranked = Perl::Critic::Violation::sort_by_severity(@violations);
203 my @top_offenders = ( reverse @ranked )[ 0 .. $limit ]; #Slicing...
d2843fb4 204 @violations = Perl::Critic::Violation::sort_by_location(@top_offenders);
7f2081ac
JRT
205 }
206
59b05e08 207 print @violations;
7f2081ac 208 return scalar @violations;
59b05e08
JRT
209}
210
db1213c6 211#-----------------------------------------------------------------------------
01625a50
JRT
212
213sub all_code_files {
214
215 # Recursively searches a list of directories and returns the paths
216 # to files that seem to be Perl source code. This subroutine was
217 # poached from Test::Perl::Critic.
218
219 my @queue = @_;
220 my @code_files = ();
221
222 while (@queue) {
223 my $file = shift @queue;
224 if ( -d $file ) {
225 opendir my ($dh), $file or next;
226 my @newfiles = readdir $dh;
227 closedir $dh;
228
229 @newfiles = File::Spec->no_upwards(@newfiles);
230 @newfiles = grep { $_ ne 'CVS' && $_ ne '.svn' } @newfiles;
231 push @queue, map { File::Spec->catfile($file, $_) } @newfiles;
232 }
233
234 if ( -f $file && _is_perl($file) ) {
235 push @code_files, $file;
236 }
237 }
238 return @code_files;
239}
240
db1213c6 241#-----------------------------------------------------------------------------
01625a50
JRT
242
243sub _is_perl {
244
245 # Returns true if the argument ends with a perl-ish file
246 # extension, or if it has a shebang-line containing 'perl' This
247 # subroutine was also poached from Test::Perl::Critic
248
249 my $file = shift;
250
251 #Check filename extensions
252 return 1 if $file =~ m{ [.] PL \z}mx;
253 return 1 if $file =~ m{ [.] p (?: l|m ) \z}mx;
254 return 1 if $file =~ m{ [.] t \z}mx;
255
256 #Check for shebang
61252a1f 257 open my ($fh), '<', $file or return;
01625a50
JRT
258 my $first = <$fh>;
259 close $fh;
260
261 return 1 if defined $first && ( $first =~ m{ \A \#!.*perl }mx );
262 return;
263}
264
265#-----------------------------------------------------------------------------
59b05e08 266sub _interpolate {
d2843fb4 267 my $literal = shift;
59b05e08 268 my $interpolated = undef;
01625a50 269 eval "\$interpolated = \"$literal\""; ## no critic
59b05e08
JRT
270 return $interpolated;
271}
272
2731;
274
275__END__
276
01625a50 277#-----------------------------------------------------------------------------
1e7b8681 278
59b05e08
JRT
279=pod
280
281=head1 NAME
282
c165f991 283C<perlcritic> - Command-line interface to critique Perl source
59b05e08
JRT
284
285=head1 SYNOPSIS
286
db1213c6
JRT
287 perlcritic [ -12345 | -severity number ] [ -noprofile | -profile file ]
288 [ -top [ number ]] [ -include pattern ] [ -exclude pattern ]
289 [ -verbose number | format ] [ -force ] [ -Version ]
290 [ -help ] [ -man ] [ FILE | DIRECTORY ]
59b05e08
JRT
291
292=head1 DESCRIPTION
293
294C<perlcritic> is a Perl source code analyzer. It is the executable
295front-end to the L<Perl::Critic> engine, which attempts to identify
296awkward, hard to read, error-prone, or unconventional constructs in
297your code. Most of the rules are based on Damian Conway's book B<Perl
25a6e413 298Best Practices>, but they can easily be configured or disabled to your
a0934394 299liking.
59b05e08 300
c165f991 301If you want to integrate C<perlcritic> with your build process, the
59b05e08 302L<Test::Perl::Critic> module provides a nice interface that is
0304068a
JRT
303suitable for test scripts. For ultimate convenience (at the expense
304of some flexibility) see the L<criticism> pragma.
305
306Win32 and ActvePerl users can find PPM distributions of Perl::Critic
307at L<http://theoryx5.uwinnipeg.ca/ppms/>.
59b05e08 308
d2843fb4
JRT
309=head1 USAGE EXAMPLES
310
25a6e413 311Before getting into all the gory details, here are some basic usage
b2c7354a 312examples to help get you started.
d2843fb4 313
6bf9b465 314 #Report only most severe violations (severity = 5)
25a6e413
JRT
315 perlcritic YourModule.pm
316
db1213c6
JRT
317 #Same as above, but read input from STDIN
318 perlcritic
319
320 #Recursively process all Perl files beneath directory
321 perlcritic /some/directory
d2843fb4 322
6bf9b465 323 #Report slightly less severe violations too (severity >= 4)
25a6e413 324 perlcritic -4 YourModule.pm
d2843fb4 325
6bf9b465 326 #Report all violations, regardless of severity (severity >= 1)
25a6e413 327 perlcritic -1 YourModule.pm
d2843fb4 328
6bf9b465 329 #Report top 20 most severe violations (severity >= 1)
25a6e413
JRT
330 perlcritic -top YourModule.pm
331
332 #Report top 20 violations with severity >= 3
333 perlcritic -3 -top YourModule.pm
d2843fb4 334
b2c7354a 335 #Report additional violations of Policies that match m/variables/ix
25a6e413 336 perlcritic -include variables YourModule.pm
d2843fb4 337
59b05e08
JRT
338=head1 ARGUMENTS
339
340The arguments are paths to the files you wish to analyze. You may
c165f991 341specify multiple files. If an argument is a directory, C<perlcritic>
01625a50
JRT
342will analyze all Perl files below the directory. If no arguments
343are specified, then input is read from STDIN.
59b05e08
JRT
344
345=head1 OPTIONS
346
347Option names can be abbreviated to uniqueness and can be stated with
348singe or double dashes, and option values can be separated from the
6bf9b465 349option name by a space or '=' (as with L<Getopt::Long>). Option names
25a6e413 350are also case-sensitive.
59b05e08
JRT
351
352=over 8
353
354=item -profile FILE
355
c165f991 356Directs C<perlcritic> to use a profile named by FILE rather than looking
59b05e08
JRT
357for the default F<.perlcriticrc> file in the current directory or your
358home directory. See L<"CONFIGURATION"> for more information.
359
360=item -noprofile
361
c165f991 362Directs C<perlcritic> not to load any configuration file, thus reverting
6bf9b465 363to the default configuration for all Policies.
59b05e08 364
1e7b8681 365=item -severity N
59b05e08 366
c165f991 367Directs C<perlcritic> to only report violations of Policies with a
13007aee 368severity greater than C<N>. Severity values are integers ranging from
6bf9b465
JRT
3691 (least severe) to 5 (most severe). The default is 5. For a given
370C<-profile>, decreasing the C<-severity> will usually produce more
371violations. Users can redefine the C<severity> for any Policy in
372their F<.perlcriticrc> file. See L<"CONFIGURATION"> for more
373information.
59b05e08 374
d2843fb4
JRT
375=item -5 | -4 | -3 | -2 | -1
376
377These are shortcuts for setting the C<-severity> option. For example
6bf9b465
JRT
378C<"-4"> is equivalent to C<"-severity 4">. Using one of these
379shortcuts causes an explicit C<-severity> option to be silently
b2c7354a 380ignored if it is given. If multiple shortcuts are specified, then the
6bf9b465 381lowest one wins. NOTE: Be careful not to put one of the severity
b60af65d 382shortcut options immediately after the C<-top> flag or C<perlcritic>
b2c7354a 383will interpret it as the number of violations to report.
d2843fb4 384
a0934394
JRT
385=item -top [ N ]
386
b60af65d
JRT
387Directs C<perlcritic> to report only the top C<N> Policy violations in
388each file, ranked by their severity. If C<N> is not specified, it
389defaults to 20. If the C<-severity> option (or one of the shortcuts)
390is not explicitly given, the C<-top> option implies that the minimum
391severity level is 1. Users can redefine the severity for any Policy in
392their F<.perlcriticrc> file. See L<"CONFIGURATION"> for more
393information. NOTE: Be careful not to put one of the severity shortcut
394options immediately after the C<-top> flag or C<perlcritic> will
395interpret it as the number of violations to report.
a0934394 396
59b05e08
JRT
397=item -include PATTERN
398
c165f991 399Directs C<perlcritic> to report additional violations of all Policy
6bf9b465
JRT
400modules that match the regex C</PATTERN/imx>. Use this option to
401temporarily override your profile and/or the severity settings at the
402command-line. For example:
403
404 perlcritic --include=layout my_file.pl
405
c165f991 406This would cause C<perlcritic> to report violations of all the
6bf9b465
JRT
407C<CodeLayout::*> policies even if they have a severity level that is
408less than the default level of 5, or have been disabled in your
409F<.perlcriticrc> file. You can specify multiple C<-include> options
410and you can use it in conjunction with the C<-exclude> option. Note
411that C<-exclude> takes precedence over C<-include> when a Policy
c5d8050b 412matches both patterns.
59b05e08
JRT
413
414=item -exclude PATTERN
415
c165f991
JRT
416Directs C<perlcritic> to not report violations of any Policy modules
417that match the regex C</PATTERN/imx>. Use this option to temporarily
6bf9b465
JRT
418override your profile and/or the severity settings at the
419command-line. For example:
420
421 perlcritic --exclude=strict my_file.pl
422
c165f991 423This would cause C<perlcritic> to not report violations of the
6bf9b465
JRT
424C<RequireUseStrict> and C<ProhibitNoStrict> policies even though they
425have a severity level that is greater than 1. You can specify
426multiple C<-exclude> options and you can use it in conjunction with
427the C<-include> option. Note that C<-exclude> takes precedence over
428C<-include> when a Policy matches both patterns.
59b05e08
JRT
429
430=item -force
431
c165f991 432Directs C<perlcritic> to ignore the magical C<## no critic>
59b05e08
JRT
433pseudo-pragmas in the source code. See L<"BENDING THE RULES"> for more
434information.
435
436=item -verbose N | FORMAT
437
438Sets the verbosity level or format for reporting violations. If given
c165f991 439a number (C<N>), C<perlcritic> reports violations using one of the
6bf9b465
JRT
440predefined formats described below. If given a string (C<FORMAT>), it
441is interpreted to be an actual format specification. If the
4d19da19 442C<-verbose> option is not specified, it defaults to either 2 or 3,
6bf9b465 443depending on whether multiple files were given as arguments to
c165f991 444C<perlcritic>.
59b05e08
JRT
445
446 Verbosity Format Specification
6bf9b465 447 ----------- --------------------------------------------------------------------
4d19da19
JRT
448 1 "%f:%l:%c:%m\n"
449 2 "%m at line %l, column %c. %e. (Severity: %s)\n"
450 3 "%f: %m at line %l, column %c. %e. (Severity: %s)\n"
451 4 "%m near '%r'. (Severity: %s)\n"
452 5 "%f: %m near '%r'. (Severity: %s)\n"
453 6 "%m at line %l, column %c near '%r'. %e. (Severity: %s)\n"
454 7 "%f: %m at line %l, column %c near '%r'. %e. (Severity: %s)\n"
455 8 "[%p] %m at line %l, column %c near '%r'. %e. (Severity: %s)\n"
456 9 "[%p] %m at line %l, column %c near '%r'. %e. (Severity: %s)\n%d\n"
59b05e08
JRT
457
458Formats are a combination of literal and escape characters similar to
459the way C<sprintf> works. See L<String::Format> for a full
460explanation of the formatting capabilities. Valid escape characters
461are:
462
463 Escape Meaning
6bf9b465 464 ------- ------------------------------------------------------------------------
59b05e08
JRT
465 %m Brief description of the violation
466 %f Name of the file where the violation occurred.
467 %l Line number where the violation occurred
468 %c Column number where the violation occurred
469 %e Explanation of violation or page numbers in PBP
470 %d Full diagnostic discussion of the violation
6bf9b465 471 %r The string of source code that caused the violation
59b05e08 472 %p Name of the Policy module that created the violation
6bf9b465 473 %s The severity level of the violation
59b05e08
JRT
474
475The purpose of these formats is to provide some compatibility with
476editors that have an interface for parsing certain kinds of input. See
477L<"EDITOR INTEGRATION"> for more information about that.
478
d2843fb4 479=item -Safari
59b05e08
JRT
480
481Report "Perl Best Practice" citations as section numbers from
482L<http://safari.oreilly.com> instead of page numbers from the actual
483book. NOTE: This feature is not implemented yet.
484
485=item -help
486
487=item -?
488
489Displays a brief summary of options and exits.
490
491=item -man
492
c165f991 493Displays the complete C<perlcritic> manual and exits.
59b05e08
JRT
494
495=item -Version
496
497=item -V
498
c165f991 499Displays the version number of C<perlcritic> and exits.
59b05e08
JRT
500
501=back
502
503=head1 CONFIGURATION
504
505The default configuration file is called F<.perlcriticrc>.
1e7b8681
JRT
506Perl::Critic::Config will look for this file in the current directory
507first, and then in your home directory. Alternatively, you can set
c165f991
JRT
508the C<PERLCRITIC> environment variable to explicitly point to a
509different file in another location. If none of these files exist, and
510the C<-profile> option is not given on the command line, then all
511Policies will be loaded with their default configuration.
59b05e08 512
6bf9b465
JRT
513The format of the configuration file is an series of INI-style
514sections that contain key-value pairs separated by '='. Comments
515should start with '#' and can be placed on a separate line or after
516the name-value pairs if you desire. The general recipe is a series of
59b05e08
JRT
517blocks like this:
518
519 [Perl::Critic::Policy::Category::PolicyName]
1e7b8681 520 severity = 1
59b05e08
JRT
521 arg1 = value1
522 arg2 = value2
523
524C<Perl::Critic::Policy::Category::PolicyName> is the full name of a
1e7b8681
JRT
525module that implements the policy. The Policy modules distributed
526with Perl::Critic have been grouped into categories according to the
527table of contents in Damian Conway's book B<Perl Best Practices>. For
b2c7354a 528brevity, you can omit the C<'Perl::Critic::Policy'> part of the
6bf9b465 529module name.
1e7b8681
JRT
530
531C<severity> is the level of importance you wish to assign to the
532Policy. All Policy modules are defined with a default severity value
533ranging from 1 (least severe) to 5 (most severe). However, you may
534disagree with the default severity and choose to give it a higher or
535lower severity, based on your own coding philosophy.
59b05e08 536
6bf9b465
JRT
537The remaining key-value pairs are configuration parameters that will
538be passed into the constructor of that Policy. The constructors for
539most Policy modules do not support arguments, and those that do should
540have reasonable defaults. See the documentation on the appropriate
541Policy module for more details.
59b05e08 542
6bf9b465
JRT
543Instead of redefining the severity for a given Policy, you can
544completely disable a Policy by prepending a '-' to the name of the
545module in your configuration file. In this manner, the Policy will
546never be loaded, regardless of the C<-severity> given on the
547command line.
59b05e08 548
1e7b8681 549A simple configuration might look like this:
59b05e08
JRT
550
551 #--------------------------------------------------------------
1e7b8681 552 # I think these are really important, so always load them
59b05e08 553
3878b20f 554 [TestingAndDebugging::RequireUseStrict]
1e7b8681 555 severity = 5
59b05e08 556
3878b20f 557 [TestingAndDebugging::RequireUseWarnings]
1e7b8681 558 severity = 5
59b05e08
JRT
559
560 #--------------------------------------------------------------
1e7b8681 561 # I think these are less important, so only load when asked
59b05e08
JRT
562
563 [Variables::ProhibitPackageVars]
1e7b8681 564 severity = 2
59b05e08
JRT
565
566 [ControlStructures::ProhibitPostfixControls]
1e7b8681
JRT
567 allow = if unless #My custom configuration
568 severity = 2
59b05e08
JRT
569
570 #--------------------------------------------------------------
1e7b8681 571 # I do not agree with these at all, so never load them
59b05e08
JRT
572
573 [-NamingConventions::ProhibitMixedCaseVars]
574 [-NamingConventions::ProhibitMixedCaseSubs]
575
1e7b8681
JRT
576 #--------------------------------------------------------------
577 # For all other Policies, I accept the default severity,
578 # so no additional configuration is required for them.
579
6bf9b465
JRT
580A few sample configuration files are included in this distribution
581under the F<t/samples> directory. The F<perlcriticrc.none> file
582demonstrates how to disable Policy modules. The
583F<perlcriticrc.levels> file demonstrates how to redefine the severity
584level for any given Policy module. The F<perlcriticrc.pbp> file
585configures Perl::Critic to load only Policies described in Damian
586Conway's book "Perl Best Practices."
587
59b05e08
JRT
588=head1 THE POLICIES
589
590The following Policy modules are distributed with Perl::Critic. The
591Policy modules have been categorized according to the table of
592contents in Damian Conway's book B<Perl Best Practices>. Since most
593coding standards take the form "do this..." or "don't do that...", I
594have adopted the convention of naming each module C<RequireSomething>
6bf9b465
JRT
595or C<ProhibitSomething>. Each Policy is listed here with it's default
596severity. If you don't agree with the default severity, you can
597change it in your F<.perlcriticrc> file. See the documentation of
598each module for it's specific details.
59b05e08
JRT
599
600=head2 L<Perl::Critic::Policy::BuiltinFunctions::ProhibitLvalueSubstr>
601
8bc162ba 602Use 4-argument C<substr> instead of writing C<substr($foo, 2, 6) = $bar> [Severity 3]
59b05e08
JRT
603
604=head2 L<Perl::Critic::Policy::BuiltinFunctions::ProhibitSleepViaSelect>
605
8bc162ba 606Use L<Time::HiRes> instead of something like C<select(undef, undef, undef, .05)> [Severity 5]
59b05e08
JRT
607
608=head2 L<Perl::Critic::Policy::BuiltinFunctions::ProhibitStringyEval>
609
8bc162ba 610Write C<eval { my $foo; bar($foo) }> instead of C<eval "my $foo; bar($foo);"> [Severity 5]
59b05e08
JRT
611
612=head2 L<Perl::Critic::Policy::BuiltinFunctions::RequireBlockGrep>
613
8bc162ba 614Write C<grep { $_ =~ /$pattern/ } @list> instead of C<grep /$pattern/, @list> [Severity 4]
59b05e08
JRT
615
616=head2 L<Perl::Critic::Policy::BuiltinFunctions::RequireBlockMap>
617
8bc162ba 618Write C<map { $_ =~ /$pattern/ } @list> instead of C<map /$pattern/, @list> [Severity 4]
59b05e08
JRT
619
620=head2 L<Perl::Critic::Policy::BuiltinFunctions::RequireGlobFunction>
621
8bc162ba 622Use C<glob q{*}> instead of <*> [Severity 5]
59b05e08
JRT
623
624=head2 L<Perl::Critic::Policy::ClassHierarchies::ProhibitOneArgBless>
625
8bc162ba 626Write C<bless {}, $class;> instead of just C<bless {};> [Severity 5]
59b05e08
JRT
627
628=head2 L<Perl::Critic::Policy::CodeLayout::ProhibitHardTabs>
629
8bc162ba 630Use spaces instead of tabs. [Severity 3]
59b05e08
JRT
631
632=head2 L<Perl::Critic::Policy::CodeLayout::ProhibitParensWithBuiltins>
633
8bc162ba 634Write C<open $handle, $path> instead of C<open($handle, $path)> [Severity 1]
59b05e08
JRT
635
636=head2 L<Perl::Critic::Policy::CodeLayout::ProhibitQuotedWordLists>
637
8bc162ba 638Write C<qw(foo bar baz)> instead of C<('foo', 'bar', 'baz')> [Severity 2]
59b05e08
JRT
639
640=head2 L<Perl::Critic::Policy::CodeLayout::RequireTidyCode>
641
8bc162ba 642Must run code through L<perltidy>. [Severity 1]
59b05e08
JRT
643
644=head2 L<Perl::Critic::Policy::CodeLayout::RequireTrailingCommas>
645
8bc162ba 646Put a comma at the end of every multi-line list declaration, including the last one. [Severity 1]
59b05e08
JRT
647
648=head2 L<Perl::Critic::Policy::ControlStructures::ProhibitCascadingIfElse>
649
8bc162ba 650Don't write long "if-elsif-elsif-elsif-elsif...else" chains. [Severity 3]
59b05e08
JRT
651
652=head2 L<Perl::Critic::Policy::ControlStructures::ProhibitCStyleForLoops>
653
8bc162ba 654Write C<for(0..20)> instead of C<for($i=0; $i<=20; $i++)> [Severity 2]
59b05e08
JRT
655
656=head2 L<Perl::Critic::Policy::ControlStructures::ProhibitPostfixControls>
657
8bc162ba 658Write C<if($condition){ do_something() }> instead of C<do_something() if $condition> [Severity 2]
59b05e08
JRT
659
660=head2 L<Perl::Critic::Policy::ControlStructures::ProhibitUnlessBlocks>
661
8bc162ba 662Write C<if(! $condition)> instead of C<unless($condition)> [Severity 2]
59b05e08
JRT
663
664=head2 L<Perl::Critic::Policy::ControlStructures::ProhibitUntilBlocks>
665
8bc162ba 666Write C<while(! $condition)> instead of C<until($condition)> [Severity 2]
59b05e08
JRT
667
668=head2 L<Perl::Critic::Policy::InputOutput::ProhibitBacktickOperators>
669
8bc162ba 670Discourage stuff like C<@files = `ls $directory`> [Severity 3]
59b05e08
JRT
671
672=head2 L<Perl::Critic::Policy::InputOutput::ProhibitBarewordFileHandles>
673
8bc162ba 674Write C<open my $fh, q{<}, $filename;> instead of C<open FH, q{<}, $filename;> [Severity 5]
59b05e08
JRT
675
676=head2 L<Perl::Critic::Policy::InputOutput::ProhibitOneArgSelect>
677
8bc162ba 678Never write C<select($fh)> [Severity 4]
59b05e08
JRT
679
680=head2 L<Perl::Critic::Policy::InputOutput::ProhibitTwoArgOpen>
681
8bc162ba 682Write C<open $fh, q{<}, $filename;> instead of C<open $fh, "<$filename";> [Severity 5]
59b05e08
JRT
683
684=head2 L<Perl::Critic::Policy::Miscellanea::RequireRcsKeywords>
685
8bc162ba 686Put source-control keywords in every file. [Severity 2]
59b05e08
JRT
687
688=head2 L<Perl::Critic::Policy::Modules::ProhibitMultiplePackages>
689
8bc162ba 690Put packages (especially subclasses) in separate files. [Severity 4]
59b05e08
JRT
691
692=head2 L<Perl::Critic::Policy::Modules::RequireBarewordIncludes>
693
8bc162ba 694Write C<require Module> instead of C<require 'Module.pm'> [Severity 5]
59b05e08 695
ad77f8eb 696=head2 L<Perl::Critic::Policy::Modules::ProhibitEvilModules>
59b05e08 697
8bc162ba 698Ban modules that aren't blessed by your shop. [Severity 5]
59b05e08
JRT
699
700=head2 L<Perl::Critic::Policy::Modules::RequireExplicitPackage>
701
8bc162ba 702Always make the C<package> explicit. [Severity 4]
59b05e08
JRT
703
704=head2 L<Perl::Critic::Policy::Modules::RequireVersionVar>
705
8bc162ba 706Give every module a C<$VERSION> number. [Severity 2]
59b05e08 707
ad77f8eb 708=head2 L<Perl::Critic::Policy::Modules::RequireEndWithOne>
59b05e08 709
b2c7354a 710End each module with an explicitly C<1;> instead of some funky expression. [Severity 4]
59b05e08 711
ad77f8eb 712=head2 L<Perl::Critic::Policy::NamingConventions::ProhibitAmbiguousNames>
59b05e08 713
8bc162ba 714Don't use vague variable or subroutine names like 'last' or 'record'. [Severity 3]
59b05e08
JRT
715
716=head2 L<Perl::Critic::Policy::NamingConventions::ProhibitMixedCaseSubs>
717
8bc162ba 718Write C<sub my_function{}> instead of C<sub MyFunction{}> [Severity 1]
59b05e08
JRT
719
720=head2 L<Perl::Critic::Policy::NamingConventions::ProhibitMixedCaseVars>
721
8bc162ba 722Write C<$my_variable = 42> instead of C<$MyVariable = 42> [Severity 1]
59b05e08 723
8bc162ba 724=head2 L<Perl::Critic::Policy::References::ProhibitDoubleSigils>
ad77f8eb 725
8bc162ba 726Write C<@{ $array_ref }> instead of C<@$array_ref> [Severity 2]
ad77f8eb 727
8bc162ba 728=head2 L<Perl::Critic::Policy::RegularExpressions::RequireLineBoundaryMatching>
ad77f8eb 729
8bc162ba 730Always use the C</m> modifier with regular expressions. [Severity 3]
ad77f8eb 731
8bc162ba 732=head2 L<Perl::Critic::Policy::RegularExpressions::RequireExtendedFormatting>
ad77f8eb 733
8bc162ba 734Always use the C</x> modifier with regular expressions. [Severity 2]
ad77f8eb
JRT
735
736=head2 L<Perl::Critic::Policy::Subroutines::ProhibitAmpersandSigils>
737
8bc162ba 738Don't call functions with a leading ampersand sigil. [Severity 2]
ad77f8eb 739
59b05e08
JRT
740=head2 L<Perl::Critic::Policy::Subroutines::ProhibitBuiltinHomonyms>
741
8bc162ba 742Don't declare your own C<open> function. [Severity 4]
59b05e08 743
ad77f8eb
JRT
744=head2 L<Perl::Critic::Policy::Subroutines::ProhibitExcessComplexity>
745
8bc162ba 746Minimize complexity by factoring code into smaller subroutines. [Severity 3]
ad77f8eb 747
59b05e08
JRT
748=head2 L<Perl::Critic::Policy::Subroutines::ProhibitExplicitReturnUndef>
749
8bc162ba 750Return failure with bare C<return> instead of C<return undef> [Severity 5]
59b05e08
JRT
751
752=head2 L<Perl::Critic::Policy::Subroutines::ProhibitSubroutinePrototypes>
753
8bc162ba 754Don't write C<sub my_function (@@) {}> [Severity 5]
59b05e08 755
ad77f8eb
JRT
756=head2 L<Perl::Critic::Policy::Subroutines::RequireFinalReturn>
757
8bc162ba 758End every path through a subroutine with an explicit C<return> statement. [Severity 4]
ad77f8eb 759
3878b20f 760=head2 L<Perl::Critic::Policy::TestingAndDebugging::ProhibitNoStrict>
ad77f8eb 761
8bc162ba 762Prohibit various flavors of C<no strict> [Severity 5]
ad77f8eb 763
3878b20f 764=head2 L<Perl::Critic::Policy::TestingAndDebugging::ProhibitNoWarnings>
ad77f8eb 765
8bc162ba 766Prohibit various flavors of C<no warnings> [Severity 4]
ad77f8eb 767
3878b20f 768=head2 L<Perl::Critic::Policy::TestingAndDebugging::RequireUseStrict>
59b05e08 769
8bc162ba 770Always C<use strict> [Severity 5]
59b05e08 771
3878b20f 772=head2 L<Perl::Critic::Policy::TestingAndDebugging::RequireUseWarnings>
59b05e08 773
8bc162ba 774Always C<use warnings> [Severity 4]
59b05e08
JRT
775
776=head2 L<Perl::Critic::Policy::ValuesAndExpressions::ProhibitConstantPragma>
777
8bc162ba 778Don't C< use constant $FOO => 15 > [Severity 4]
59b05e08
JRT
779
780=head2 L<Perl::Critic::Policy::ValuesAndExpressions::ProhibitEmptyQuotes>
781
8bc162ba 782Write C<q{}> instead of C<''> [Severity 2]
59b05e08
JRT
783
784=head2 L<Perl::Critic::Policy::ValuesAndExpressions::ProhibitInterpolationOfLiterals>
785
8bc162ba 786Always use single quotes for literal strings. [Severity 1]
59b05e08
JRT
787
788=head2 L<Perl::Critic::Policy::ValuesAndExpressions::ProhibitLeadingZeros>
789
8bc162ba 790Write C<oct(755)> instead of C<0755> [Severity 5]
59b05e08
JRT
791
792=head2 L<Perl::Critic::Policy::ValuesAndExpressions::ProhibitNoisyQuotes>
793
8bc162ba 794Use C<q{}> or C<qq{}> instead of quotes for awkward-looking strings. [Severity 2]
59b05e08
JRT
795
796=head2 L<Perl::Critic::Policy::ValuesAndExpressions::RequireInterpolationOfMetachars>
797
8bc162ba 798Warns that you might have used single quotes when you really wanted double-quotes. [Severity 1]
59b05e08
JRT
799
800=head2 L<Perl::Critic::Policy::ValuesAndExpressions::RequireNumberSeparators>
801
8bc162ba 802Write C< 141_234_397.0145 > instead of C< 141234397.0145 > [Severity 2]
59b05e08
JRT
803
804=head2 L<Perl::Critic::Policy::ValuesAndExpressions::RequireQuotedHeredocTerminator>
805
8bc162ba 806Write C< print <<'THE_END' > or C< print <<"THE_END" > [Severity 3]
59b05e08
JRT
807
808=head2 L<Perl::Critic::Policy::ValuesAndExpressions::RequireUpperCaseHeredocTerminator>
809
8bc162ba 810Write C< <<'THE_END'; > instead of C< <<'theEnd'; > [Severity 1]
59b05e08
JRT
811
812=head2 L<Perl::Critic::Policy::Variables::ProhibitLocalVars>
813
8bc162ba 814Use C<my> instead of C<local>, except when you have to. [Severity 2]
59b05e08 815
b672fd9e
CD
816=head2 L<Perl::Critic::Policy::Variables::ProhibitMatchVars>
817
818Avoid C<$`>, C<$&>, C<$'> and their English equivalents. [Severity 4]
819
59b05e08
JRT
820=head2 L<Perl::Critic::Policy::Variables::ProhibitPackageVars>
821
8bc162ba 822Eliminate globals declared with C<our> or C<use vars> [Severity 3]
59b05e08
JRT
823
824=head2 L<Perl::Critic::Policy::Variables::ProhibitPunctuationVars>
825
8bc162ba 826Write C<$EVAL_ERROR> instead of C<$@> [Severity 2]
59b05e08
JRT
827
828=head1 BENDING THE RULES
829
59b05e08
JRT
830Perl::Critic takes a hard-line approach to your code: either you
831comply or you don't. In the real world, it is not always practical
832(or even possible) to fully comply with coding standards. In such
833cases, it is wise to show that you are knowingly violating the
834standards and that you have a Damn Good Reason (DGR) for doing so.
835
836To help with those situations, you can direct Perl::Critic to ignore
837certain lines or blocks of code by using pseudo-pragmas:
838
839 require 'LegacyLibaray1.pl'; ## no critic
840 require 'LegacyLibrary2.pl'; ## no critic
841
842 for my $element (@list) {
843
844 ## no critic
845
846 $foo = ""; #Violates 'ProhibitEmptyQuotes'
847 $barf = bar() if $foo; #Violates 'ProhibitPostfixControls'
848 #Some more evil code...
849
850 ## use critic
851
852 #Some good code...
853 do_something($_);
854 }
855
856
6bf9b465 857The C<"## no critic"> comments direct Perl::Critic to ignore the
59b05e08
JRT
858remaining lines of code until the end of the current block, or until a
859C<"## use critic"> comment is found (whichever comes first). If the
860C<"## no critic"> comment is on the same line as a code statement,
c165f991 861then only that line of code is overlooked. To direct C<perlcritic> to
59b05e08
JRT
862ignore the C<"## no critic"> comments, use the C<-force> option.
863
864Use this feature wisely. C<"## no critic"> should be used in the
865smallest possible scope, or only on individual lines of code. If
866Perl::Critic complains about your code, try and find a compliant
867solution before resorting to this feature.
868
869=head1 EDITOR INTEGRATION
870
c165f991
JRT
871For ease-of-use, C<perlcritic> can be integrated with your favorite text
872editor. The output-formatting capabilities of C<perlcritic> are
59b05e08
JRT
873specifically intended for use with the "grep" or "compile" modes
874available in editors like C<emacs> and C<vim>. In these modes, you can
875run an arbitrary command and the editor will parse the output into an
876interactive buffer that you can click on and jump to the relevant line
877of code.
878
879=head2 EMACS
880
881Entering C<'Meta-x compile'> causes emacs to switch to compile-mode.
882Next, enter the following command in the minibuffer:
883
884 perlcritic -verbose 1 path/to/your/file
885
886When the results are displayed, pressing [Enter] on any of the
887Violation messages will move the pointer to the relevant location
888within the file. Type C<'Ctrl-h a compile'> for information about
5deaba5e 889compile-mode.
59b05e08
JRT
890
891=head2 VIM
892
893Configure the grep format as follows:
894
895 set grepformat=%f:%l:%c:m
896 set grepprg=perlcritic\ -verbose\ 1\ %
897
898Then, you can run perlcritic on the current buffer with:
899
900 :grep
901
902Navigation and display instructions can be found under C<:help grep>.
903Someone with stronger Vim-fu may wish to convert this to a real macro.
904
905=head1 EXIT STATUS
906
c165f991
JRT
907If C<perlcritic> has any errors itself, exits with status == 1. If there
908are no errors, but C<perlcritic> finds Policy violations in your source
59b05e08
JRT
909code, exits with status == 2. If there were no errors and no
910violations were found, exits with status == 0.
911
4d19da19 912=head1 EXTENDING THE CRITIC
5deaba5e 913
4d19da19
JRT
914The modular design of Perl::Critic is intended to facilitate the
915addition of new Policies. You'll need to have some understanding of
916L<PPI>, but most Policy modules are pretty straightforward and only
5ab86a86
JRT
917require about 20 lines of code. Please see the
918L<Perl::Critic::DEVELOPER> file included in this distribution for a
919step-by-step demonstration of how to create new Policy modules.
4d19da19
JRT
920
921If you develop any new Policy modules, feel free to send them to
922<thaljef@cpan.org> and I'll be happy to put them into the Perl::Critic
923distribution. Or if you'd like to work on the Perl::Critic project
924directly, check out our repository at L<http://perlcritic.tigris.org>.
925To subscribe to our mailing list, send a message to
5deaba5e
JRT
926C<dev-subscribe@perlcritic.tigris.org>.
927
59b05e08
JRT
928=head1 BUGS
929
930Scrutinizing Perl code is hard for humans, let alone machines. If you
931find any bugs, particularly false-positives or false-negatives from a
932Perl::Critic::Policy, please submit them to
933L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Perl-Critic>. Thanks.
934
935=head1 CREDITS
936
937Adam Kennedy - For creating L<PPI>, the heart and soul of Perl::Critic.
938
939Damian Conway - For writing B<Perl Best Practices>.
940
941Giuseppe Maxia - For all the great ideas and enhancements.
942
943Chris Dolan - For numerous bug reports and suggestions.
944
945Sharon, my wife - For putting up with my all-night code sessions.
946
947=head1 AUTHOR
948
949Jeffrey Ryan Thalhammer <thaljef@cpan.org>
950
951=head1 COPYRIGHT
952
c3c88e54 953Copyright (c) 2005-2006 Jeffrey Ryan Thalhammer. All rights reserved.
59b05e08
JRT
954
955This program is free software; you can redistribute it and/or modify
956it under the same terms as Perl itself. The full text of this license
957can be found in the LICENSE file included with this module.
958
959=cut