3 ##############################################################################
4 # $URL: http://perlcritic.tigris.org/svn/perlcritic/trunk/Perl-Critic/bin/perlcritic $
5 # $Date: 2008-07-03 10:19:10 -0500 (Thu, 03 Jul 2008) $
8 ##############################################################################
10 ## no critic (ErrorHandling::RequireUseOfExceptions)
17 use English qw< -no_match_vars >;
20 use Getopt::Long qw< GetOptions >;
21 use List::Util qw< first >;
22 use Pod::Usage qw< pod2usage >;
24 use Perl::Critic::Exception::Parse ();
25 use Perl::Critic::Utils qw<
26 :characters :severities policy_short_name
27 $DEFAULT_VERBOSITY $DEFAULT_VERBOSITY_WITH_FILE_NAME
29 use Perl::Critic::Violation qw<>;
31 #-----------------------------------------------------------------------------
33 our $VERSION = '1.088';
35 Readonly::Scalar my $DEFAULT_VIOLATIONS_FOR_TOP => 20;
37 Readonly::Scalar my $EXIT_SUCCESS => 0;
38 Readonly::Scalar my $EXIT_NO_FILES => 1;
39 Readonly::Scalar my $EXIT_HAD_VIOLATIONS => 2;
40 Readonly::Scalar my $EXIT_HAD_FILE_PROBLEMS => 3;
42 #-----------------------------------------------------------------------------
43 # Begin script. Don't run when loaded as a library
47 exit run() if not caller;
49 #-----------------------------------------------------------------------------
53 my %options = get_options();
54 @FILES = get_input(@ARGV);
56 my ($violations, $had_error_in_file) = critique(\%options, @FILES);
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;
65 #-----------------------------------------------------------------------------
69 my %opts = _parse_command_line();
70 _dispatch_special_requests( %opts );
71 _validate_options( %opts );
73 # Convert severity shortcut options. If multiple shortcuts
74 # are given, the lowest one wins. If an explicit --severity
75 # option has been given, then the shortcuts are ignored. The
76 # @SEVERITY_NAMES variable is exported by Perl::Critic::Utils.
77 $opts{severity} ||= first { exists $opts{$_} } @SEVERITY_NAMES;
79 first { exists $opts{$_} } ($SEVERITY_LOWEST .. $SEVERITY_HIGHEST);
82 # If --top is specified, default the severity level to 1, unless an
83 # explicit severity is defined. This provides us flexibility to
84 # report top-offenders across just some or all of the severity levels.
85 # We also default the --top count to twenty if none is given
86 if ( exists $opts{top} ) {
87 $opts{severity} ||= 1;
88 $opts{top} ||= $DEFAULT_VIOLATIONS_FOR_TOP;
91 #Override profile, if --noprofile is specified
92 if ( exists $opts{noprofile} ) {
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;
104 #-----------------------------------------------------------------------------
106 sub _parse_command_line {
107 my %opts = ( -color => 1 );
108 my @opt_specs = _get_option_specification();
109 Getopt::Long::Configure('no_ignore_case');
110 GetOptions( \%opts, @opt_specs ) || pod2usage(); #Exits
114 #-----------------------------------------------------------------------------
116 sub _dispatch_special_requests {
118 if ( $opts{help} ) { pod2usage( -verbose => 0 ) } #Exits
119 if ( $opts{options} ) { pod2usage( -verbose => 1 ) } #Exits
120 if ( $opts{man} ) { pod2usage( -verbose => 2 ) } #Exits
121 if ( $opts{version} ) { print "$VERSION\n"; exit 0; } #Exits
122 if ( $opts{list} ) { render_policy_listing(); } #Exits
123 if ( $opts{'list-themes'} ) { render_theme_listing(); } #Exits
124 if ( $opts{'profile-proto'} ) { render_profile_prototype(); } #Exits
125 if ( $opts{doc} ) { policy_docs( $opts{doc} ); } #Exits
129 #-----------------------------------------------------------------------------
131 sub _validate_options {
136 if ( $opts{noprofile} && $opts{profile} ) {
137 $msg .= qq{Warning: Cannot use -noprofile with -profile option.\n};
140 if ( $opts{verbose} && $opts{verbose} !~ m{(?: \d+ | %[mfFlcedrpPs] )}mx) {
141 $msg .= qq<Warning: --verbose arg "$opts{verbose}" looks odd. >;
142 $msg .= qq<Perhaps you meant to say "--verbose 3 $opts{verbose}"\n>;
145 if ( exists $opts{top} && $opts{top} < 0 ) {
146 $msg .= qq<Warning: --top argument "$opts{top}" is negative. >;
147 $msg .= qq<Perhaps you meant to say "$opts{top} --top".\n>;
151 exists $opts{severity}
153 $opts{severity} < $SEVERITY_LOWEST
154 || $opts{severity} > $SEVERITY_HIGHEST
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>;
164 pod2usage( -exitstatus => 1, -message => $msg, -verbose => 0); #Exits
171 #-----------------------------------------------------------------------------
177 if ( !@args || (@args == 1 && $args[0] eq q{-}) ) {
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> };
183 # Notice if STDIN was closed (pipe error, etc)
184 if ( ! defined $code_string ) {
188 $code_string =~ m{ \S+ }mx || die qq{Nothing to critique.\n};
189 return \$code_string; #Convert to SCALAR ref for PPI
193 # Test to make sure all the specified files or directories
194 # actually exist. If any one of them is bogus, then die.
195 if ( my $nonexistant = first { ! -e $_ } @args ) {
196 my $msg = qq{No such file or directory: '$nonexistant'};
197 pod2usage( -exitstatus => 1, -message => $msg, -verbose => 0);
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.
204 return map { -d $_ ? Perl::Critic::Utils::all_perl_files($_) : $_ } @args;
208 #------------------------------------------------------------------------------
212 my ( $opts_ref, @files ) = @_;
213 @files || die "No perl files were found.\n";
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.
221 require Perl::Critic;
222 $CRITIC = Perl::Critic->new( %{$opts_ref} );
223 $CRITIC->policies() || die "No policies selected.\n";
225 my $number_of_violations = undef;
226 my $had_error_in_file = 0;
228 for my $file (@files) {
231 my @violations = $CRITIC->critique($file);
232 $number_of_violations += scalar @violations;
234 if (not $opts_ref->{'-statistics-only'}) {
235 render_report( $file, $opts_ref, @violations )
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>;
244 elsif ($EVAL_ERROR) {
245 # P::C::Exception::Fatal includes the stack trace in its
247 die qq<Fatal error while critiquing "$file": $EVAL_ERROR\n>;
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>;
257 if ( $opts_ref->{-statistics} or $opts_ref->{'-statistics-only'} ) {
258 my $stats = $CRITIC->statistics();
259 report_statistics( $opts_ref, $stats );
262 return $number_of_violations, $had_error_in_file;
265 #------------------------------------------------------------------------------
269 my ( $file, $opts_ref, @violations ) = @_;
271 # Only report the number of violations, if asked.
272 my $number_of_violations = scalar @violations;
273 if( $opts_ref->{-count} ){
274 ref $file || print "$file: ";
275 print "$number_of_violations\n";
276 return $number_of_violations;
279 # Hail all-clear unless we should shut up.
280 if( !@violations && !$opts_ref->{-quiet} ) {
281 ref $file || print "$file ";
286 # Otherwise, format and print violations
287 my $verbosity = $CRITIC->config->verbose();
288 # $verbosity can be numeric or string, so use "eq" for comparison;
290 ($verbosity eq $DEFAULT_VERBOSITY && @FILES > 1)
291 ? $DEFAULT_VERBOSITY_WITH_FILE_NAME
293 my $fmt = Perl::Critic::Utils::verbosity_to_format( $verbosity );
294 if (not -f $file) { $fmt =~ s{\%[fF]}{STDIN}mx; } #HACK!
295 Perl::Critic::Violation::set_format( $fmt );
297 my $color = $CRITIC->config->color();
298 print $color ? _colorize_by_severity(@violations) : @violations;
300 return $number_of_violations;
303 #-----------------------------------------------------------------------------
305 sub report_statistics {
306 my ($opts_ref, $statistics) = @_;
309 not $opts_ref->{'-statistics-only'}
311 $statistics->total_violations()
312 or not $opts_ref->{-quiet} and $statistics->modules()
315 print "\n"; # There's prior output that we want to separate from.
318 print _commaify($statistics->modules()), " files.\n";
319 print _commaify($statistics->subs()), " subroutines/methods.\n";
320 print _commaify($statistics->statements_other_than_subs()), " statements.\n";
321 print _commaify($statistics->lines()), " lines.\n";
323 my $average_sub_mccabe = $statistics->average_sub_mccabe();
324 if (defined $average_sub_mccabe) {
326 "\nAverage McCabe score of subroutines was %.2f.\n",
332 print _commaify($statistics->total_violations()), " violations.\n";
334 my $violations_per_file = $statistics->violations_per_file();
335 if (defined $violations_per_file) {
337 "Violations per file was %.3f.\n",
338 $violations_per_file;
340 my $violations_per_statement = $statistics->violations_per_statement();
341 if (defined $violations_per_statement) {
343 "Violations per statement was %.3f.\n",
344 $violations_per_statement;
346 my $violations_per_line = $statistics->violations_per_line_of_code();
347 if (defined $violations_per_line) {
349 "Violations per line of code was %.3f.\n",
350 $violations_per_line;
353 if ( $statistics->total_violations() ) {
356 my %severity_violations = %{ $statistics->violations_by_severity() };
357 foreach my $severity ( reverse sort keys %severity_violations ) {
359 _commaify($severity_violations{$severity}),
360 " severity $severity violations.\n";
365 my %policy_violations = %{ $statistics->violations_by_policy() };
366 foreach my $policy ( sort keys %policy_violations ) {
368 _commaify($policy_violations{$policy}),
370 policy_short_name($policy),
378 #-----------------------------------------------------------------------------
380 # Only works for integers.
384 while ($number =~ s/ \A ( [-+]? \d+ ) ( \d{3} ) /$1,$2/xms) {
391 #-----------------------------------------------------------------------------
393 sub _get_option_specification {
431 #-----------------------------------------------------------------------------
433 sub _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 };
440 $SEVERITY_HIGHEST => 'bold red',
441 $SEVERITY_HIGH => 'yellow',
443 return map { _colorize( "$_", $color_of{$_->severity()} ) } @violations;
447 #-----------------------------------------------------------------------------
450 my ($string, $color) = @_;
451 return $string if not defined $color;
452 return Term::ANSIColor::colored( $string, $color );
455 #-----------------------------------------------------------------------------
457 sub _this_is_windows {
458 return 1 if $OSNAME =~ m/MSWin32/mx;
462 #-----------------------------------------------------------------------------
465 return -t STDOUT; ##no critic 'InteractiveTest';
468 #-----------------------------------------------------------------------------
470 sub render_policy_listing {
472 require Perl::Critic::PolicyListing;
473 require Perl::Critic;
475 my %pc_params = (-profile => $EMPTY, -severity => $SEVERITY_LOWEST);
476 my @policies = Perl::Critic->new( %pc_params )->policies();
477 my $listing = Perl::Critic::PolicyListing->new( -policies => \@policies );
482 #-----------------------------------------------------------------------------
484 sub render_theme_listing {
485 require Perl::Critic::ThemeListing;
486 require Perl::Critic;
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 );
495 #-----------------------------------------------------------------------------
497 sub render_profile_prototype {
499 require Perl::Critic::ProfilePrototype;
500 require Perl::Critic;
502 my %pc_params = (-profile => $EMPTY, -severity => $SEVERITY_LOWEST);
503 my @policies = Perl::Critic->new( %pc_params )->policies();
504 my $prototype = Perl::Critic::ProfilePrototype->new( -policies => \@policies );
509 #-----------------------------------------------------------------------------
514 require Perl::Critic;
516 my %pc_params = (-profile => $EMPTY, -severity => $SEVERITY_LOWEST);
517 my @policies = Perl::Critic::Config->new( %pc_params )->policies();
518 my @matches = grep { $_ =~ m/$pattern/imx } @policies;
520 for my $matching_policy ( @matches ) {
521 my @perldoc_cmd = qw(perldoc -T); #-T means don't send to pager
522 system @perldoc_cmd, ref $matching_policy;
531 #-----------------------------------------------------------------------------
535 =for stopwords DGR INI-style vim-fu minibuffer -noprofile API -singlepolicy
536 singlepolicy -profileproto -profile-proto ben Jore formatter Peshak pbp Komodo
537 screenshots tty emacs gVIM plugin Perlish templating ActiveState
541 C<perlcritic> - Command-line interface to critique Perl source.
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]
550 [--statistics] [--statistics-only] [--verbose {number | format}]
551 [--color | --nocolor] [--quiet] {FILE | DIRECTORY | STDIN}
553 perlcritic --profile-proto
555 perlcritic { --list | --list-themes | --doc pattern [...] }
557 perlcritic { --help | --options | --man | --version }
561 C<perlcritic> is a Perl source code analyzer. It is the executable
562 front-end to the L<Perl::Critic> engine, which attempts to identify
563 awkward, hard to read, error-prone, or unconventional constructs in
564 your code. Most of the rules are based on Damian Conway's book B<Perl
565 Best Practices>. However, C<perlcritic> is B<not> limited to
566 enforcing PBP, and it will even support rules that contradict Conway.
567 All rules can easily be configured or disabled to your liking.
569 This documentation only covers how to drive this command. For all
570 other information, including how to persistently configure this
571 command so that you don't have to say so much on the command-line,
572 see the documentation for L<Perl::Critic> itself.
575 =head1 USAGE EXAMPLES
577 Before getting into all the gory details, here are some basic usage
578 examples to help get you started.
580 # Report only most severe violations (severity = 5)
581 perlcritic YourModule.pm
583 # Same as above, but read input from STDIN
586 # Recursively process all Perl files beneath directory
587 perlcritic /some/directory
589 # Report slightly less severe violations too (severity >= 4)
590 perlcritic -4 YourModule.pm
592 # Same as above, but using named severity level
593 perlcritic --stern YourModule.pm
595 # Report all violations, regardless of severity (severity >= 1)
596 perlcritic -1 YourModule.pm
598 # Same as above, but using named severity level
599 perlcritic --brutal YourModule.pm
601 # Report only violations of things from "Perl Best Practices"
602 perlcritic --theme pbp YourModule.pm
604 # Report top 20 most severe violations (severity >= 1)
605 perlcritic --top YourModule.pm
607 # Report additional violations of Policies that match m/variables/ix
608 perlcritic --include variables YourModule.pm
610 # Use defaults from somewhere other than ~/.perlcriticrc
611 perlcriticrc --profile project/specific/perlcriticrc YourModule.pm
615 The arguments are paths to the files you wish to analyze. You may
616 specify multiple files. If an argument is a directory, C<perlcritic>
617 will analyze all Perl files below the directory. If no arguments
618 are specified, then input is read from STDIN.
622 Option names can be abbreviated to uniqueness and can be stated with
623 singe or double dashes, and option values can be separated from the
624 option name by a space or '=' (as with L<Getopt::Long>). Option names
625 are also case-sensitive.
629 =item C<--profile FILE>
631 Directs C<perlcritic> to use a profile named by FILE rather than looking
632 for the default F<.perlcriticrc> file in the current directory or your
633 home directory. See L<Perl::Critic/"CONFIGURATION"> for more information.
637 Directs C<perlcritic> not to load any configuration file, thus reverting
638 to the default configuration for all Policies.
640 =item C<--severity N>
642 Directs C<perlcritic> to only apply Policies with a severity greater than
643 C<N>. Severity values are integers ranging from 1 (least severe) to 5 (most
644 severe). The default is 5. For a given C<--profile>, decreasing the
645 C<--severity> will usually produce more violations. You can set the default
646 value for this option in your F<.perlcriticrc> file. You can also redefine
647 the C<severity> for any Policy in your F<.perlcriticrc> file. See
648 L<"CONFIGURATION"> for more information.
650 =item C<-5 | -4 | -3 | -2 | -1>
652 These are numeric shortcuts for setting the C<--severity> option. For example,
653 C<"-4"> is equivalent to C<"--severity 4">. If multiple shortcuts are
654 specified, then the most restrictive one wins. If an explicit C<--severity>
655 option is also given, then all shortcut options are silently ignored. NOTE:
656 Be careful not to put one of the number severity shortcut options immediately
657 after the C<--top> flag or C<perlcritic> will interpret it as the number of
658 violations to report.
660 =item C<--severity NAME>
662 If it is difficult for you to remember whether severity "5" is the most
663 or least restrictive level, then you can use one of these named values:
665 SEVERITY NAME ...is equivalent to... SEVERITY NUMBER
666 --------------------------------------------------------
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
673 =item C<--gentle | --stern | --harsh | --cruel | --brutal>
675 These are named shortcuts for setting the C<--severity> option. For example,
676 C<"--cruel"> is equivalent to C<"--severity 2">. If multiple shortcuts are
677 specified, then the most restrictive one wins. If an explicit C<--severity>
678 option is also given, then all shortcut options are silently ignored.
680 =item C<--theme RULE>
682 Directs C<perlcritic> to apply only Policies with themes that satisfy the
683 C<RULE>. Themes are arbitrary names for groups of related policies. You can
684 combine theme names with boolean operators to create an arbitrarily complex
685 C<RULE>. For example, the following would apply only Policies that have a
686 'bugs' AND 'pbp' theme:
688 $> perlcritic --theme='bugs && pbp' MyModule.pm
690 Unless the C<--severity> option is explicitly given, setting C<--theme> silently
691 causes the C<--severity> to be set to 1. You can set the default value for
692 this option in your F<.perlcriticrc> file. See L<Perl::Critic/"POLICY THEMES">
693 for more information about themes.
695 =item C<--include PATTERN>
697 Directs C<perlcritic> to apply additional Policies that match the regex
698 C</PATTERN/imx>. Use this option to temporarily override your profile and/or
699 the severity settings at the command-line. For example:
701 perlcritic --include=layout my_file.pl
703 This would cause C<perlcritic> to apply all the C<CodeLayout::*> policies even
704 if they have a severity level that is less than the default level of 5, or
705 have been disabled in your F<.perlcriticrc> file. You can specify multiple
706 C<--include> options and you can use it in conjunction with the C<--exclude>
707 option. Note that C<--exclude> takes precedence over C<--include> when a Policy
708 matches both patterns. You can set the default value for this option in your
709 F<.perlcriticrc> file.
711 =item C<--exclude PATTERN>
713 Directs C<perlcritic> to not apply any Policy that matches the regex
714 C</PATTERN/imx>. Use this option to temporarily override your profile and/or
715 the severity settings at the command-line. For example:
717 perlcritic --exclude=strict my_file.pl
719 This would cause C<perlcritic> to not apply the C<RequireUseStrict> and
720 C<ProhibitNoStrict> Policies even though they have the highest severity level.
721 You can specify multiple C<--exclude> options and you can use it in conjunction
722 with the C<--include> option. Note that C<--exclude> takes precedence over
723 C<--include> when a Policy matches both patterns. You can set the default
724 value for this option in your F<.perlcriticrc> file.
726 =item C<--single-policy PATTERN>
728 Directs C<perlcritic> to apply just one Policy module matching the regex
729 C</PATTERN/imx>, and exclude all other Policies. This option has precedence
730 over the C<--severity>, C<--theme>, C<--include>, C<--exclude>, and C<--only>
731 options. For example:
733 perlcritic --single-policy=nowarnings my_file.pl
735 This would cause C<perlcritic> to apply just the C<ProhibitNoWarnings> Policy,
736 regardless of the severity level setting. No other Policies would be applied.
738 This is equivalent to what one might intend by...
740 perlcritic --exclude=. --include=nowarnings my_file.pl
742 ... but this won't work because the C<--exclude> option overrides the
745 The equivalent of this option can be accomplished by creating a custom profile
746 containing only the desired policy and then running...
748 perlcritic --profile=customprofile --only my_file.pl
752 Directs C<perlcritic> to report only the top C<N> Policy violations in each
753 file, ranked by their severity. If C<N> is not specified, it defaults to 20.
754 If the C<--severity> option (or one of the shortcuts) is not explicitly given,
755 the C<--top> option implies that the minimum severity level is "1"
756 (i.e. "brutal"). Users can redefine the severity for any Policy in their
757 F<.perlcriticrc> file. See L<"CONFIGURATION"> for more information. You can
758 set the default value for this option in your F<.perlcriticrc> file. NOTE: Be
759 careful not to put one of the severity shortcut options immediately after the
760 C<--top> flag or C<perlcritic> will interpret it as the number of violations to
765 Directs C<perlcritic> to ignore the magical C<"## no critic"> pseudo-pragmas
766 in the source code. See L<"BENDING THE RULES"> for more information. You can
767 set the default value for this option in your F<.perlcriticrc> file.
769 =item C<--statistics>
771 Causes several statistics about the code being scanned and the violations
772 found to be reported after any other output.
774 =item C<--statistics-only>
776 Like the C<--statistics> option, but suppresses normal output and only shows
779 =item C<--verbose N | FORMAT>
781 Sets the verbosity level or format for reporting violations. If given a
782 number (C<N>), C<perlcritic> reports violations using one of the predefined
783 formats described below. If given a string (C<FORMAT>), it is interpreted to
784 be an actual format specification. If the C<--verbose> option is not
785 specified, it defaults to either 4 or 5, depending on whether multiple files
786 were given as arguments to C<perlcritic>. You can set the default value for
787 this option in your F<.perlcriticrc> file.
789 Verbosity Format Specification
790 ----------- -------------------------------------------------------------
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"
803 Formats are a combination of literal and escape characters similar to the way
804 C<sprintf> works. See L<String::Format> for a full explanation of the
805 formatting capabilities. Valid escape characters are:
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
821 The purpose of these formats is to provide some compatibility with text
822 editors that have an interface for parsing certain kinds of input. See
823 L<"EDITOR INTEGRATION"> for more information about that.
827 Displays a condensed listing of all the L<Perl::Critic::Policy> modules that
828 are found on this machine. For each Policy, the name, default severity and
829 default themes are shown.
831 =item C<--list-themes>
833 Displays a list of all the themes of the L<Perl::Critic::Policy> modules that
834 are found on this machine.
836 =item C<--profile-proto>
838 Displays an expanded listing of all the L<Perl::Critic::Policy> modules that
839 are found on this machine. For each Policy, the name, default severity and
840 default themes are shown, as well as the name of any additional parameters
841 that the Policy supports. The format is suitable as a prototype for your
842 F<.perlcriticrc> file.
846 Directs perlcritic to apply only Policies that are explicitly mentioned in
847 your F<.perlcriticrc> file. This is useful if you want to use just a small
848 subset of Policies without having to disable all the others. You can set the
849 default value for this option in your F<.perlcriticrc> file.
851 =item C<--profile-strictness {warn|fatal|quiet}>
853 Directs perlcritic how to treat certain recoverable problems found in a
854 F<.perlcriticrc> or file specified via the C<--profile> option. Valid values
855 are C<warn> (the default), C<fatal>, and C<quiet>. For example, perlcritic
856 normally only warns about profiles referring to non-existent Policies, but
857 this option can make this situation fatal. You can set the default value for
858 this option in your F<.perlcriticrc> file.
864 Display only the number of violations for each file. Use this feature to get
865 a quick handle on where a large pile of code might need the most attention.
869 Report "Perl Best Practice" citations as section numbers from
870 L<http://safari.oreilly.com> instead of page numbers from the actual book.
871 NOTE: This feature is not implemented yet.
875 This option is on by default. When set, Severity 5 and 4 are colored red and
876 yellow, respectively. Colorization only happens if STDOUT is a tty and
877 L<Term::ANSIColor> is installed. And it only works on non-Windows
878 environments. Negate this switch to disable color. You can set the default
879 value for this option in your F<.perlcriticrc> file.
881 Can also be specified as C<--colour>.
883 =item C<--doc PATTERN>
885 Displays the perldoc for all L<Perl::Critic::Policy> modules that match
886 C<m/PATTERN/imx>. Since Policy modules tend to have rather long names, this
887 just provides a more convenient way to say something like: C<"perldoc
888 Perl::Critic::Policy::ValuesAndExpressions::RequireUpperCaseHeredocTerminator">
889 at the command prompt.
893 Suppress the "source OK" message when no violations are found.
901 Displays a brief summary of options and exits.
905 Displays the descriptions of the options and exits. While this output is
906 long, it it nowhere near the length of the output of C<--man>.
910 Displays the complete C<perlcritic> manual and exits.
916 Displays the version number of C<perlcritic> and exits.
922 Most of the settings for Perl::Critic and each of the Policy modules can be
923 controlled by a configuration file. The default configuration file is called
924 F<.perlcriticrc>. C<perlcritic> will look for this file in the current
925 directory first, and then in your home directory. Alternatively, you can set
926 the C<PERLCRITIC> environment variable to explicitly point to a different file
927 in another location. If none of these files exist, and the C<--profile> option
928 is not given on the command-line, then all Policies will be loaded with their
929 default configuration.
931 The format of the configuration file is a series of INI-style blocks that
932 contain key-value pairs separated by "=". Comments should start with "#" and
933 can be placed on a separate line or after the name-value pairs if you desire.
935 Default settings for perlcritic itself can be set B<before the first named
936 block.> For example, putting any or all of these at the top of your
937 F<.perlcriticrc> file will set the default value for the corresponding
938 command-line argument.
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
949 The remainder of the configuration file is a series of blocks like this:
951 [Perl::Critic::Policy::Category::PolicyName]
958 C<Perl::Critic::Policy::Category::PolicyName> is the full name of a module
959 that implements the policy. The Policy modules distributed with Perl::Critic
960 have been grouped into categories according to the table of contents in Damian
961 Conway's book B<Perl Best Practices>. For brevity, you can omit the
962 C<'Perl::Critic::Policy'> part of the module name.
964 C<severity> is the level of importance you wish to assign to the Policy. All
965 Policy modules are defined with a default severity value ranging from 1 (least
966 severe) to 5 (most severe). However, you may disagree with the default
967 severity and choose to give it a higher or lower severity, based on your own
968 coding philosophy. You can set the C<severity> to an integer from 1 to 5, or
969 use one of the equivalent names:
971 SEVERITY NAME ...is equivalent to... SEVERITY NUMBER
972 ----------------------------------------------------
979 C<set_themes> sets the theme for the Policy and overrides its default theme.
980 The argument is a string of one or more whitespace-delimited alphanumeric
981 words. Themes are case-insensitive. See L<"POLICY THEMES"> for more
984 C<add_themes> appends to the default themes for this Policy. The argument is
985 a string of one or more whitespace-delimited words. Themes are
986 case-insensitive. See L<"POLICY THEMES"> for more information.
988 The remaining key-value pairs are configuration parameters that will be passed
989 into the constructor of that Policy. The constructors for most Policy modules
990 do not support arguments, and those that do should have reasonable defaults.
991 See the documentation on the appropriate Policy module for more details.
993 Instead of redefining the severity for a given Policy, you can completely
994 disable a Policy by prepending a '-' to the name of the module in your
995 configuration file. In this manner, the Policy will never be loaded,
996 regardless of the C<--severity> given on the command line.
998 A simple configuration might look like this:
1000 #--------------------------------------------------------------
1001 # I think these are really important, so always load them
1003 [TestingAndDebugging::RequireUseStrict]
1006 [TestingAndDebugging::RequireUseWarnings]
1009 #--------------------------------------------------------------
1010 # I think these are less important, so only load when asked
1012 [Variables::ProhibitPackageVars]
1015 [ControlStructures::ProhibitPostfixControls]
1016 allow = if unless # My custom configuration
1017 severity = cruel # Same as "severity = 2"
1019 #--------------------------------------------------------------
1020 # Give these policies a custom theme. I can activate just
1021 # these policies by saying "perlcritic --theme 'larry || curly'"
1023 [Modules::RequireFilenameMatchesPackage]
1026 [TestingAndDebugging::RequireTestLabels]
1027 add_themes = curly moe
1029 #--------------------------------------------------------------
1030 # I do not agree with these at all, so never load them
1032 [-NamingConventions::ProhibitMixedCaseVars]
1033 [-NamingConventions::ProhibitMixedCaseSubs]
1035 #--------------------------------------------------------------
1036 # For all other Policies, I accept the default severity,
1037 # so no additional configuration is required for them.
1039 Note that all policies included with the Perl::Critic distribution that have
1040 integer parameters accept underscores ("_") in their values, as with Perl
1041 numeric literals. For example,
1043 [ValuesAndExpressions::RequireNumberSeparators]
1046 For additional configuration examples, see the F<perlcriticrc> file that is
1047 included in this F<examples> directory of this distribution.
1049 Damian Conway's own Perl::Critic configuration is also included in this
1050 distribution as F<examples/perlcriticrc-conway>.
1054 A large number of Policy modules are distributed with Perl::Critic. They are
1055 described briefly in the companion document L<Perl::Critic::PolicySummary> and
1056 in more detail in the individual modules themselves. Say C<"perlcritic --doc
1057 PATTERN"> to see the perldoc for all Policy modules that match the regex
1060 There are a number of distributions of additional policies on CPAN. If
1061 L<Perl::Critic> doesn't contain a policy that you want, some one may have
1062 already written it. See L<Perl::Critic/"SEE ALSO"> for a list of some of
1063 these distributions.
1065 =head1 POLICY THEMES
1067 Each Policy is defined with one or more "themes". Themes can be used to
1068 create arbitrary groups of Policies. They are intended to provide an
1069 alternative mechanism for selecting your preferred set of Policies. For
1070 example, you may wish disable a certain set of Policies when analyzing test
1071 scripts. Conversely, you may wish to enable only a specific subset of
1072 Policies when analyzing modules.
1074 The Policies that ship with Perl::Critic are have been divided into the
1075 following themes. This is just our attempt to provide some basic logical
1076 groupings. You are free to invent new themes that suit your needs.
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
1089 Say C<"perlcritic --list"> to get a listing of all available policies and the
1090 themes that are associated with each one. You can also change the theme for
1091 any Policy in your F<.perlcriticrc> file. See the L<"CONFIGURATION"> section
1092 for more information about that.
1094 Using the C<--theme> command-line option, you can create an arbitrarily complex
1095 rule that determines which Policies to apply. Precedence is the same as
1096 regular Perl code, and you can use parentheses to enforce precedence as well.
1097 Supported operators are:
1099 Operator Altertative Example
1100 ----------------------------------------------------------------------------
1101 && and 'pbp && core'
1102 || or 'pbp || (bugs && security)'
1103 ! not 'pbp && ! (portability || complexity)'
1105 Theme names are case-insensitive. If the C<--theme> is set to an empty string,
1106 then it evaluates as true all Policies.
1108 =head1 BENDING THE RULES
1110 Perl::Critic takes a hard-line approach to your code: either you
1111 comply 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
1113 cases, it is wise to show that you are knowingly violating the
1114 standards and that you have a Damn Good Reason (DGR) for doing so.
1116 To help with those situations, you can direct Perl::Critic to ignore
1117 certain lines or blocks of code by using pseudo-pragmas:
1119 require 'LegacyLibaray1.pl'; ## no critic
1120 require 'LegacyLibrary2.pl'; ## no critic
1122 for my $element (@list) {
1126 $foo = ""; #Violates 'ProhibitEmptyQuotes'
1127 $barf = bar() if $foo; #Violates 'ProhibitPostfixControls'
1128 #Some more evil code...
1136 The C<"## no critic"> comments direct Perl::Critic to ignore the remaining
1137 lines of code until the end of the current block, or until a C<"## use
1138 critic"> comment is found (whichever comes first). If the C<"## no critic">
1139 comment is on the same line as a code statement, then only that line of code
1140 is overlooked. To direct perlcritic to ignore the C<"## no critic"> comments,
1141 use the C<--force> option.
1143 A bare C<"## no critic"> comment disables all the active Policies. If you
1144 wish to disable only specific Policies, add a list of Policy names as
1145 arguments just as you would for the C<"no strict"> or C<"no warnings"> pragma.
1146 For example, this would disable the C<ProhibitEmptyQuotes> and
1147 C<ProhibitPostfixControls> policies until the end of the block or until the
1148 next C<"## use critic"> comment (whichever comes first):
1150 ## no critic (EmptyQuotes, PostfixControls);
1152 # Now exempt from ValuesAndExpressions::ProhibitEmptyQuotes
1155 # Now exempt ControlStructures::ProhibitPostfixControls
1156 $barf = bar() if $foo;
1158 # Still subject to ValuesAndExpression::RequireNumberSeparators
1159 $long_int = 10000000000;
1161 Since the Policy names are matched against the C<"## no critic"> arguments as
1162 regular expressions, you can abbreviate the Policy names or disable an entire
1163 family of Policies in one shot like this:
1165 ## no critic (NamingConventions)
1167 # Now exempt from NamingConventions::ProhibitMixedCaseVars
1168 my $camelHumpVar = 'foo';
1170 # Now exempt from NamingConventions::ProhibitMixedCaseSubs
1173 The argument list must be enclosed in parentheses and must contain one or more
1174 comma-separated barewords (i.e. don't use quotes). The C<"## no critic">
1175 pragmas can be nested, and Policies named by an inner pragma will be disabled
1176 along with those already disabled an outer pragma.
1178 Some Policies like C<Subroutines::ProhibitExcessComplexity> apply to an entire
1179 block of code. In those cases, C<"## no critic"> must appear on the line
1180 where the violation is reported. For example:
1182 sub complicated_function { ## no critic (ProhibitExcessComplexity)
1186 Some Policies like C<Documentation::RequirePodSections> apply to the entire
1187 document, in which case violations are reported at line 1. But if the file
1188 requires a shebang line, it is impossible to put C<"## no critic"> on the
1189 first line of the file. This is a known limitation and it will be addressed
1190 in a future release. As a workaround, you can disable the affected policies
1191 at the command-line or in your F<.perlcriticrc> file. But beware that this
1192 will affect the analysis of B<all> files.
1194 Use this feature wisely. C<"## no critic"> should be used in the smallest
1195 possible scope, or only on individual lines of code. And you should always be
1196 as specific as possible about which policies you want to disable (i.e. never
1197 use a bare C<"## no critic">). If Perl::Critic complains about your code, try
1198 and find a compliant solution before resorting to this feature.
1200 =head1 EDITOR INTEGRATION
1202 For ease-of-use, C<perlcritic> can be integrated with your favorite text
1203 editor. The output-formatting capabilities of C<perlcritic> are specifically
1204 intended for use with the "grep" or "compile" modes available in editors like
1205 C<emacs> and C<vim>. In these modes, you can run an arbitrary command and the
1206 editor will parse the output into an interactive buffer that you can click on
1207 and jump to the relevant line of code.
1209 The Perl::Critic team thanks everyone who has helped integrate Perl-Critic
1210 with their favorite editor. Your contributions in particular have made
1211 Perl-Critic a convenient and user-friendly tool for Perl developers of all
1212 stripes. We sincerely appreciate your hard work.
1216 Joshua ben Jore has authored a minor-mode for emacs that allows you to run
1217 perlcritic on the current region or buffer. You can run it on demand, or
1218 configure it to run automatically when you save the buffer. The output
1219 appears in a hot-linked compiler buffer. The code and installation
1220 instructions can be found in the F<extras> directory inside this distribution.
1224 Scott Peshak has published F<perlchecker.vim>, which is available at
1225 L<http://www.vim.org/scripts/script.php?script_id=1731>.
1229 Fritz Mehner recently added support for C<perlcritic> to his fantastic gVIM
1230 plugin. In addition to providing a very Perlish IDE, Fritz's plugin enables
1231 one-click access to C<perlcritic> and many other very useful utilities. And
1232 all is seamlessly integrated into the editor. See
1233 L<http://lug.fh-swf.de/vim/vim-perl/screenshots-en.html> for complete details.
1237 EPIC is an open source Perl IDE based on the Eclipse platform. Features
1238 supported are syntax highlighting, on-the-fly syntax check, content assist,
1239 perldoc support, source formatter, templating support and a Perl debugger. Go
1240 to L<http://e-p-i-c.sourceforge.net> for more information about EPIC.
1242 The EPIC team is currently working on integration with Perl::Critic. In the
1243 meantime, you can use the L<criticism> pragma and EPIC will highlight
1244 violations whenever it does a syntax check on your code. I haven't tried this
1245 myself, but other folks say it works.
1249 Josh Clark has produced an excellent Perl-Critic plugin for BBEdit. A copy is
1250 included in this distribution at F<extras/perl_critic_for_bbedit-1_0.zip>. See
1251 L<http://beta.bigmedium.com/projects/bbedit-perl-critic/index.shtml> for
1252 screenshots and additional installation info. Apple users rejoice!
1256 Komodo is a proprietary IDE for Perl and several other dynamic languages.
1257 Free trial copies of Komodo can be obtained from the ActiveState website at
1258 L<http://www.activestate.com>. For instructions on integrating F<perlcritic>
1259 with Komodo, see F<extras/KomodoIntegration.pod> in this distribution.
1263 If C<perlcritic> has any errors itself, exits with status == 1. If there are
1264 no errors, but C<perlcritic> finds Policy violations in your source code,
1265 exits with status == 2. If there were no errors and no violations were found,
1266 exits with status == 0.
1268 =head1 THE L<Perl::Critic> PHILOSOPHY
1272 Coding standards are deeply personal and highly subjective. The goal of
1273 Perl::Critic is to help you write code that conforms with a set of best
1274 practices. Our primary goal is not to dictate what those practices are, but
1275 rather, to implement the practices discovered by others. Ultimately, you make
1276 the rules -- Perl::Critic is merely a tool for encouraging consistency. If
1277 there is a policy that you think is important or that we have overlooked, we
1278 would be very grateful for contributions, or you can simply load your own
1279 private set of policies into Perl::Critic.
1283 =head1 EXTENDING THE CRITIC
1285 The modular design of Perl::Critic is intended to facilitate the addition of
1286 new Policies. You'll need to have some understanding of L<PPI>, but most
1287 Policy modules are pretty straightforward and only require about 20 lines of
1288 code, and half of those lines are simple use statements and simple
1289 declarations.. Please see the L<Perl::Critic::DEVELOPER> file included in
1290 this distribution for a step-by-step demonstration of how to create new Policy
1293 If you develop any new Policy modules, feel free to send them to
1294 C<< <thaljef@cpan.org> >> and I'll be happy to put them into the Perl::Critic
1295 distribution. Or if you would like to work on the Perl::Critic project
1296 directly, check out our repository at L<http://perlcritic.tigris.org>. To
1297 subscribe to our mailing list, send a message to
1298 C<< <dev-subscribe@perlcritic.tigris.org> >>.
1300 The Perl::Critic team is also available for hire. If your organization has
1301 its own coding standards, we can create custom Policies to enforce your local
1302 guidelines. Or if your code base is prone to a particular defect pattern, we
1303 can design Policies that will help you catch those costly defects B<before>
1304 they go into production. To discuss your needs with the Perl::Critic team,
1305 just contact C<< <thaljef@cpan.org> >>.
1307 =head1 CONTACTING THE DEVELOPMENT TEAM
1309 You are encouraged to subscribe to the mailing list; send a message to
1310 C<< <users-subscribe@perlcritic.tigris.org> >>. See also
1311 L<the archives|http://perlcritic.tigris.org/servlets/SummarizeList?listName=users>.
1312 You can also contact the author at C<< <thaljef@cpan.org> >>.
1314 At least one member of the development team has started hanging around in
1315 L<irc://irc.perl.org/#perlcritic>.
1319 There are a number of distributions of additional Policies available. A few
1322 L<Perl::Critic::More>
1323 L<Perl::Critic::Bangs>
1324 L<Perl::Critic::Lax>
1325 L<Perl::Critic::StricterSubs>
1326 L<Perl::Critic::Swift>
1328 These distributions enable you to use Perl::Critic in your unit tests:
1330 L<Test::Perl::Critic>
1331 L<Test::Perl::Critic::Progressive>
1333 There are also a couple of distributions that will install all the
1334 Perl::Critic related modules known to the development team:
1336 L<Bundle::Perl::Critic>
1337 L<Task::Perl::Critic>
1341 Scrutinizing Perl code is hard for humans, let alone machines. If you find
1342 any bugs, particularly false-positives or false-negatives from a
1343 Perl::Critic::Policy, please submit them to
1344 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Perl-Critic>. Thanks.
1346 Most policies will produce false-negatives if they cannot understand a
1347 particular block of code.
1351 Adam Kennedy - For creating L<PPI>, the heart and soul of L<Perl::Critic>.
1353 Damian Conway - For writing B<Perl Best Practices>, finally :)
1355 Chris Dolan - For contributing the best features and Policy modules.
1357 Andy Lester - Wise sage and master of all-things-testing.
1359 Elliot Shank - The self-proclaimed quality freak.
1361 Giuseppe Maxia - For all the great ideas and positive encouragement.
1363 and Sharon, my wife - For putting up with my all-night code sessions.
1367 Jeffrey Ryan Thalhammer <thaljef@cpan.org>
1371 Copyright (c) 2005-2008 Jeffrey Ryan Thalhammer. All rights reserved.
1373 This program is free software; you can redistribute it and/or modify it under
1374 the same terms as Perl itself. The full text of this license can be found in
1375 the LICENSE file included with this module.
1379 ##############################################################################
1382 # cperl-indent-level: 4
1384 # indent-tabs-mode: nil
1385 # c-indentation-style: bsd
1387 # ex: set ts=8 sts=4 sw=4 tw=78 ft=perl expandtab shiftround :