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