Login
Apply the unmodified patch from Schwern (modulo dealing with
[gknop/Perl-Critic.git] / bin / perlcritic
CommitLineData
59b05e08
JRT
1#!/usr/bin/perl
2
6036a254 3##############################################################################
3915361f
JRT
4# $URL$
5# $Date$
6# $Author$
7# $Revision$
e68db767 8##############################################################################
3915361f 9
ced050bc 10## no critic (ErrorHandling::RequireUseOfExceptions)
59b05e08
JRT
11package main;
12
df6dee2b 13use 5.006001;
59b05e08
JRT
14use strict;
15use warnings;
a79d19f4
ES
16
17use English qw< -no_match_vars >;
05b5f925
ES
18use Readonly;
19
a79d19f4
ES
20use Getopt::Long qw< GetOptions >;
21use List::Util qw< first >;
22use Pod::Usage qw< pod2usage >;
e68db767 23
94472d4a 24use Perl::Critic::Exception::Parse ();
a79d19f4 25use Perl::Critic::Utils qw<
70f3f307 26 :characters :severities policy_short_name
05b5f925 27 $DEFAULT_VERBOSITY $DEFAULT_VERBOSITY_WITH_FILE_NAME
a79d19f4
ES
28>;
29use Perl::Critic::Violation qw<>;
05b5f925 30
7807e1bf 31#-----------------------------------------------------------------------------
59b05e08 32
be4331b3 33our $VERSION = '1.090';
db1213c6 34
05b5f925
ES
35Readonly::Scalar my $DEFAULT_VIOLATIONS_FOR_TOP => 20;
36
a79d19f4
ES
37Readonly::Scalar my $EXIT_SUCCESS => 0;
38Readonly::Scalar my $EXIT_NO_FILES => 1;
39Readonly::Scalar my $EXIT_HAD_VIOLATIONS => 2;
40Readonly::Scalar my $EXIT_HAD_FILE_PROBLEMS => 3;
41
4268e673
JRT
42#-----------------------------------------------------------------------------
43# Begin script. Don't run when loaded as a library
44
45my @FILES = ();
e68db767 46my $CRITIC = undef;
89b50090 47my $Output = \*STDOUT;
72d248e0
RS
48
49# This %ENV check is to allow perlcritic to function when bundled under PAR,
50# which invokes this program not as the top stack frame. -- rjbs, 2008-08-11
51exit run() if not caller() or $ENV{PAR_0};
59b05e08 52
db1213c6 53#-----------------------------------------------------------------------------
4268e673 54# Begin subroutines
af1acfa2 55
89b50090
ES
56sub out {
57 print $Output @_;
58}
59
60
4268e673 61sub run {
55ae7242 62 my %options = get_options();
4268e673 63 @FILES = get_input(@ARGV);
a79d19f4
ES
64
65 my ($violations, $had_error_in_file) = critique(\%options, @FILES);
66
67 return $EXIT_HAD_FILE_PROBLEMS if $had_error_in_file;
68 return $EXIT_NO_FILES if not defined $violations;
69 return $EXIT_HAD_VIOLATIONS if $violations;
70
71 return $EXIT_SUCCESS;
af1acfa2 72}
59b05e08 73
db1213c6 74#-----------------------------------------------------------------------------
59b05e08 75
6e7d6c9f 76sub get_options {
59b05e08 77
55ae7242
JRT
78 my %opts = _parse_command_line();
79 _dispatch_special_requests( %opts );
80 _validate_options( %opts );
81
82 # Convert severity shortcut options. If multiple shortcuts
e7ae8f62 83 # are given, the lowest one wins. If an explicit --severity
0bcb38c0
JRT
84 # option has been given, then the shortcuts are ignored. The
85 # @SEVERITY_NAMES variable is exported by Perl::Critic::Utils.
05b5f925
ES
86 $opts{severity} ||= first { exists $opts{$_} } @SEVERITY_NAMES;
87 $opts{severity} ||=
88 first { exists $opts{$_} } ($SEVERITY_LOWEST .. $SEVERITY_HIGHEST);
55ae7242
JRT
89
90
e7ae8f62 91 # If --top is specified, default the severity level to 1, unless an
55ae7242
JRT
92 # explicit severity is defined. This provides us flexibility to
93 # report top-offenders across just some or all of the severity levels.
e7ae8f62 94 # We also default the --top count to twenty if none is given
55ae7242
JRT
95 if ( exists $opts{top} ) {
96 $opts{severity} ||= 1;
05b5f925 97 $opts{top} ||= $DEFAULT_VIOLATIONS_FOR_TOP;
55ae7242
JRT
98 }
99
e7ae8f62 100 #Override profile, if --noprofile is specified
55ae7242
JRT
101 if ( exists $opts{noprofile} ) {
102 $opts{profile} = q{};
103 }
104
105 # I've adopted the convention of using key-value pairs for
106 # arguments to most functions. And to increase legibility,
107 # I have also adopted the familiar command-line practice
108 # of denoting argument names with a leading dash (-).
109 my %dashed_opts = map { ( "-$_" => $opts{$_} ) } keys %opts;
110 return %dashed_opts;
111}
112
113#-----------------------------------------------------------------------------
114
115sub _parse_command_line {
89b50090 116 my %opts;
faa35de4 117 my @opt_specs = _get_option_specification();
59b05e08 118 Getopt::Long::Configure('no_ignore_case');
55ae7242 119 GetOptions( \%opts, @opt_specs ) || pod2usage(); #Exits
55ae7242
JRT
120 return %opts;
121}
59b05e08 122
55ae7242
JRT
123#-----------------------------------------------------------------------------
124
125sub _dispatch_special_requests {
126 my (%opts) = @_;
738830ba
ES
127 if ( $opts{help} ) { pod2usage( -verbose => 0 ) } #Exits
128 if ( $opts{options} ) { pod2usage( -verbose => 1 ) } #Exits
129 if ( $opts{man} ) { pod2usage( -verbose => 2 ) } #Exits
89b50090 130 if ( $opts{version} ) { out "$VERSION\n"; exit 0; } #Exits
738830ba 131 if ( $opts{list} ) { render_policy_listing(); } #Exits
71ef7d49 132 if ( $opts{'list-themes'} ) { render_theme_listing(); } #Exits
738830ba
ES
133 if ( $opts{'profile-proto'} ) { render_profile_prototype(); } #Exits
134 if ( $opts{doc} ) { policy_docs( $opts{doc} ); } #Exits
55ae7242
JRT
135 return 1;
136}
137
138#-----------------------------------------------------------------------------
139
140sub _validate_options {
141 my (%opts) = @_;
142 my $msg = q{};
122d73f6 143
122d73f6 144
59b05e08 145 if ( $opts{noprofile} && $opts{profile} ) {
faa35de4 146 $msg .= qq{Warning: Cannot use -noprofile with -profile option.\n};
59b05e08
JRT
147 }
148
7175ddcc 149 if ( $opts{verbose} && $opts{verbose} !~ m{(?: \d+ | %[mfFlcedrpPs] )}mx) {
b8d28f35
ES
150 $msg .= qq<Warning: --verbose arg "$opts{verbose}" looks odd. >;
151 $msg .= qq<Perhaps you meant to say "--verbose 3 $opts{verbose}"\n>;
6bf9b465
JRT
152 }
153
55ae7242 154 if ( exists $opts{top} && $opts{top} < 0 ) {
b8d28f35
ES
155 $msg .= qq<Warning: --top argument "$opts{top}" is negative. >;
156 $msg .= qq<Perhaps you meant to say "$opts{top} --top".\n>;
d2843fb4
JRT
157 }
158
05b5f925
ES
159 if (
160 exists $opts{severity}
161 && (
162 $opts{severity} < $SEVERITY_LOWEST
163 || $opts{severity} > $SEVERITY_HIGHEST
164 )
165 ) {
b8d28f35
ES
166 $msg .= qq<Warning: --severity arg "$opts{severity}" out of range. >;
167 $msg .= qq<Severities range from "$SEVERITY_LOWEST" (lowest) to >;
168 $msg .= qq<"$SEVERITY_HIGHEST" (highest).\n>;
59b05e08
JRT
169 }
170
55ae7242
JRT
171
172 if ( $msg ) {
173 pod2usage( -exitstatus => 1, -message => $msg, -verbose => 0); #Exits
174 }
175
176
177 return 1;
178}
179
db1213c6 180#-----------------------------------------------------------------------------
1e7b8681 181
59b05e08
JRT
182sub get_input {
183
8001b0a7
CD
184 my @args = @_;
185
186 if ( !@args || (@args == 1 && $args[0] eq q{-}) ) {
ada28359
JRT
187
188 # Reading code from STDIN. All the code is slurped into
189 # a string. PPI will barf if the string is just whitespace.
190 my $code_string = do { local $RS = undef; <STDIN> };
191
192 # Notice if STDIN was closed (pipe error, etc)
193 if ( ! defined $code_string ) {
194 $code_string = q{};
195 }
196
ced050bc 197 $code_string =~ m{ \S+ }mx || die qq{Nothing to critique.\n};
ada28359
JRT
198 return \$code_string; #Convert to SCALAR ref for PPI
199 }
200 else {
59b05e08 201
55ae7242
JRT
202 # Test to make sure all the specified files or directories
203 # actually exist. If any one of them is bogus, then die.
dc4552db
JRT
204 if ( my $nonexistent = first { ! -e $_ } @args ) {
205 my $msg = qq{No such file or directory: '$nonexistent'};
dfbe98be
JRT
206 pod2usage( -exitstatus => 1, -message => $msg, -verbose => 0);
207 }
208
fdfe1e54
JRT
209 # Reading code from files or dirs. If argument is a file,
210 # then we process it as-is (even though it may not actually
211 # be Perl code). If argument is a directory, recursively
212 # search the directory for files that look like Perl code.
8001b0a7 213 return map { -d $_ ? Perl::Critic::Utils::all_perl_files($_) : $_ } @args;
59b05e08 214 }
59b05e08
JRT
215}
216
adc2e250 217#------------------------------------------------------------------------------
1e7b8681 218
59b05e08 219sub critique {
1e7b8681 220
0bce889d 221 my ( $opts_ref, @files ) = @_;
a609ec83 222 @files || die "No perl files were found.\n";
59b05e08 223
db1213c6
JRT
224 # Perl::Critic has lots of dependencies, so loading is delayed
225 # until it is really needed. This hack reduces startup time for
226 # doing other things like getting the version number or dumping
227 # the man page. Arguably, those things are pretty rare, but hey,
228 # why not save a few seconds if you can.
229
fdfe1e54 230 require Perl::Critic;
e68db767 231 $CRITIC = Perl::Critic->new( %{$opts_ref} );
d032ff5e
JRT
232 $CRITIC->policies() || die "No policies selected.\n";
233
89b50090
ES
234 set_up_pager();
235
576f6411 236 my $number_of_violations = undef;
a79d19f4 237 my $had_error_in_file = 0;
576f6411 238
f03e8867 239 for my $file (@files) {
adc2e250 240
f03e8867 241 eval {
2ce0b9ee 242 my @violations = $CRITIC->critique($file);
576f6411 243 $number_of_violations += scalar @violations;
cb43b040 244
738830ba 245 if (not $opts_ref->{'-statistics-only'}) {
cb43b040
ES
246 render_report( $file, $opts_ref, @violations )
247 }
62d2fc9e 248 1;
a79d19f4 249 }
62d2fc9e
ES
250 or do {
251 if ( my $exception = Perl::Critic::Exception::Parse->caught() ) {
252 $had_error_in_file = 1;
253 warn qq<Problem while critiquing "$file": $EVAL_ERROR\n>;
254 }
255 elsif ($EVAL_ERROR) {
256 # P::C::Exception::Fatal includes the stack trace in its
257 # stringification.
258 die qq<Fatal error while critiquing "$file": $EVAL_ERROR\n>;
259 }
260 else {
261 die qq<Fatal error while critiquing "$file". Unfortunately, >,
262 q<$@/$EVAL_ERROR >, ## no critic (RequireInterpolationOfMetachars)
263 qq<is empty, so the reason can't be shown.\n>;
264 }
94472d4a 265 }
f03e8867 266 }
db1213c6 267
738830ba 268 if ( $opts_ref->{-statistics} or $opts_ref->{'-statistics-only'} ) {
2ce0b9ee
JRT
269 my $stats = $CRITIC->statistics();
270 report_statistics( $opts_ref, $stats );
576f6411
ES
271 }
272
a79d19f4 273 return $number_of_violations, $had_error_in_file;
576f6411
ES
274}
275
276#------------------------------------------------------------------------------
277
7f2081ac
JRT
278sub render_report {
279
55ae7242 280 my ( $file, $opts_ref, @violations ) = @_;
7f2081ac 281
faa35de4 282 # Only report the number of violations, if asked.
d032ff5e 283 my $number_of_violations = scalar @violations;
faa35de4 284 if( $opts_ref->{-count} ){
89b50090
ES
285 ref $file || out "$file: ";
286 out "$number_of_violations\n";
d032ff5e 287 return $number_of_violations;
faa35de4 288 }
1e7b8681 289
faa35de4 290 # Hail all-clear unless we should shut up.
6eb4058e 291 if( !@violations && !$opts_ref->{-quiet} ) {
89b50090
ES
292 ref $file || out "$file ";
293 out "source OK\n";
6eb4058e 294 return 0;
2bfd3a79
JRT
295 }
296
faa35de4 297 # Otherwise, format and print violations
9f6df1c1 298 my $verbosity = $CRITIC->config->verbose();
3c16210a 299 # $verbosity can be numeric or string, so use "eq" for comparison;
05b5f925
ES
300 $verbosity =
301 ($verbosity eq $DEFAULT_VERBOSITY && @FILES > 1)
302 ? $DEFAULT_VERBOSITY_WITH_FILE_NAME
303 : $verbosity;
7b177782 304 my $fmt = Perl::Critic::Utils::verbosity_to_format( $verbosity );
02c643f7 305 if (not -f $file) { $fmt =~ s{\%[fF]}{STDIN}mx; } #HACK!
7b84ff16 306 Perl::Critic::Violation::set_format( $fmt );
faa35de4 307
51ae9d9b 308 my $color = $CRITIC->config->color();
89b50090 309 out $color ? _colorize_by_severity(@violations) : @violations;
25792f52 310
d032ff5e 311 return $number_of_violations;
faa35de4 312}
576f6411 313
89b50090
ES
314
315sub set_up_pager {
316 return unless _at_tty();
317
318 my $command = $CRITIC->config->pager;
319 open( my $pager, '|-', $command ) or die qq{Unable to pipe to pager "$command": $!};
320 $Output = $pager;
321}
322
323
576f6411
ES
324#-----------------------------------------------------------------------------
325
326sub report_statistics {
327 my ($opts_ref, $statistics) = @_;
576f6411
ES
328
329 if (
738830ba 330 not $opts_ref->{'-statistics-only'}
cb43b040
ES
331 and (
332 $statistics->total_violations()
333 or not $opts_ref->{-quiet} and $statistics->modules()
334 )
576f6411 335 ) {
89b50090 336 out "\n"; # There's prior output that we want to separate from.
576f6411
ES
337 }
338
89b50090
ES
339 out _commaify($statistics->modules()), " files.\n";
340 out _commaify($statistics->subs()), " subroutines/methods.\n";
341 out _commaify($statistics->statements_other_than_subs()), " statements.\n";
342 out _commaify($statistics->lines()), " lines.\n";
fb1d7f95 343
35541a80
ES
344 my $average_sub_mccabe = $statistics->average_sub_mccabe();
345 if (defined $average_sub_mccabe) {
89b50090 346 out sprintf
35541a80
ES
347 "\nAverage McCabe score of subroutines was %.2f.\n",
348 $average_sub_mccabe;
349 }
350
89b50090 351 out "\n";
576f6411 352
89b50090 353 out _commaify($statistics->total_violations()), " violations.\n";
576f6411 354
da1c78d8
ES
355 my $violations_per_file = $statistics->violations_per_file();
356 if (defined $violations_per_file) {
89b50090 357 out sprintf
da1c78d8
ES
358 "Violations per file was %.3f.\n",
359 $violations_per_file;
360 }
361 my $violations_per_statement = $statistics->violations_per_statement();
362 if (defined $violations_per_statement) {
89b50090 363 out sprintf
da1c78d8
ES
364 "Violations per statement was %.3f.\n",
365 $violations_per_statement;
366 }
35541a80
ES
367 my $violations_per_line = $statistics->violations_per_line_of_code();
368 if (defined $violations_per_line) {
89b50090 369 out sprintf
35541a80
ES
370 "Violations per line of code was %.3f.\n",
371 $violations_per_line;
372 }
373
fb1d7f95 374 if ( $statistics->total_violations() ) {
89b50090 375 out "\n";
576f6411 376
ee9c1726 377 my %severity_violations = %{ $statistics->violations_by_severity() };
fb1d7f95 378 foreach my $severity ( reverse sort keys %severity_violations ) {
89b50090 379 out
fb1d7f95
ES
380 _commaify($severity_violations{$severity}),
381 " severity $severity violations.\n";
576f6411
ES
382 }
383
89b50090 384 out "\n";
576f6411 385
ee9c1726 386 my %policy_violations = %{ $statistics->violations_by_policy() };
fb1d7f95 387 foreach my $policy ( sort keys %policy_violations ) {
89b50090 388 out
fb1d7f95
ES
389 _commaify($policy_violations{$policy}),
390 ' violations of ',
576f6411
ES
391 policy_short_name($policy),
392 ".\n";
393 }
394 }
395
396 return;
397}
398
faa35de4
JRT
399#-----------------------------------------------------------------------------
400
35541a80 401# Only works for integers.
fb1d7f95
ES
402sub _commaify {
403 my ( $number ) = @_;
404
405 while ($number =~ s/ \A ( [-+]? \d+ ) ( \d{3} ) /$1,$2/xms) {
406 # nothing
407 }
408
409 return $number;
410}
411
412#-----------------------------------------------------------------------------
413
faa35de4
JRT
414sub _get_option_specification {
415
416 return qw(
417 5 4 3 2 1
418 Safari
eb4540f0 419 version
0bcb38c0 420 brutal
5176884d 421 count|C
0bcb38c0 422 cruel
6332a5f1 423 doc=s
faa35de4 424 exclude=s@
410cf90b 425 force!
0bcb38c0
JRT
426 gentle
427 harsh
5176884d 428 help|?|H
faa35de4
JRT
429 include=s@
430 list
71ef7d49 431 list-themes
faa35de4 432 man
ae9b3404 433 color|colour!
faa35de4 434 noprofile
7b84ff16 435 only!
bbcf8061 436 options
89b50090 437 pager=s
faa35de4 438 profile=s
738830ba 439 profile-proto
faa35de4
JRT
440 quiet
441 severity=i
2849151b 442 single-policy|s=s
0bcb38c0 443 stern
576f6411 444 statistics!
738830ba 445 statistics-only!
9f12283e 446 profile-strictness=s
410cf90b 447 theme=s
faa35de4
JRT
448 top:i
449 verbose=s
450 );
59b05e08
JRT
451}
452
db1213c6 453#-----------------------------------------------------------------------------
01625a50 454
faa35de4
JRT
455sub _colorize_by_severity {
456 my (@violations) = @_;
faa35de4
JRT
457 return @violations if _this_is_windows();
458 return @violations if not eval { require Term::ANSIColor };
459
05b5f925
ES
460 my %color_of = (
461 $SEVERITY_HIGHEST => 'bold red',
462 $SEVERITY_HIGH => 'yellow',
463 );
faa35de4
JRT
464 return map { _colorize( "$_", $color_of{$_->severity()} ) } @violations;
465
466}
467
468#-----------------------------------------------------------------------------
469
470sub _colorize {
471 my ($string, $color) = @_;
472 return $string if not defined $color;
473 return Term::ANSIColor::colored( $string, $color );
474}
475
476#-----------------------------------------------------------------------------
477
478sub _this_is_windows {
479 return 1 if $OSNAME =~ m/MSWin32/mx;
480 return 0;
481}
482
483#-----------------------------------------------------------------------------
484
485sub _at_tty {
486 return -t STDOUT; ##no critic 'InteractiveTest';
487}
faa35de4 488
e68db767 489#-----------------------------------------------------------------------------
faa35de4 490
fd5bd7b5 491sub render_policy_listing {
fdfe1e54 492
c2018d77 493 require Perl::Critic::PolicyListing;
606ea80c 494 require Perl::Critic;
e68db767 495
05b5f925 496 my %pc_params = (-profile => $EMPTY, -severity => $SEVERITY_LOWEST);
71ef7d49
ES
497 my @policies = Perl::Critic->new( %pc_params )->policies();
498 my $listing = Perl::Critic::PolicyListing->new( -policies => \@policies );
89b50090 499 out $listing;
71ef7d49
ES
500 exit 0;
501}
502
503#-----------------------------------------------------------------------------
504
505sub render_theme_listing {
506 require Perl::Critic::ThemeListing;
507 require Perl::Critic;
508
509 my %pc_params = (-profile => $EMPTY, -severity => $SEVERITY_LOWEST);
510 my @policies = Perl::Critic->new( %pc_params )->policies();
511 my $listing = Perl::Critic::ThemeListing->new( -policies => \@policies );
89b50090 512 out $listing;
d6950ab1 513 exit 0;
fd5bd7b5
JRT
514}
515
516#-----------------------------------------------------------------------------
517
518sub render_profile_prototype {
519
520 require Perl::Critic::ProfilePrototype;
606ea80c 521 require Perl::Critic;
fd5bd7b5 522
05b5f925 523 my %pc_params = (-profile => $EMPTY, -severity => $SEVERITY_LOWEST);
71ef7d49
ES
524 my @policies = Perl::Critic->new( %pc_params )->policies();
525 my $prototype = Perl::Critic::ProfilePrototype->new( -policies => \@policies );
89b50090 526 out $prototype;
d6950ab1 527 exit 0;
faa35de4
JRT
528}
529
6332a5f1
JRT
530#-----------------------------------------------------------------------------
531
532sub policy_docs {
533
534 my $pattern = shift;
606ea80c 535 require Perl::Critic;
6332a5f1 536
05b5f925 537 my %pc_params = (-profile => $EMPTY, -severity => $SEVERITY_LOWEST);
606ea80c
JRT
538 my @policies = Perl::Critic::Config->new( %pc_params )->policies();
539 my @matches = grep { $_ =~ m/$pattern/imx } @policies;
6332a5f1
JRT
540
541 for my $matching_policy ( @matches ) {
542 my @perldoc_cmd = qw(perldoc -T); #-T means don't send to pager
606ea80c 543 system @perldoc_cmd, ref $matching_policy;
6332a5f1
JRT
544 }
545 exit 0;
546}
547
59b05e08
JRT
5481;
549
550__END__
551
01625a50 552#-----------------------------------------------------------------------------
1e7b8681 553
59b05e08
JRT
554=pod
555
2849151b
ES
556=for stopwords DGR INI-style vim-fu minibuffer -noprofile API
557-profileproto -profile-proto ben Jore formatter Peshak pbp Komodo
c296c678 558screenshots tty emacs gVIM plugin Perlish templating ActiveState
821d0eb5 559
59b05e08
JRT
560=head1 NAME
561
13c1001a 562C<perlcritic> - Command-line interface to critique Perl source.
59b05e08 563
11f53956 564
59b05e08
JRT
565=head1 SYNOPSIS
566
e7ae8f62
ES
567 perlcritic [-12345 | --brutal | --cruel | --harsh | --stern | --gentle]
568 [--severity number | name] [--profile file | --noprofile]
569 [--top [ number ]] [--theme expression] [--include pattern]
2849151b
ES
570 [--exclude pattern] [{-s | --single-policy} pattern]
571 [--only | --noonly] [--profile-strictness {warn|fatal|quiet}]
572 [--force | --noforce] [--statistics] [--statistics-only]
573 [--count | -C] [--verbose {number | format}]
89b50090
ES
574 [--color | --nocolor] [--pager pager]
575 [--quiet] {FILE | DIRECTORY | STDIN}
05b913fd 576
e7ae8f62 577 perlcritic --profile-proto
05b913fd 578
71ef7d49 579 perlcritic { --list | --list-themes | --doc pattern [...] }
9f12283e 580
eb4540f0 581 perlcritic { --help | --options | --man | --version }
59b05e08 582
11f53956 583
59b05e08
JRT
584=head1 DESCRIPTION
585
586C<perlcritic> is a Perl source code analyzer. It is the executable
11f53956
ES
587front-end to the L<Perl::Critic|Perl::Critic> engine, which attempts
588to identify awkward, hard to read, error-prone, or unconventional
589constructs in your code. Most of the rules are based on Damian
590Conway's book B<Perl Best Practices>. However, C<perlcritic> is
591B<not> limited to enforcing PBP, and it will even support rules that
592contradict Conway. All rules can easily be configured or disabled to
593your liking.
59b05e08 594
e7ae8f62
ES
595This documentation only covers how to drive this command. For all
596other information, including how to persistently configure this
11f53956
ES
597command so that you don't have to say so much on the command-line, see
598the documentation for L<Perl::Critic|Perl::Critic> itself.
0304068a 599
8d36cd6f 600
d2843fb4
JRT
601=head1 USAGE EXAMPLES
602
25a6e413 603Before getting into all the gory details, here are some basic usage
b2c7354a 604examples to help get you started.
d2843fb4 605
11f53956
ES
606 # Report only most severe violations (severity = 5)
607 perlcritic YourModule.pm
608
609 # Same as above, but read input from STDIN
610 perlcritic
25a6e413 611
11f53956
ES
612 # Recursively process all Perl files beneath directory
613 perlcritic /some/directory
db1213c6 614
11f53956
ES
615 # Report slightly less severe violations too (severity >= 4)
616 perlcritic -4 YourModule.pm
d2843fb4 617
11f53956
ES
618 # Same as above, but using named severity level
619 perlcritic --stern YourModule.pm
d2843fb4 620
11f53956
ES
621 # Report all violations, regardless of severity (severity >= 1)
622 perlcritic -1 YourModule.pm
0bcb38c0 623
11f53956
ES
624 # Same as above, but using named severity level
625 perlcritic --brutal YourModule.pm
d2843fb4 626
11f53956
ES
627 # Report only violations of things from "Perl Best Practices"
628 perlcritic --theme pbp YourModule.pm
e7ae8f62 629
11f53956
ES
630 # Report top 20 most severe violations (severity >= 1)
631 perlcritic --top YourModule.pm
0bcb38c0 632
11f53956
ES
633 # Report additional violations of Policies that match m/variables/ix
634 perlcritic --include variables YourModule.pm
4a24d03a 635
11f53956
ES
636 # Use defaults from somewhere other than ~/.perlcriticrc
637 perlcriticrc --profile project/specific/perlcriticrc YourModule.pm
25a6e413 638
d2843fb4 639
59b05e08
JRT
640=head1 ARGUMENTS
641
642The arguments are paths to the files you wish to analyze. You may
c165f991 643specify multiple files. If an argument is a directory, C<perlcritic>
11f53956
ES
644will analyze all Perl files below the directory. If no arguments are
645specified, then input is read from STDIN.
646
59b05e08
JRT
647
648=head1 OPTIONS
649
650Option names can be abbreviated to uniqueness and can be stated with
651singe or double dashes, and option values can be separated from the
11f53956
ES
652option name by a space or '=' (as with L<Getopt::Long|Getopt::Long>).
653Option names are also case-sensitive.
59b05e08
JRT
654
655=over 8
656
e7ae8f62 657=item C<--profile FILE>
59b05e08 658
11f53956
ES
659Directs C<perlcritic> to use a profile named by FILE rather than
660looking for the default F<.perlcriticrc> file in the current directory
661or your home directory. See L<Perl::Critic/"CONFIGURATION"> for more
662information.
59b05e08 663
e7ae8f62 664=item C<--noprofile>
59b05e08 665
11f53956
ES
666Directs C<perlcritic> not to load any configuration file, thus
667reverting to the default configuration for all Policies.
59b05e08 668
e7ae8f62 669=item C<--severity N>
59b05e08 670
11f53956
ES
671Directs C<perlcritic> to only apply Policies with a severity greater
672than C<N>. Severity values are integers ranging from 1 (least severe)
673to 5 (most severe). The default is 5. For a given C<--profile>,
674decreasing the C<--severity> will usually produce more violations.
675You can set the default value for this option in your F<.perlcriticrc>
676file. You can also redefine the C<severity> for any Policy in your
677F<.perlcriticrc> file. See L<"CONFIGURATION"> for more information.
59b05e08 678
faa35de4 679=item C<-5 | -4 | -3 | -2 | -1>
d2843fb4 680
11f53956
ES
681These are numeric shortcuts for setting the C<--severity> option. For
682example, C<"-4"> is equivalent to C<"--severity 4">. If multiple
683shortcuts are specified, then the most restrictive one wins. If an
684explicit C<--severity> option is also given, then all shortcut options
685are silently ignored. NOTE: Be careful not to put one of the number
686severity shortcut options immediately after the C<--top> flag or
687C<perlcritic> will interpret it as the number of violations to report.
0bcb38c0 688
e7ae8f62 689=item C<--severity NAME>
0bcb38c0 690
11f53956
ES
691If it is difficult for you to remember whether severity "5" is the
692most or least restrictive level, then you can use one of these named
693values:
0bcb38c0 694
7711a331 695 SEVERITY NAME ...is equivalent to... SEVERITY NUMBER
0bcb38c0 696 --------------------------------------------------------
e7ae8f62
ES
697 --severity gentle --severity 5
698 --severity stern --severity 4
699 --severity harsh --severity 3
700 --severity cruel --severity 2
701 --severity brutal --severity 1
0bcb38c0 702
e7ae8f62 703=item C<--gentle | --stern | --harsh | --cruel | --brutal>
0bcb38c0 704
11f53956
ES
705These are named shortcuts for setting the C<--severity> option. For
706example, C<"--cruel"> is equivalent to C<"--severity 2">. If multiple
707shortcuts are specified, then the most restrictive one wins. If an
708explicit C<--severity> option is also given, then all shortcut options
709are silently ignored.
d2843fb4 710
e7ae8f62 711=item C<--theme RULE>
a0934394 712
11f53956
ES
713Directs C<perlcritic> to apply only Policies with themes that satisfy
714the C<RULE>. Themes are arbitrary names for groups of related
715policies. You can combine theme names with boolean operators to
716create an arbitrarily complex C<RULE>. For example, the following
717would apply only Policies that have a 'bugs' AND 'pbp' theme:
1c5955e4 718
11f53956 719 $> perlcritic --theme='bugs && pbp' MyModule.pm
1c5955e4 720
11f53956
ES
721Unless the C<--severity> option is explicitly given, setting
722C<--theme> silently causes the C<--severity> to be set to 1. You can
723set the default value for this option in your F<.perlcriticrc> file.
724See L<Perl::Critic/"POLICY THEMES"> for more information about themes.
faa35de4 725
e7ae8f62 726=item C<--include PATTERN>
59b05e08 727
11f53956
ES
728Directs C<perlcritic> to apply additional Policies that match the
729regex C</PATTERN/imx>. Use this option to temporarily override your
730profile and/or the severity settings at the command-line. For
731example:
6bf9b465 732
11f53956 733 perlcritic --include=layout my_file.pl
6bf9b465 734
11f53956
ES
735This would cause C<perlcritic> to apply all the C<CodeLayout::*>
736policies even if they have a severity level that is less than the
737default level of 5, or have been disabled in your F<.perlcriticrc>
738file. You can specify multiple C<--include> options and you can use
739it in conjunction with the C<--exclude> option. Note that
740C<--exclude> takes precedence over C<--include> when a Policy matches
741both patterns. You can set the default value for this option in your
77de3405 742F<.perlcriticrc> file.
59b05e08 743
e7ae8f62 744=item C<--exclude PATTERN>
59b05e08 745
77de3405 746Directs C<perlcritic> to not apply any Policy that matches the regex
11f53956
ES
747C</PATTERN/imx>. Use this option to temporarily override your profile
748and/or the severity settings at the command-line. For example:
6bf9b465 749
11f53956 750 perlcritic --exclude=strict my_file.pl
6bf9b465 751
11f53956
ES
752This would cause C<perlcritic> to not apply the C<RequireUseStrict>
753and C<ProhibitNoStrict> Policies even though they have the highest
754severity level. You can specify multiple C<--exclude> options and you
755can use it in conjunction with the C<--include> option. Note that
756C<--exclude> takes precedence over C<--include> when a Policy matches
757both patterns. You can set the default value for this option in your
758F<.perlcriticrc> file.
59b05e08 759
e7ae8f62 760=item C<--single-policy PATTERN>
585ddee1 761
2849151b
ES
762=item C<-s PATTERN>
763
11f53956
ES
764Directs C<perlcritic> to apply just one Policy module matching the
765regex C</PATTERN/imx>, and exclude all other Policies. This option
766has precedence over the C<--severity>, C<--theme>, C<--include>,
767C<--exclude>, and C<--only> options. For example:
585ddee1 768
11f53956 769 perlcritic --single-policy=nowarnings my_file.pl
585ddee1 770
11f53956
ES
771This would cause C<perlcritic> to apply just the C<ProhibitNoWarnings>
772Policy, regardless of the severity level setting. No other Policies
773would be applied.
585ddee1 774
77de3405 775This is equivalent to what one might intend by...
585ddee1 776
11f53956 777 perlcritic --exclude=. --include=nowarnings my_file.pl
585ddee1 778
e7ae8f62
ES
779... but this won't work because the C<--exclude> option overrides the
780C<--include> option.
585ddee1 781
11f53956
ES
782The equivalent of this option can be accomplished by creating a custom
783profile containing only the desired policy and then running...
585ddee1 784
11f53956 785 perlcritic --profile=customprofile --only my_file.pl
585ddee1 786
e7ae8f62 787=item C<--top [ N ]>
faa35de4 788
11f53956
ES
789Directs C<perlcritic> to report only the top C<N> Policy violations in
790each file, ranked by their severity. If C<N> is not specified, it
791defaults to 20. If the C<--severity> option (or one of the shortcuts)
792is not explicitly given, the C<--top> option implies that the minimum
793severity level is "1" (i.e. "brutal"). Users can redefine the severity
794for any Policy in their F<.perlcriticrc> file. See L<"CONFIGURATION">
795for more information. You can set the default value for this option
796in your F<.perlcriticrc> file. NOTE: Be careful not to put one of the
797severity shortcut options immediately after the C<--top> flag or
798C<perlcritic> will interpret it as the number of violations to report.
faa35de4 799
e7ae8f62 800=item C<--force>
59b05e08 801
11f53956
ES
802Directs C<perlcritic> to ignore the magical C<"## no critic">
803pseudo-pragmas in the source code. See L<"BENDING THE RULES"> for more
804information. You can set the default value for this option in your
805F<.perlcriticrc> file.
59b05e08 806
e7ae8f62 807=item C<--statistics>
576f6411 808
11f53956
ES
809Causes several statistics about the code being scanned and the
810violations found to be reported after any other output.
576f6411 811
e7ae8f62 812=item C<--statistics-only>
cb43b040 813
11f53956
ES
814Like the C<--statistics> option, but suppresses normal output and only
815shows the statistics.
cb43b040 816
e7ae8f62 817=item C<--verbose N | FORMAT>
59b05e08 818
11f53956
ES
819Sets the verbosity level or format for reporting violations. If given
820a number (C<N>), C<perlcritic> reports violations using one of the
821predefined formats described below. If given a string (C<FORMAT>), it
822is interpreted to be an actual format specification. If the
823C<--verbose> option is not specified, it defaults to either 4 or 5,
824depending on whether multiple files were given as arguments to
825C<perlcritic>. You can set the default value for this option in your
826F<.perlcriticrc> file.
827
828 Verbosity Format Specification
829 ----------- -------------------------------------------------------
830 1 "%f:%l:%c:%m\n",
831 2 "%f: (%l:%c) %m\n",
832 3 "%m at %f line %l\n",
833 4 "%m at line %l, column %c. %e. (Severity: %s)\n",
834 5 "%f: %m at line %l, column %c. %e. (Severity: %s)\n",
835 6 "%m at line %l, near '%r'. (Severity: %s)\n",
836 7 "%f: %m at line %l near '%r'. (Severity: %s)\n",
837 8 "[%p] %m at line %l, column %c. (Severity: %s)\n",
838 9 "[%p] %m at line %l, near '%r'. (Severity: %s)\n",
839 10 "%m at line %l, column %c.\n %p (Severity: %s)\n%d\n",
840 11 "%m at line %l, near '%r'.\n %p (Severity: %s)\n%d\n"
841
842Formats are a combination of literal and escape characters similar to
843the way C<sprintf> works. See L<String::Format|String::Format> for a
844full explanation of the formatting capabilities. Valid escape
845characters are:
846
847 Escape Meaning
848 ------- ------------------------------------------------------------
849 %c Column number where the violation occurred
850 %d Full diagnostic discussion of the violation
851 %e Explanation of violation or page numbers in PBP
852 %F Just the name of the file where the violation occurred.
853 %f Path to the file where the violation occurred.
854 %l Line number where the violation occurred
855 %m Brief description of the violation
856 %P Full name of the Policy module that created the violation
857 %p Name of the Policy without the Perl::Critic::Policy:: prefix
858 %r The string of source code that caused the violation
859 %s The severity level of the violation
860
861The purpose of these formats is to provide some compatibility with
862text editors that have an interface for parsing certain kinds of
863input. See L<"EDITOR INTEGRATION"> for more information about that.
59b05e08 864
e7ae8f62 865=item C<--list>
122d73f6 866
11f53956
ES
867Displays a condensed listing of all the
868L<Perl::Critic::Policy|Perl::Critic::Policy> modules that are found on
869this machine. For each Policy, the name, default severity and default
870themes are shown.
64eea91f 871
71ef7d49
ES
872=item C<--list-themes>
873
11f53956
ES
874Displays a list of all the themes of the
875L<Perl::Critic::Policy|Perl::Critic::Policy> modules that are found on
876this machine.
71ef7d49 877
e7ae8f62 878=item C<--profile-proto>
64eea91f 879
11f53956
ES
880Displays an expanded listing of all the
881L<Perl::Critic::Policy|Perl::Critic::Policy> modules that are found on
882this machine. For each Policy, the name, default severity and default
883themes are shown, as well as the name of any additional parameters
884that the Policy supports. The format is suitable as a prototype for
885your F<.perlcriticrc> file.
122d73f6 886
e7ae8f62 887=item C<--only>
e967596d 888
11f53956
ES
889Directs perlcritic to apply only Policies that are explicitly
890mentioned in your F<.perlcriticrc> file. This is useful if you want
891to use just a small subset of Policies without having to disable all
892the others. You can set the default value for this option in your
893F<.perlcriticrc> file.
e967596d 894
e7ae8f62 895=item C<--profile-strictness {warn|fatal|quiet}>
66186ba3 896
11f53956
ES
897Directs perlcritic how to treat certain recoverable problems found in
898a F<.perlcriticrc> or file specified via the C<--profile> option.
899Valid values are C<warn> (the default), C<fatal>, and C<quiet>. For
900example, perlcritic normally only warns about profiles referring to
901non-existent Policies, but this option can make this situation fatal.
902You can set the default value for this option in your F<.perlcriticrc>
903file.
66186ba3 904
e7ae8f62 905=item C<--count>
faa35de4 906
0bcb38c0
JRT
907=item C<-C>
908
11f53956
ES
909Display only the number of violations for each file. Use this feature
910to get a quick handle on where a large pile of code might need the
911most attention.
faa35de4 912
e7ae8f62 913=item C<--Safari>
59b05e08
JRT
914
915Report "Perl Best Practice" citations as section numbers from
11f53956
ES
916L<http://safari.oreilly.com> instead of page numbers from the actual
917book. NOTE: This feature is not implemented yet.
59b05e08 918
e7ae8f62 919=item C<--color>
faa35de4 920
89b50090
ES
921This option is on when outputting to a tty. When set, Severity 5 and 4 are
922colored red and yellow, respectively. Colorization only happens if
923L<Term::ANSIColor|Term::ANSIColor> is installed and it only works on
924non-Windows environments. Negate this switch to disable color. You can set
925the default value for this option in your F<.perlcriticrc> file.
faa35de4 926
ae9b3404
ES
927Can also be specified as C<--colour>.
928
89b50090
ES
929=item C<--pager PAGER>
930
931If set, perlcritic will pipe it's output to the given PAGER.
932
933Setting a pager turns off color by default. You will have to turn color on
934manually.
935
e7ae8f62 936=item C<--doc PATTERN>
6332a5f1 937
11f53956
ES
938Displays the perldoc for all
939L<Perl::Critic::Policy|Perl::Critic::Policy> modules that match
940C<m/PATTERN/imx>. Since Policy modules tend to have rather long
941names, this just provides a more convenient way to say something like:
942C<"perldoc Perl::Critic::Policy::ValuesAndExpressions::RequireUpperCaseHeredocTerminator">
6332a5f1
JRT
943at the command prompt.
944
e7ae8f62 945=item C<--quiet>
8b5892fc 946
1c5955e4 947Suppress the "source OK" message when no violations are found.
8b5892fc 948
e7ae8f62 949=item C<--help>
59b05e08 950
faa35de4 951=item C<-?>
59b05e08 952
0bcb38c0
JRT
953=item C<-H>
954
59b05e08
JRT
955Displays a brief summary of options and exits.
956
e7ae8f62 957=item C<--options>
bbcf8061 958
11f53956
ES
959Displays the descriptions of the options and exits. While this output
960is long, it it nowhere near the length of the output of C<--man>.
bbcf8061 961
e7ae8f62 962=item C<--man>
59b05e08 963
c165f991 964Displays the complete C<perlcritic> manual and exits.
59b05e08 965
eb4540f0 966=item C<--version>
59b05e08 967
faa35de4 968=item C<-V>
59b05e08 969
c165f991 970Displays the version number of C<perlcritic> and exits.
59b05e08
JRT
971
972=back
973
974=head1 CONFIGURATION
975
11f53956
ES
976Most of the settings for Perl::Critic and each of the Policy modules
977can be controlled by a configuration file. The default configuration
978file is called F<.perlcriticrc>. C<perlcritic> will look for this
979file in the current directory first, and then in your home directory.
980Alternatively, you can set the C<PERLCRITIC> environment variable to
981explicitly point to a different file in another location. If none of
982these files exist, and the C<--profile> option is not given on the
983command-line, then all Policies will be loaded with their default
984configuration.
985
986The format of the configuration file is a series of INI-style blocks
987that contain key-value pairs separated by "=". Comments should start
988with "#" and can be placed on a separate line or after the name-value
989pairs if you desire.
990
991Default settings for perlcritic itself can be set B<before the first
992named block.> For example, putting any or all of these at the top of
993your F<.perlcriticrc> file will set the default value for the
994corresponding command-line argument.
995
996 severity = 3 #Integer or named level
997 only = 1 #Zero or One
998 force = 0 #Zero or One
999 verbose = 4 #Integer or format spec
1000 top = 50 #A positive integer
1001 theme = (pbp + security) * bugs #A theme expression
1002 include = NamingConventions ClassHierarchies #Space-delimited list
1003 exclude = Variables Modules::RequirePackage #Space-delimited list
4a24d03a 1004
7711a331 1005The remainder of the configuration file is a series of blocks like this:
59b05e08 1006
11f53956
ES
1007 [Perl::Critic::Policy::Category::PolicyName]
1008 severity = 1
1009 set_themes = foo bar
1010 add_themes = baz
1011 arg1 = value1
1012 arg2 = value2
1013
1014C<Perl::Critic::Policy::Category::PolicyName> is the full name of a
1015module that implements the policy. The Policy modules distributed
1016with Perl::Critic have been grouped into categories according to the
1017table of contents in Damian Conway's book B<Perl Best Practices>. For
1018brevity, you can omit the C<'Perl::Critic::Policy'> part of the module
1019name.
1020
1021C<severity> is the level of importance you wish to assign to the
1022Policy. All Policy modules are defined with a default severity value
1023ranging from 1 (least severe) to 5 (most severe). However, you may
1024disagree with the default severity and choose to give it a higher or
1025lower severity, based on your own coding philosophy. You can set the
1026C<severity> to an integer from 1 to 5, or use one of the equivalent
1027names:
1028
1029 SEVERITY NAME ...is equivalent to... SEVERITY NUMBER
1030 ----------------------------------------------------
1031 gentle 5
1032 stern 4
1033 harsh 3
1034 cruel 2
1035 brutal 1
1036
1037C<set_themes> sets the theme for the Policy and overrides its default
1038theme. The argument is a string of one or more whitespace-delimited
1039alphanumeric words. Themes are case-insensitive. See L<"POLICY
1040THEMES"> for more information.
1041
1042C<add_themes> appends to the default themes for this Policy. The
1043argument is a string of one or more whitespace-delimited words.
1044Themes are case-insensitive. See L<"POLICY THEMES"> for more
faa35de4
JRT
1045information.
1046
11f53956
ES
1047The remaining key-value pairs are configuration parameters that will
1048be passed into the constructor of that Policy. The constructors for
1049most Policy modules do not support arguments, and those that do should
1050have reasonable defaults. See the documentation on the appropriate
1051Policy module for more details.
faa35de4 1052
11f53956
ES
1053Instead of redefining the severity for a given Policy, you can
1054completely disable a Policy by prepending a '-' to the name of the
1055module in your configuration file. In this manner, the Policy will
1056never be loaded, regardless of the C<--severity> given on the command
1057line.
59b05e08 1058
1e7b8681 1059A simple configuration might look like this:
59b05e08 1060
11f53956
ES
1061 #--------------------------------------------------------------
1062 # I think these are really important, so always load them
1063
1064 [TestingAndDebugging::RequireUseStrict]
1065 severity = 5
59b05e08 1066
11f53956
ES
1067 [TestingAndDebugging::RequireUseWarnings]
1068 severity = 5
59b05e08 1069
11f53956
ES
1070 #--------------------------------------------------------------
1071 # I think these are less important, so only load when asked
59b05e08 1072
11f53956
ES
1073 [Variables::ProhibitPackageVars]
1074 severity = 2
59b05e08 1075
11f53956
ES
1076 [ControlStructures::ProhibitPostfixControls]
1077 allow = if unless # My custom configuration
1078 severity = cruel # Same as "severity = 2"
59b05e08 1079
11f53956
ES
1080 #--------------------------------------------------------------
1081 # Give these policies a custom theme. I can activate just
1082 # these policies by saying "perlcritic --theme 'larry || curly'"
59b05e08 1083
11f53956
ES
1084 [Modules::RequireFilenameMatchesPackage]
1085 add_themes = larry
7b84ff16 1086
11f53956
ES
1087 [TestingAndDebugging::RequireTestLabels]
1088 add_themes = curly moe
7b84ff16 1089
11f53956
ES
1090 #--------------------------------------------------------------
1091 # I do not agree with these at all, so never load them
7b84ff16 1092
11f53956
ES
1093 [-NamingConventions::ProhibitMixedCaseVars]
1094 [-NamingConventions::ProhibitMixedCaseSubs]
59b05e08 1095
11f53956
ES
1096 #--------------------------------------------------------------
1097 # For all other Policies, I accept the default severity,
1098 # so no additional configuration is required for them.
59b05e08 1099
11f53956
ES
1100Note that all policies included with the Perl::Critic distribution
1101that have integer parameters accept underscores ("_") in their values,
1102as with Perl numeric literals. For example,
1e7b8681 1103
11f53956
ES
1104 [ValuesAndExpressions::RequireNumberSeparators]
1105 min_value = 1_000
ced050bc 1106
11f53956
ES
1107For additional configuration examples, see the F<perlcriticrc> file
1108that is included in this F<examples> directory of this distribution.
ced050bc 1109
11f53956
ES
1110Damian Conway's own Perl::Critic configuration is also included in
1111this distribution as F<examples/perlcriticrc-conway>.
b87fc7eb 1112
75d77367 1113
59b05e08
JRT
1114=head1 THE POLICIES
1115
11f53956
ES
1116A large number of Policy modules are distributed with Perl::Critic.
1117They are described briefly in the companion document
1118L<Perl::Critic::PolicySummary|Perl::Critic::PolicySummary> and in more
1119detail in the individual modules themselves. Say C<"perlcritic --doc
1120PATTERN"> to see the perldoc for all Policy modules that match the
1121regex C<m/PATTERN/imx>
1122
1123There are a number of distributions of additional policies on CPAN.
1124If L<Perl::Critic|Perl::Critic> doesn't contain a policy that you
1125want, some one may have already written it. See L<Perl::Critic/"SEE
1126ALSO"> for a list of some of these distributions.
e7ff023b 1127
a41e8614 1128
faa35de4
JRT
1129=head1 POLICY THEMES
1130
11f53956
ES
1131Each Policy is defined with one or more "themes". Themes can be used
1132to create arbitrary groups of Policies. They are intended to provide
1133an alternative mechanism for selecting your preferred set of Policies.
1134For example, you may wish disable a certain set of Policies when
1135analyzing test scripts. Conversely, you may wish to enable only a
1136specific subset of Policies when analyzing modules.
1137
1138The Policies that ship with Perl::Critic are have been divided into
1139the following themes. This is just our attempt to provide some basic
1140logical groupings. You are free to invent new themes that suit your
1141needs.
1142
1143 THEME DESCRIPTION
1144 ------------------------------------------------------------------------
1145 core All policies that ship with Perl::Critic
1146 pbp Policies that come directly from "Perl Best Practices"
1147 bugs Policies that that prevent or reveal bugs
1148 maintenance Policies that affect the long-term health of the code
1149 cosmetic Policies that only have a superficial effect
1150 complexity Policies that specificaly relate to code complexity
1151 security Policies that relate to security issues
1152 tests Policies that are specific to test scripts
1153
1154Say C<"perlcritic --list"> to get a listing of all available policies
1155and the themes that are associated with each one. You can also change
1156the theme for any Policy in your F<.perlcriticrc> file. See the
1157L<"CONFIGURATION"> section for more information about that.
1158
1159Using the C<--theme> command-line option, you can create an
1160arbitrarily complex rule that determines which Policies to apply.
1161Precedence is the same as regular Perl code, and you can use
1162parentheses to enforce precedence as well. Supported operators are:
1163
1164 Operator Altertative Example
1165 -----------------------------------------------------------------
1166 && and 'pbp && core'
1167 || or 'pbp || (bugs && security)'
1168 ! not 'pbp && ! (portability || complexity)'
1169
1170Theme names are case-insensitive. If the C<--theme> is set to an
1171empty string, then it evaluates as true all Policies.
1172
faa35de4 1173
59b05e08
JRT
1174=head1 BENDING THE RULES
1175
59b05e08
JRT
1176Perl::Critic takes a hard-line approach to your code: either you
1177comply or you don't. In the real world, it is not always practical
1178(or even possible) to fully comply with coding standards. In such
1179cases, it is wise to show that you are knowingly violating the
1180standards and that you have a Damn Good Reason (DGR) for doing so.
1181
1182To help with those situations, you can direct Perl::Critic to ignore
1183certain lines or blocks of code by using pseudo-pragmas:
1184
67a7fe92
ES
1185 require 'LegacyLibaray1.pl'; ## no critic
1186 require 'LegacyLibrary2.pl'; ## no critic
59b05e08 1187
67a7fe92 1188 for my $element (@list) {
59b05e08 1189
67a7fe92 1190 ## no critic
59b05e08 1191
67a7fe92
ES
1192 $foo = ""; #Violates 'ProhibitEmptyQuotes'
1193 $barf = bar() if $foo; #Violates 'ProhibitPostfixControls'
1194 #Some more evil code...
59b05e08 1195
67a7fe92 1196 ## use critic
59b05e08 1197
67a7fe92
ES
1198 #Some good code...
1199 do_something($_);
1200 }
59b05e08 1201
11f53956
ES
1202The C<"## no critic"> comments direct Perl::Critic to ignore the
1203remaining lines of code until the end of the current block, or until a
1204C<"## use critic"> comment is found (whichever comes first). If the
1205C<"## no critic"> comment is on the same line as a code statement,
1206then only that line of code is overlooked. To direct perlcritic to
1207ignore the C<"## no critic"> comments, use the C<--force> option.
77de3405 1208
11f53956
ES
1209A bare C<"## no critic"> comment disables all the active Policies. If
1210you wish to disable only specific Policies, add a list of Policy names
1211as arguments just as you would for the C<"no strict"> or C<"no
1212warnings"> pragma. For example, this would disable the
1213C<ProhibitEmptyQuotes> and C<ProhibitPostfixControls> policies until
1214the end of the block or until the next C<"## use critic"> comment
1215(whichever comes first):
c70a9ff6 1216
11f53956 1217 ## no critic (EmptyQuotes, PostfixControls);
c70a9ff6 1218
11f53956
ES
1219 # Now exempt from ValuesAndExpressions::ProhibitEmptyQuotes
1220 $foo = "";
64eea91f 1221
11f53956
ES
1222 # Now exempt ControlStructures::ProhibitPostfixControls
1223 $barf = bar() if $foo;
64eea91f 1224
11f53956
ES
1225 # Still subject to ValuesAndExpression::RequireNumberSeparators
1226 $long_int = 10000000000;
c70a9ff6 1227
11f53956
ES
1228Since the Policy names are matched against the C<"## no critic">
1229arguments as regular expressions, you can abbreviate the Policy names
1230or disable an entire family of Policies in one shot like this:
c70a9ff6 1231
11f53956 1232 ## no critic (NamingConventions)
c70a9ff6 1233
11f53956
ES
1234 # Now exempt from NamingConventions::ProhibitMixedCaseVars
1235 my $camelHumpVar = 'foo';
64eea91f 1236
11f53956
ES
1237 # Now exempt from NamingConventions::ProhibitMixedCaseSubs
1238 sub camelHumpSub {}
c70a9ff6 1239
11f53956
ES
1240The argument list must be enclosed in parentheses and must contain one
1241or more comma-separated barewords (i.e. don't use quotes). The C<"##
1242no critic"> pragmas can be nested, and Policies named by an inner
1243pragma will be disabled along with those already disabled an outer
1244pragma.
c70a9ff6 1245
11f53956
ES
1246Some Policies like C<Subroutines::ProhibitExcessComplexity> apply to
1247an entire block of code. In those cases, C<"## no critic"> must
1248appear on the line where the violation is reported. For example:
35892a39 1249
11f53956
ES
1250 sub complicated_function { ## no critic (ProhibitExcessComplexity)
1251 # Your code here...
1252 }
1253
1254Some Policies like C<Documentation::RequirePodSections> apply to the
1255entire document, in which case violations are reported at line 1. But
1256if the file requires a shebang line, it is impossible to put C<"## no
1257critic"> on the first line of the file. This is a known limitation
1258and it will be addressed in a future release. As a workaround, you
1259can disable the affected policies at the command-line or in your
1260F<.perlcriticrc> file. But beware that this will affect the analysis
1261of B<all> files.
35892a39 1262
11f53956
ES
1263Use this feature wisely. C<"## no critic"> should be used in the
1264smallest possible scope, or only on individual lines of code. And you
1265should always be as specific as possible about which policies you want
1266to disable (i.e. never use a bare C<"## no critic">). If Perl::Critic
1267complains about your code, try and find a compliant solution before
1268resorting to this feature.
35892a39 1269
1c5955e4 1270
59b05e08
JRT
1271=head1 EDITOR INTEGRATION
1272
11f53956
ES
1273For ease-of-use, C<perlcritic> can be integrated with your favorite
1274text editor. The output-formatting capabilities of C<perlcritic> are
1275specifically intended for use with the "grep" or "compile" modes
1276available in editors like C<emacs> and C<vim>. In these modes, you
1277can run an arbitrary command and the editor will parse the output into
1278an interactive buffer that you can click on and jump to the relevant
1279line of code.
59b05e08 1280
fb87b5f0
JRT
1281The Perl::Critic team thanks everyone who has helped integrate Perl-Critic
1282with their favorite editor. Your contributions in particular have made
1283Perl-Critic a convenient and user-friendly tool for Perl developers of all
1284stripes. We sincerely appreciate your hard work.
1285
11f53956 1286
59b05e08
JRT
1287=head2 EMACS
1288
11f53956
ES
1289Joshua ben Jore has authored a minor-mode for emacs that allows you to
1290run perlcritic on the current region or buffer. You can run it on
1291demand, or configure it to run automatically when you save the buffer.
1292The output appears in a hot-linked compiler buffer. The code and
1293installation instructions can be found in the F<extras> directory
1294inside this distribution.
1295
59b05e08
JRT
1296
1297=head2 VIM
1298
77de3405
JRT
1299Scott Peshak has published F<perlchecker.vim>, which is available at
1300L<http://www.vim.org/scripts/script.php?script_id=1731>.
59b05e08 1301
11f53956 1302
57d6a8e3
JRT
1303=head2 gVIM
1304
11f53956
ES
1305Fritz Mehner recently added support for C<perlcritic> to his fantastic
1306gVIM plugin. In addition to providing a very Perlish IDE, Fritz's
1307plugin enables one-click access to C<perlcritic> and many other very
1308useful utilities. And all is seamlessly integrated into the editor.
1309See L<http://lug.fh-swf.de/vim/vim-perl/screenshots-en.html> for
1310complete details.
1311
57d6a8e3 1312
5b0502a0
JRT
1313=head2 EPIC
1314
11f53956
ES
1315EPIC is an open source Perl IDE based on the Eclipse platform.
1316Features supported are syntax highlighting, on-the-fly syntax check,
1317content assist, perldoc support, source formatter, templating support
1318and a Perl debugger. Go to L<http://e-p-i-c.sourceforge.net> for more
1319information about EPIC.
1320
1321The EPIC team is currently working on integration with Perl::Critic.
1322In the meantime, you can use the L<criticism|criticism> pragma and
1323EPIC will highlight violations whenever it does a syntax check on your
1324code. I haven't tried this myself, but other folks say it works.
5b0502a0 1325
5b0502a0 1326
fb87b5f0
JRT
1327=head2 BBEdit
1328
11f53956
ES
1329Josh Clark has produced an excellent Perl-Critic plugin for BBEdit. A
1330copy is included in this distribution at
1331F<extras/perl_critic_for_bbedit-1_0.zip>. See
1332L<http://beta.bigmedium.com/projects/bbedit-perl-critic/index.shtml>
1333for screenshots and additional installation info. Apple users
1334rejoice!
1335
775df202
JRT
1336
1337=head2 Komodo
1338
11f53956
ES
1339Komodo is a proprietary IDE for Perl and several other dynamic
1340languages. Free trial copies of Komodo can be obtained from the
1341ActiveState website at L<http://www.activestate.com>. For instructions
1342on integrating F<perlcritic> with Komodo, see
1343F<extras/KomodoIntegration.pod> in this distribution.
1344
fb87b5f0 1345
59b05e08
JRT
1346=head1 EXIT STATUS
1347
11f53956
ES
1348If C<perlcritic> has any errors itself, exits with status == 1. If
1349there are no errors, but C<perlcritic> finds Policy violations in your
1350source code, exits with status == 2. If there were no errors and no
1351violations were found, exits with status == 0.
1352
59b05e08 1353
11f53956 1354=head1 THE L<Perl::Critic|Perl::Critic> PHILOSOPHY
b87b00dd 1355
67a7fe92
ES
1356=over
1357
11f53956
ES
1358Coding standards are deeply personal and highly subjective. The goal
1359of Perl::Critic is to help you write code that conforms with a set of
1360best practices. Our primary goal is not to dictate what those
1361practices are, but rather, to implement the practices discovered by
1362others. Ultimately, you make the rules -- Perl::Critic is merely a
1363tool for encouraging consistency. If there is a policy that you think
1364is important or that we have overlooked, we would be very grateful for
1365contributions, or you can simply load your own private set of policies
1366into Perl::Critic.
67a7fe92
ES
1367
1368=back
b87b00dd 1369
11f53956 1370
4d19da19 1371=head1 EXTENDING THE CRITIC
5deaba5e 1372
11f53956
ES
1373The modular design of Perl::Critic is intended to facilitate the
1374addition of new Policies. You'll need to have some understanding of
1375L<PPI|PPI>, but most Policy modules are pretty straightforward and
1376only require about 20 lines of code, and half of those lines are
1377simple use statements and simple declarations.. Please see the
1378L<Perl::Critic::DEVELOPER|Perl::Critic::DEVELOPER> file included in
1379this distribution for a step-by-step demonstration of how to create
1380new Policy modules.
1381
1382If you develop any new Policy modules, feel free to send them to C<<
1383<thaljef@cpan.org> >> and I'll be happy to put them into the
1384Perl::Critic distribution. Or if you would like to work on the
1385Perl::Critic project directly, check out our repository at
1386L<http://perlcritic.tigris.org>. To subscribe to our mailing list,
1387send a message to C<< <dev-subscribe@perlcritic.tigris.org> >>.
1388
1389The Perl::Critic team is also available for hire. If your
1390organization has its own coding standards, we can create custom
1391Policies to enforce your local guidelines. Or if your code base is
1392prone to a particular defect pattern, we can design Policies that will
1393help you catch those costly defects B<before> they go into production.
1394To discuss your needs with the Perl::Critic team, just contact C<<
1395<thaljef@cpan.org> >>.
1396
5deaba5e 1397
25e89cf1
ES
1398=head1 CONTACTING THE DEVELOPMENT TEAM
1399
1400You are encouraged to subscribe to the mailing list; send a message to
1401C<< <users-subscribe@perlcritic.tigris.org> >>. See also
1402L<the archives|http://perlcritic.tigris.org/servlets/SummarizeList?listName=users>.
1403You can also contact the author at C<< <thaljef@cpan.org> >>.
1404
11f53956
ES
1405At least one member of the development team has started hanging around
1406in L<irc://irc.perl.org/#perlcritic>.
1407
098d393b 1408
3123bf46
ES
1409=head1 SEE ALSO
1410
11f53956
ES
1411There are a number of distributions of additional Policies available.
1412A few are listed here:
3123bf46 1413
11f53956
ES
1414L<Perl::Critic::More|Perl::Critic::More>
1415L<Perl::Critic::Bangs|Perl::Critic::Bangs>
1416L<Perl::Critic::Lax|Perl::Critic::Lax>
1417L<Perl::Critic::StricterSubs|Perl::Critic::StricterSubs>
1418L<Perl::Critic::Swift|Perl::Critic::Swift>
3123bf46 1419
d032ff5e
JRT
1420These distributions enable you to use Perl::Critic in your unit tests:
1421
11f53956
ES
1422L<Test::Perl::Critic|Test::Perl::Critic>
1423L<Test::Perl::Critic::Progressive|Test::Perl::Critic::Progressive>
d032ff5e 1424
3123bf46
ES
1425There are also a couple of distributions that will install all the
1426Perl::Critic related modules known to the development team:
1427
11f53956
ES
1428L<Bundle::Perl::Critic|Bundle::Perl::Critic>
1429L<Task::Perl::Critic|Task::Perl::Critic>
1430
3123bf46 1431
59b05e08
JRT
1432=head1 BUGS
1433
11f53956
ES
1434Scrutinizing Perl code is hard for humans, let alone machines. If you
1435find any bugs, particularly false-positives or false-negatives from a
59b05e08
JRT
1436Perl::Critic::Policy, please submit them to
1437L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Perl-Critic>. Thanks.
1438
fc0fffee
ES
1439Most policies will produce false-negatives if they cannot understand a
1440particular block of code.
1441
11f53956 1442
59b05e08
JRT
1443=head1 CREDITS
1444
11f53956
ES
1445Adam Kennedy - For creating L<PPI|PPI>, the heart and soul of
1446L<Perl::Critic|Perl::Critic>.
59b05e08 1447
b87b00dd 1448Damian Conway - For writing B<Perl Best Practices>, finally :)
59b05e08 1449
b87b00dd 1450Chris Dolan - For contributing the best features and Policy modules.
59b05e08 1451
7711a331
JRT
1452Andy Lester - Wise sage and master of all-things-testing.
1453
1454Elliot Shank - The self-proclaimed quality freak.
1455
b87b00dd 1456Giuseppe Maxia - For all the great ideas and positive encouragement.
59b05e08 1457
b87b00dd 1458and Sharon, my wife - For putting up with my all-night code sessions.
59b05e08 1459
11f53956 1460
59b05e08
JRT
1461=head1 AUTHOR
1462
1463Jeffrey Ryan Thalhammer <thaljef@cpan.org>
1464
11f53956 1465
59b05e08
JRT
1466=head1 COPYRIGHT
1467
20dfddeb 1468Copyright (c) 2005-2008 Jeffrey Ryan Thalhammer. All rights reserved.
59b05e08 1469
11f53956
ES
1470This program is free software; you can redistribute it and/or modify
1471it under the same terms as Perl itself. The full text of this license
1472can be found in the LICENSE file included with this module.
59b05e08
JRT
1473
1474=cut
737d3b65 1475
7711a331 1476##############################################################################
737d3b65
CD
1477# Local Variables:
1478# mode: cperl
1479# cperl-indent-level: 4
1480# fill-column: 78
1481# indent-tabs-mode: nil
1482# c-indentation-style: bsd
1483# End:
96fed375 1484# ex: set ts=8 sts=4 sw=4 tw=78 ft=perl expandtab shiftround :