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