PERLCRITIC(1p)

๐Ÿ“ฆ
version 1.156 ยท 5 versions
, in debian trixie, ubuntu resolute, ubuntu stonking

๐Ÿ’– PERLCRITIC ๐Ÿ’–

ok so you're looking at perlcritic from the User Contributed Perl Documentation section โ€” that's the perlcritic(1p) manual page, bestie. sit down, get comfy, we're gonna read it together ๐Ÿซถ


โœจ NAME โœจ

perlcritic โ€” the command-line interface to critique Perl source. yes, it's literally a vibe check for your code ๐Ÿ’…


โœจ SYNOPSIS โœจ

perlcritic [-12345 | --brutal | --cruel | --harsh | --stern | --gentle]
           [--severity number | name] [{-p | --profile} file | --noprofile]
           [--top [ number ]] [--theme expression] [--include pattern]
           [--exclude pattern] [{-s | --single-policy} pattern]
           [--only | --noonly] [--profile-strictness {warn|fatal|quiet}]
           [--force | --noforce] [--statistics] [--statistics-only]
           [--count | -C] [--verbose {number | format}] [--allow-unsafe]
           [--color | --nocolor] [--pager pager] [--quiet]
           [--color-severity-highest color_specification]
           [--color-severity-high color_specification]
           [--color-severity-medium color_specification]
           [--color-severity-low color_specification]
           [--color-severity-lowest color_specification]
           [--files-with-violations | -l]
           [--files-without-violations | -L]
           [--program-extensions file_name_extension]
           {FILE | DIRECTORY | STDIN}

perlcritic --profile-proto

perlcritic { --list | --list-enabled | --list-themes | --doc pattern [...] }

perlcritic { --help | --options | --man | --version }

โœจ DESCRIPTION โœจ

so perlcritic is a Perl source code analyzer โœจ it's the executable front-end to the Perl::Critic engine, and what it does is go looking through your code for constructs that are awkward, hard to read, error-prone, or just plain unconventional. it's giving "your code, but make it a group project and everyone's judging" ๐Ÿ˜ญ

most of the rules come straight from Damian Conway's book Perl Best Practices. but โ€” and this is important โ€” perlcritic is not limited to enforcing PBP. it will literally support rules that contradict Conway. icon behaviour honestly ๐Ÿ‘‘ and every single rule can be configured or disabled to your liking, so you're never stuck with a rule you hate.

this doc only covers how to drive this command. for everything else โ€” API reference, alternative interfaces, all of it โ€” go look at the documentation for Perl::Critic itself ๐Ÿ’œ

โœจ USAGE EXAMPLES โœจ

before we get into all the gory details (and bestie, there are so many gory details), here's some basic stuff to get you started ๐ŸŽ€

# Report only most severe violations (severity = 5)
perlcritic YourModule.pm

# Same as above, but read input from STDIN
perlcritic

# Recursively process all Perl files beneath directory
perlcritic /some/directory

# Report slightly less severe violations too (severity >= 4)
perlcritic -4 YourModule.pm

# Same as above, but using named severity level
perlcritic --stern YourModule.pm

# Report all violations, regardless of severity (severity >= 1)
perlcritic -1 YourModule.pm

# Same as above, but using named severity level
perlcritic --brutal YourModule.pm

# Report only violations of things from "Perl Best Practices"
perlcritic --theme pbp YourModule.pm

# Report top 20 most severe violations (severity >= 1)
perlcritic --top YourModule.pm

# Report additional violations of Policies that match m/variables/xms
perlcritic --include variables YourModule.pm

# Use defaults from somewhere other than ~/.perlcriticrc
perlcritic --profile project/specific/perlcriticrc YourModule.pm

โœจ ARGUMENTS โœจ

the arguments are paths to the files you wish to analyze. you can hand it multiple files, no problem. if an argument is a directory, perlcritic will analyze all the Perl files below that directory ๐ŸŒธ

and if you give it no arguments at all? then input gets read from STDIN. yes, you can just pipe stuff in. main character energy honestly ๐Ÿ’…


โœจ OPTIONS โœจ

okay real talk before the list: option names can be abbreviated to uniqueness, and you can write them with single or double dashes. option values can be separated from the option name by a space or an = โ€” just like with Getopt::Long. and heads up: option names are case-sensitive. ๐Ÿ™ˆ

  • --profile FILE or -p FILE โ€” tells perlcritic to use a profile named by FILE instead of going hunting for the default .perlcriticrc file in the current directory or your home directory. want more deets? see "CONFIGURATION" in Perl::Critic. ๐ŸŽ€
  • --noprofile โ€” tells perlcritic to load no configuration file at all, which means everything reverts to the default configuration for all Policies. factory settings, periodt โœจ
  • --severity N โ€” tells perlcritic to only apply Policies with a severity greater than N. severity values are integers ranging from 1 (least severe) to 5 (most severe). the default is 5. for a given --profile, decreasing the --severity will usually produce more violations. you can set the default value for this option in your .perlcriticrc file. you can also redefine the severity for any Policy in your .perlcriticrc file. see "CONFIGURATION" for more info. ๐Ÿ’–
  • -5 | -4 | -3 | -2 | -1 โ€” these are numeric shortcuts for setting the --severity option. for example, -4 is equivalent to --severity 4. if multiple shortcuts are specified, then the most restrictive one wins. if an explicit --severity option is also given, then all shortcut options are silently ignored.
โš ๏ธ NOTE: be careful not to put one of the number severity shortcut options immediately after the --top flag, or perlcritic will interpret it as the number of violations to report. ๐Ÿ’€
  • --severity NAME โ€” if you can never remember whether severity 5 is the most or the least restrictive level (no judgement, same), then you can use one of these named values:
SEVERITY NAME   ...is equivalent to...   SEVERITY NUMBER
--------------------------------------------------------
--severity gentle                           --severity 5
--severity stern                            --severity 4
--severity harsh                            --severity 3
--severity cruel                            --severity 2
--severity brutal                           --severity 1
  • --gentle | --stern | --harsh | --cruel | --brutal โ€” these are named shortcuts for setting the --severity option. for example, --cruel is equivalent to --severity 2. if multiple shortcuts are specified, then the most restrictive one wins. if an explicit --severity option is also given, then all shortcut options are silently ignored. ๐Ÿฆ‹
  • --theme RULE โ€” tells perlcritic to apply only Policies with themes that satisfy the RULE. themes are arbitrary names for groups of related policies. you can combine theme names with boolean operators to create an arbitrarily complex RULE. for example, the following would apply only Policies that have a 'bugs' AND 'pbp' theme:
$> perlcritic --theme='bugs && pbp' MyModule.pm

unless the --severity option is explicitly given, setting --theme silently causes the --severity to be set to 1. you can set the default value for this option in your .perlcriticrc file. see "POLICY THEMES" in Perl::Critic for more info about themes. ๐ŸŒˆ

  • --include PATTERN โ€” tells perlcritic to apply additional Policies that match the regex /PATTERN/imx. use this option to temporarily override your profile and/or the severity settings at the command-line. for example:
perlcritic --include=layout my_file.pl

this would cause perlcritic to apply all the CodeLayout::* policies even if they have a severity level that is less than the default level of 5, or have been disabled in your .perlcriticrc file. you can specify multiple --include options and you can use it in conjunction with the --exclude option. note that --exclude takes precedence over --include when a Policy matches both patterns. you can set the default value for this option in your .perlcriticrc file. ๐Ÿ’œ

  • --exclude PATTERN โ€” tells perlcritic to not apply any Policy that matches the regex /PATTERN/imx. use this option to temporarily override your profile and/or the severity settings at the command-line. for example:
perlcritic --exclude=strict my_file.pl

this would cause perlcritic to not apply the RequireUseStrict and ProhibitNoStrict Policies even though they have the highest severity level. you can specify multiple --exclude options and you can use it in conjunction with the --include option. note that --exclude takes precedence over --include when a Policy matches both patterns. you can set the default value for this option in your .perlcriticrc file. ๐Ÿ˜ค

  • --single-policy PATTERN or -s PATTERN โ€” tells perlcritic to apply just one Policy module matching the regex /PATTERN/ixms, and exclude all other Policies. this option has precedence over the --severity, --theme, --include, --exclude, and --only options. for example:
perlcritic --single-policy=nowarnings my_file.pl

this would cause perlcritic to apply just the ProhibitNoWarnings Policy, regardless of the severity level setting. no other Policies would be applied. ๐Ÿ‘‘

this is equivalent to what one might intend by...

perlcritic --exclude=. --include=nowarnings my_file.pl

...but this won't work because the --exclude option overrides the --include option. ๐Ÿ’€

the equivalent of this option can be accomplished by creating a custom profile containing only the desired policy and then running...

perlcritic --profile=customprofile --only my_file.pl
  • --top [ N ] โ€” tells perlcritic to report only the top N Policy violations in each file, ranked by their severity. if N is not specified, it defaults to 20. if the --severity option (or one of the shortcuts) is not explicitly given, the --top option implies that the minimum severity level is 1 (i.e. brutal). users can redefine the severity for any Policy in their .perlcriticrc file. see "CONFIGURATION" for more info. you can set the default value for this option in your .perlcriticrc file.
โš ๏ธ NOTE: be careful not to put one of the severity shortcut options immediately after the --top flag, or perlcritic will interpret it as the number of violations to report. ๐Ÿ˜ญ
  • --force โ€” tells perlcritic to ignore the magical ## no critic annotations in the source code. see "BENDING THE RULES" for more info. you can set the default value for this option in your .perlcriticrc file. ๐Ÿ”ฅ
  • --statistics โ€” causes several statistics about the code being scanned and the violations found to be reported after any other output. numbers girlies rise ๐Ÿ“
  • --statistics-only โ€” like the --statistics option, but it suppresses normal output and only shows the statistics. just the receipts, nothing else ๐Ÿ’…
  • --verbose N | FORMAT โ€” this is the how much tea are we spilling dial ๐Ÿซ–. Hand it a number (N) and perlcritic reports violations using one of the preset formats listed below. Hand it a string (FORMAT) and it treats that string as an actual format specification. Don't pass --verbose at all? It defaults to either 4 or 5, depending on whether multiple files were given as arguments to perlcritic. And yeah bestie, you can set the default value for this one in your .perlcriticrc file. ๐Ÿ’…
Verbosity     Format Specification
-----------   -------------------------------------------------------
 1            "%f:%l:%c:%m\n",
 2            "%f: (%l:%c) %m\n",
 3            "%m at %f line %l\n",
 4            "%m at line %l, column %c.  %e.  (Severity: %s)\n",
 5            "%f: %m at line %l, column %c.  %e.  (Severity: %s)\n",
 6            "%m at line %l, near '%r'.  (Severity: %s)\n",
 7            "%f: %m at line %l near '%r'.  (Severity: %s)\n",
 8            "[%p] %m at line %l, column %c.  (Severity: %s)\n",
 9            "[%p] %m at line %l, near '%r'.  (Severity: %s)\n",
10            "%m at line %l, column %c.\n  %p (Severity: %s)\n%d\n",
11            "%m at line %l, near '%r'.\n  %p (Severity: %s)\n%d\n"

Formats are a lil combo of literal characters and escape characters, kinda like how sprintf does its thing. Go read String::Format for the full rundown of the formatting capabilities. The valid escape characters are:

Escape    Meaning
-------   ------------------------------------------------------------
%c        Column number where the violation occurred
%d        Full diagnostic discussion of the violation
%e        Explanation of violation or page numbers in PBP
%F        Just the name of the file where the violation occurred.
%f        Path to the file where the violation occurred.
%l        Line number where the violation occurred
%m        Brief description of the violation
%P        Full name of the Policy module that created the violation
%p        Name of the Policy without the Perl::Critic::Policy:: prefix
%r        The string of source code that caused the violation
%C        The class of the PPI::Element that caused the violation
%s        The severity level of the violation

The whole reason these formats exist is to give you some compatibility with text editors that have an interface for parsing certain kinds of input. See "EDITOR INTEGRATION" for more on that. ๐Ÿ‘€

  • --list โ€” shows a condensed listing of every Perl::Critic::Policy module found on this machine. And when we say every, we mean every โ€” this lists all Policies regardless of your .perlcriticrc or command line options. For each Policy you get the name, default severity and default themes. โœจ
  • --list-enabled โ€” same condensed listing energy, but only for the Perl::Critic::Policy modules that would actually be enforced if you were really about to critique a file with this command. So useful when you've built some complicated command or edited your .perlcriticrc file and you wanna see exactly which Policies are going to be enforced (or not enforced, as the case may be). For each Policy: name, default severity and default themes. ๐ŸŽ€
  • --list-themes โ€” drops a list of all the themes of the Perl::Critic::Policy modules found on this machine. Themes, bestie. All of them. ๐ŸŒˆ
  • --profile-proto โ€” an expanded listing of all the Perl::Critic::Policy modules found on this machine. For each Policy you get the name, default severity and default themes, plus the name of any additional parameters that Policy supports. The format is suitable as a prototype for your .perlcriticrc file. Chef's kiss for bootstrapping. ๐Ÿ‘‘
  • --only โ€” tells perlcritic to apply only the Policies that are explicitly mentioned in your .perlcriticrc file. Perfect if you want just a tiny subset of Policies without the whole song and dance of disabling all the others. You can set the default value for this option in your .perlcriticrc file. ๐Ÿ’–
  • --profile-strictness {warn|fatal|quiet} โ€” tells perlcritic how to treat certain recoverable problems found in a .perlcriticrc or in a file specified via the --profile option. Valid values are "warn" (the default), "fatal", and "quiet". For example, perlcritic normally only warns about profiles referring to non-existent Policies, but this option can make that situation fatal. You can set the default value for this option in your .perlcriticrc file. ๐Ÿ˜ค
  • --count, -C โ€” display only the number of violations for each file. Use this feature to get a quick handle on where a large pile of code might need the most attention. Number-crunching main character energy. ๐Ÿ”ข
  • --color, --colour โ€” this option is on when outputting to a tty. When it's set, Severity 5 and 4 are colored red and yellow, respectively. Colorization only happens if Term::ANSIColor is installed. And for Windows environments, Win32::Console::ANSI must also be installed. Negate this switch to disable color. You can set the default value for this option in your .perlcriticrc file. ๐ŸŒˆ๐Ÿ’…
  • --pager PAGER_COMMAND_STRING โ€” if set, perlcritic will pipe its output to the given PAGER_COMMAND_STRING. You can set the default value for this option in your .perlcriticrc file.

Setting a pager turns off color by default. You will have to turn color on explicitly. If you want color, you'll probably also want to tell your pager to display raw characters. For less and more, use the -R switch. ๐Ÿ“–

  • --color-severity-highest COLOR_SPECIFICATION โ€” specifies the color to be used for highest severity violations, as a Term::ANSIColor color specification. Can also be specified as --colour-severity-highest, --color-severity-5, or --colour-severity-5.
  • --color-severity-high COLOR_SPECIFICATION โ€” specifies the color to be used for high severity violations, as a Term::ANSIColor color specification. Can also be specified as --colour-severity-high, --color-severity-4, or --colour-severity-4.
  • --color-severity-medium COLOR_SPECIFICATION โ€” specifies the color to be used for medium severity violations, as a Term::ANSIColor color specification. Can also be specified as --colour-severity-medium, --color-severity-3, or --colour-severity-3.
  • --color-severity-low COLOR_SPECIFICATION โ€” specifies the color to be used for low severity violations, as a Term::ANSIColor color specification. Can also be specified as --colour-severity-low, --color-severity-2, or --colour-severity-2.
  • --color-severity-lowest COLOR_SPECIFICATION โ€” specifies the color to be used for lowest severity violations, as a Term::ANSIColor color specification. Can also be specified as --colour-severity-lowest, --color-severity-1, or --colour-severity-1.
  • --files-with-violations โ€” display only the names of files with violations. Use this feature with --single-policy to find files that contain violations of a given policy. Can also be specified as --l.
  • --files-without-violations โ€” display only the names of files without violations. Use this feature with --single-policy to find files that do not contain violations of a given policy. Can also be specified as --L.
  • --program-extensions file_name_extension โ€” tell perlcritic to treat files whose names end in the given file name extension as programs, not as modules. If a leading . is desired it must be explicitly specified, e.g.
--program-extensions .pl

The matching is case-sensitive, and the option may be specified as many times as desired, e.g.

--program-extensions .pl --program-extensions .cgi

The above can also be done by quoting the file name extensions:

--program-extensions '.pl .cgi'

Files whose name ends in .PL will always be considered programs. ๐Ÿ“Ž

  • --doc PATTERN โ€” displays the perldoc for all Perl::Critic::Policy modules that match m/PATTERN/ixms. Since Policy modules tend to have rather long names, this just provides a more convenient way to say something like: perldoc Perl::Critic::Policy::ValuesAndExpressions::RequireUpperCaseHeredocTerminator at the command prompt. Life-saver, fr. ๐Ÿ“š
  • --allow-unsafe โ€” this option directs perlcritic to allow the use of Policies that have been marked as "unsafe". Unsafe Policies may result in risky operations by compiling and executing the code they analyze. All the Policies that ship in the core Perl::Critic distribution are safe. However, third party Policies, such as those in the Perl::Critic::Dynamic distribution, may not be. Note that "safety" is honorary โ€” if a Policy author marks a Policy as safe, it is not a guarantee that it won't do nasty things. If you don't trust your Policies and the code you are analyzing, then do not use this switch. ๐Ÿšจ
Okay so seriously, bestie: --allow-unsafe is not a vibe, it's a risk. Unsafe Policies can literally compile and execute the code they analyze. Read the warning again before you type it. ๐Ÿ’€
  • --quiet โ€” suppress the "source OK" message when no violations are found. ๐Ÿคซ
  • --help, -?, -H โ€” displays a brief summary of options and exits. ๐Ÿ™‹
  • --options โ€” displays the descriptions of the options and exits. While this output is long, it is nowhere near the length of the output of --man. ๐Ÿ˜ฎโ€๐Ÿ’จ
  • --man โ€” displays the complete perlcritic manual and exits. The whole thing. Every last word. Grab a snack. ๐Ÿ“
  • --version โ€” displays the version number of perlcritic and exits. ๐Ÿท๏ธ

๐Ÿ’– CONFIGURATION ๐Ÿ’–

okay so this is the part where you get to make perlcritic yours. Most of the settings for Perl::Critic and for every single one of the Policy modules can be controlled by a configuration file. The default one is called .perlcriticrc โ€” cute name, right? perlcritic will go looking for it in the current directory first, and then in your home directory. Or, if you're feeling extra, you can set the PERLCRITIC environment variable to explicitly point at a completely different file somewhere else on your system. And if literally none of those files exist, and you didn't pass --profile on the command line, then every Policy just loads up with its default configuration. no config, no drama. ๐Ÿ’…

The format is a series of INI-style blocks holding key-value pairs separated by =. Comments start with # and can chill on their own line, or sit right after a name-value pair if that's the vibe you want.

Default settings for perlcritic itself go before the first named block. So like, dropping any or all of these at the top of your .perlcriticrc sets the default value for the matching command-line argument:

severity  = 3                                     #Integer or named level
only      = 1                                     #Zero or One
force     = 0                                     #Zero or One
verbose   = 4                                     #Integer or format spec
top       = 50                                    #A positive integer
theme     = (pbp + security) * bugs               #A theme expression
include   = NamingConventions ClassHierarchies    #Space-delimited list
exclude   = Variables  Modules::RequirePackage    #Space-delimited list

And the rest of the file is just a series of blocks shaped like this:

[Perl::Critic::Policy::Category::PolicyName]
severity = 1
set_themes = foo bar
add_themes = baz
arg1 = value1
arg2 = value2

Perl::Critic::Policy::Category::PolicyName is the full name of the module that implements the policy. The Policy modules that ship with Perl::Critic are grouped into categories based on the table of contents in Damian Conway's book Perl Best Practices. And for brevity โ€” because typing that whole thing out is a lot โ€” you can just omit the Perl::Critic::Policy part of the module name. ๐Ÿซถ

severity is the level of importance you want to assign to the Policy. Every Policy module comes with a default severity value from 1 (least severe) to 5 (most severe). But bestie, you're allowed to disagree with the default and give it a higher or lower severity based on your own coding philosophy. You can set severity to an integer from 1 to 5, or use one of the equivalent names:

  • gentle โ†’ 5
  • stern โ†’ 4
  • harsh โ†’ 3
  • cruel โ†’ 2
  • brutal โ†’ 1

(so like, SEVERITY NAME ...is equivalent to... SEVERITY NUMBER, if you want the original framing โœจ)

set_themes sets the theme for the Policy and overrides its default theme. The argument is a string of one or more whitespace-delimited alphanumeric words. Themes are case-insensitive. See "POLICY THEMES" for more.

add_themes appends to the default themes for this Policy. The argument is a string of one or more whitespace-delimited words. Themes are case-insensitive. Again, see "POLICY THEMES". ๐ŸŒธ

The remaining key-value pairs are configuration parameters that get passed into the constructor of that Policy. The constructors for most Policy modules don't support arguments at all, and the ones that do should have reasonable defaults. Peep the documentation on the appropriate Policy module for the details.

Instead of redefining the severity for a given Policy, you can completely disable a Policy by prepending a - to the name of the module in your configuration file. Do it that way and the Policy will never be loaded, no matter what --severity you gave on the command line. gone. not invited. ๐Ÿ™ˆ

A simple configuration might look like this:

#--------------------------------------------------------------
# I think these are really important, so always load them

[TestingAndDebugging::RequireUseStrict]
severity = 5

[TestingAndDebugging::RequireUseWarnings]
severity = 5

#--------------------------------------------------------------
# I think these are less important, so only load when asked

[Variables::ProhibitPackageVars]
severity = 2

[ControlStructures::ProhibitPostfixControls]
allow = if unless  # My custom configuration
severity = cruel   # Same as "severity = 2"

#--------------------------------------------------------------
# Give these policies a custom theme.  I can activate just
# these policies by saying "perlcritic --theme 'larry || curly'"

[Modules::RequireFilenameMatchesPackage]
add_themes = larry

[TestingAndDebugging::RequireTestLabels]
add_themes = curly moe

#--------------------------------------------------------------
# I do not agree with these at all, so never load them

[-NamingConventions::Capitalization]
[-ValuesAndExpressions::ProhibitMagicNumbers]

#--------------------------------------------------------------
# For all other Policies, I accept the default severity,
# so no additional configuration is required for them.

Note that all policies included with the Perl::Critic distribution that have integer parameters accept underscores (_) in their values, same as Perl numeric literals. So like:

[ValuesAndExpressions::RequireNumberSeparators]
min_value = 1_000

For additional configuration examples, see the perlcriticrc file that's included in this examples directory of this distribution.

Damian Conway's own Perl::Critic configuration is also included in this distribution as examples/perlcriticrc-conway. yes, the actual icon himself. ๐Ÿ‘‘


โœจ THE POLICIES โœจ

A large number of Policy modules are distributed with Perl::Critic. They're described briefly in the companion document Perl::Critic::PolicySummary and in way more detail in the individual modules themselves. Say perlcritic --doc PATTERN to see the perldoc for all Policy modules that match the regex m/PATTERN/ixms. ๐Ÿ”ฅ

There are a bunch of distributions of additional policies on CPAN. If Perl::Critic doesn't contain a policy you want, someone may have already written it. See "SEE ALSO" in Perl::Critic for a list of some of these distributions.


๐ŸŒˆ POLICY THEMES ๐ŸŒˆ

Every Policy is defined with one or more "themes". Themes let you create arbitrary groups of Policies, and they're meant to give you an alternative mechanism for selecting your preferred set. For example, you might want to disable a certain set of Policies when analyzing test programs. Conversely, you might want to enable only a specific subset of Policies when analyzing modules. your call, bestie. ๐Ÿ’…

The Policies that ship with Perl::Critic have been divided into the following themes. This is just our attempt at some basic logical groupings โ€” you're free to invent new themes that suit your needs.

  • core โ€” All policies that ship with Perl::Critic
  • pbp โ€” Policies that come directly from "Perl Best Practices"
  • bugs โ€” Policies that that prevent or reveal bugs
  • certrec โ€” Policies that CERT recommends
  • certrule โ€” Policies that CERT considers rules
  • maintenance โ€” Policies that affect the long-term health of the code
  • cosmetic โ€” Policies that only have a superficial effect
  • complexity โ€” Policies that specifically relate to code complexity
  • security โ€” Policies that relate to security issues
  • tests โ€” Policies that are specific to test programs

Say perlcritic --list to get a listing of all available policies and the themes associated with each one. You can also change the theme for any Policy in your .perlcriticrc file โ€” see the "CONFIGURATION" section for more about that. ๐ŸŽ€

Using the --theme command-line option, you can create an arbitrarily complex rule that determines which Policies to apply. Precedence works the same as regular Perl code, and you can use parentheses to enforce precedence too. The supported operators are:

  • && โ€” alternative: and โ€” example: 'pbp && core'
  • || โ€” alternative: or โ€” example: 'pbp || (bugs && security)'
  • ! โ€” alternative: not โ€” example: 'pbp && ! (portability || complexity)'

Theme names are case-insensitive. And if --theme is set to an empty string, then it evaluates as true for all Policies. yeah. everything. all of them. ๐Ÿ’€

๐Ÿ’… BENDING THE RULES ๐Ÿ’…

Okay bestie, real talk. Perl::Critic is a hard-line girlie at heart: either you comply or you don't. No in-between, no vibes-based exceptions. But in the actual real world? Fully complying with coding standards is not always practical โ€” or honestly even possible. ๐Ÿ˜ญ And when that happens, the move is to be loud about it: show that you're knowingly breaking the standards and that you have a Damn Good Reason (DGR) for doing so. Own it.

To help you out in those moments, you can direct Perl::Critic to ignore certain lines or blocks of code using annotations:

require 'LegacyLibaray1.pl';  ## no critic
require 'LegacyLibrary2.pl';  ## no critic

for my $element (@list) {

    ## no critic

    $foo = "";               #Violates 'ProhibitEmptyQuotes'
    $barf = bar() if $foo;   #Violates 'ProhibitPostfixControls'
    #Some more evil code...

    ## use critic

    #Some good code...
    do_something($_);
}

So the ## no critic annotations tell Perl::Critic to ignore the remaining lines of code until it finds a ## use critic annotation. But โœจimportantโœจ โ€” if the ## no critic annotation sits on the same line as a code statement, then only that one line gets overlooked. And if you want to make perlcritic straight-up ignore the ## no critic annotations themselves? Use the --force option. ๐Ÿซถ

A bare ## no critic annotation disables all the active Policies. That's the nuclear option, and honestly? Slightly dramatic. If you only wanna disable specific Policies, just add a list of Policy names as arguments, exactly like you would for the no strict or no warnings pragma. For example, this would disable the ProhibitEmptyQuotes and ProhibitPostfixControls policies until the end of the block, or until the next ## use critic annotation โ€” whichever comes first:

    ## no critic (EmptyQuotes, PostfixControls);

    # Now exempt from ValuesAndExpressions::ProhibitEmptyQuotes
    $foo = "";

    # Now exempt ControlStructures::ProhibitPostfixControls
    $barf = bar() if $foo;

    # Still subject to ValuesAndExpression::RequireNumberSeparators
    $long_int = 10000000000;

Now here's the fun part ๐ŸŽ€ โ€” since the Policy names get matched against the ## no critic arguments as regular expressions, you can abbreviate Policy names or disable an entire family of Policies in one shot. It's giving efficiency:

    ## no critic (NamingConventions)

    # Now exempt from NamingConventions::Capitalization
    my $camelHumpVar = 'foo';

    # Now exempt from NamingConventions::Capitalization
    sub camelHumpSub {}

The argument list must be enclosed in parentheses and must contain one or more comma-separated barewords (i.e. no quotes, bestie, don't do it). And yes, the ## no critic annotations can be nested โ€” Policies named by an inner annotation get disabled along with those already disabled by an outer annotation. Layers on layers. ๐Ÿงš

Some Policies, like Subroutines::ProhibitExcessComplexity, apply to an entire block of code. In those cases, ## no critic has to appear on the line where the violation is reported. Like so:

    sub complicated_function {  ## no critic (ProhibitExcessComplexity)
        # Your code here...
    }

And then there are Policies like Documentation::RequirePodSections that apply to the entire document โ€” in which case violations get reported at line 1. But if the file needs a shebang line, it is literally impossible to put ## no critic on the first line of the file. ๐Ÿ™ˆ This is a known limitation and it will be addressed in a future release. As a workaround, you can disable the affected policies at the command-line or in your .perlcriticrc file. But beware โ€” that will affect the analysis of all files.

Use this feature wisely, bestie. ## no critic should be used in the smallest possible scope, or only on individual lines of code. And you should always be as specific as possible about which policies you want to disable โ€” i.e. never use a bare ## no critic. If Perl::Critic complains about your code, try and find a compliant solution before resorting to this feature. No cap. ๐Ÿ’€

๐Ÿ–ฅ๏ธ EDITOR INTEGRATION ๐Ÿ–ฅ๏ธ

For ease-of-use, perlcritic can be integrated with your favorite text editor. The output-formatting capabilities of perlcritic are specifically intended for use with the grep or compile modes available in editors like emacs and vim. In these modes, you can run an arbitrary command and the editor will parse the output into an interactive buffer that you can click on and jump straight to the relevant line of code. Chef's kiss. ๐Ÿ‘‘

The Perl::Critic team thanks everyone who has helped integrate Perl::Critic with their favorite editor. Your contributions in particular have made Perl::Critic a convenient and user-friendly tool for Perl developers of all stripes. We sincerely appreciate your hard work. ๐Ÿ’–

๐ŸŒธ EMACS ๐ŸŒธ

Joshua ben Jore has authored a minor-mode for emacs that allows you to run perlcritic on the current region or buffer. You can run it on demand, or configure it to run automatically when you save the buffer. The output appears in a hot-linked compiler buffer. The code and installation instructions can be found in the extras directory inside this distribution.

๐Ÿฆ‹ VIM ๐Ÿฆ‹

Scott Peshak has published perlchecker.vim, which is available at <http://www.vim.org/scripts/script.php?script_id=1731>.

โœจ gVIM โœจ

Fritz Mehner recently added support for perlcritic to his fantastic gVIM plugin. In addition to providing a very Perlish IDE, Fritz's plugin enables one-click access to perlcritic and many other very useful utilities. And all is seamlessly integrated into the editor. See <http://lug.fh-swf.de/vim/vim-perl/screenshots-en.html> for complete details.

๐Ÿ’œ EPIC ๐Ÿ’œ

EPIC is an open source Perl IDE based on the Eclipse platform. Features include syntax highlighting, on-the-fly syntax check, content assist, code completion, perldoc support, source formatting with Perl::Tidy, code templates, a regular expression editing tool, and integration with the Perl debugger. Recent versions of EPIC also have built-in support for Perl::Critic. At least one Perl::Critic contributor swears by EPIC. Go to <http://e-p-i-c.sourceforge.net> for more information about EPIC.

๐Ÿ“ BBEdit ๐Ÿ“

Josh Clark has produced an excellent Perl::Critic plugin for BBEdit. See <http://globalmoxie.com/projects/bbedit-perl-critic/index.shtml> for download, installation, and usage instructions. Apple users rejoice! ๐ŸŽ

๐ŸŽ€ Komodo ๐ŸŽ€

Komodo is a proprietary IDE for Perl and several other dynamic languages. Starting in version 5.1.1, Komodo has built-in support for Perl::Critic, if you have the Perl::Critic and criticism modules installed. Free trial copies of Komodo can be obtained from the ActiveState website at <http://www.activestate.com>.

๐ŸŒˆ ActivePerl ๐ŸŒˆ

ActivePerl includes a very slick graphical interface for configuring and running Perl::Critic called perlcritic-gui. A free community edition of ActivePerl can be obtained from the ActiveState website at <http://www.activestate.com>.

โญ Visual Studio Code โญ

Visual Studio Code is a lightweight but powerful source code editor which runs on your desktop and is available for Windows, macOS and Linux.

The perlcritic extension can be found here: <https://marketplace.visualstudio.com/items?itemName=sfodje.perlcritic>

The steps to install the perlcritic extension:

  1. Menu: View->Command Palette
  2. Type in "Extensions"
  3. Select "Extensions: Install Extension"
  4. In the search box type "perlcritic" and the extensions pane will open.
  5. perlcritic should be the first entry
  6. Select the "install" button
  7. Once installed go to Preferences->Settings
  8. Type in "perlcritic" in the search box
  9. The settings options for perlcritic will show and you configure the extension here. 9a. If you want perlcritic to run automatically when the file is saved, select "only critique on save".

Open a Perl file. Save it and perlcritic should fire. There is a triangle with an exclamation point on the status bar. Click it and it will open the issues that perlcritic has found. ๐Ÿ”ฅ


๐Ÿšฆ EXIT STATUS ๐Ÿšฆ

  • If perlcritic has any errors itself, exits with status == 1.
  • If there are no errors, but perlcritic finds Policy violations in your source code, exits with status == 2.
  • If there were no errors and no violations were found, exits with status == 0.

๐Ÿ‘‘ THE Perl::Critic PHILOSOPHY ๐Ÿ‘‘

Coding standards are deeply personal and highly subjective. The goal of Perl::Critic is to help you write code that conforms with a set of best practices. Our primary goal is not to dictate what those practices are, but rather, to implement the practices discovered by others. Ultimately, you make the rules โ€” Perl::Critic is merely a tool for encouraging consistency. If there is a policy that you think is important or that we have overlooked, we would be very grateful for contributions, or you can simply load your own private set of policies into Perl::Critic. ๐Ÿซถ


๐Ÿงš EXTENDING THE CRITIC ๐Ÿงš

The modular design of Perl::Critic is intended to facilitate the addition of new Policies. You'll need to have some understanding of PPI, but most Policy modules are pretty straightforward and only require about 20 lines of code. Please see the Perl::Critic::DEVELOPER file included in this distribution for a step-by-step demonstration of how to create new Policy modules.

If you develop any new Policy modules, feel free to send them to <team@perlcritic.com> and I'll be happy to consider putting them into the Perl::Critic distribution. Or if you would like to work on the Perl::Critic project directly, you can fork our repository at <https://github.com/Perl-Critic/Perl-Critic.git>.

The Perl::Critic team is also available for hire. ๐Ÿ’ผ If your organization has its own coding standards, we can create custom Policies to enforce your local guidelines. Or if your code base is prone to a particular defect pattern, we can design Policies that will help you catch those costly defects before they go into production. To discuss your needs with the Perl::Critic team, just contact <team@perlcritic.com>.


๐Ÿ“ฌ CONTACTING THE DEVELOPMENT TEAM ๐Ÿ“ฌ

You are encouraged to subscribe to the mailing list at <https://groups.google.com/d/forum/perl-critic>. At least one member of the development team is usually hanging around in <irc://irc.perl.org/#perlcritic> and you can follow Perl::Critic on Twitter, at <https://twitter.com/perlcritic>.


๐ŸŒˆ SEE ALSO ๐ŸŒˆ

There are a number of distributions of additional Policies available. A few are listed here:

  • Perl::Critic::More
  • Perl::Critic::Bangs
  • Perl::Critic::Lax
  • Perl::Critic::StricterSubs
  • Perl::Critic::Swift
  • Perl::Critic::Tics

These distributions enable you to use Perl::Critic in your unit tests:

  • Test::Perl::Critic
  • Test::Perl::Critic::Progressive

There is also a distribution that will install all the Perl::Critic related modules known to the development team:

  • Task::Perl::Critic

๐Ÿ’€ BUGS ๐Ÿ’€

Okay bestie, real talk: reading Perl code and judging it? That's hard. Like, hard for actual humans with brains, so imagine how hard it is for a machine. ๐Ÿ˜ญ

So if you find any bugs โ€” and especially if you find false-positives or false-negatives coming out of a Perl::Critic::Policy โ€” please, please submit them here:

https://github.com/Perl-Critic/Perl-Critic/issues

Thanks. ๐Ÿซถ Like genuinely, the devs eat these up, no cap.


๐ŸŽ€ CREDITS ๐ŸŽ€

Time to hype up the icons who made this whole thing happen. Sit down, we're doing shoutouts. ๐Ÿ‘‘

  • Adam Kennedy โ€” For creating PPI, the heart and soul of Perl::Critic. ๐Ÿ’– Literally the whole vibe depends on this man.
  • Damian Conway โ€” For writing Perl Best Practices, finally :) โœจ The source text, the blueprint, the moment.
  • Chris Dolan โ€” For contributing the best features and Policy modules. ๐Ÿ”ฅ Absolute main character energy.
  • Andy Lester โ€” Wise sage and master of all-things-testing. ๐Ÿงš Testing royalty fr fr.
  • Elliot Shank โ€” The self-proclaimed quality freak. ๐Ÿ’… Respect the branding, honestly.
  • Giuseppe Maxia โ€” For all the great ideas and positive encouragement. ๐ŸŒธ The supportive bestie we all need.
  • and Sharon, my wife โ€” For putting up with my all-night code sessions. ๐Ÿฅน Okay this one made me emotional actually.

Thanks also to the Perl Foundation for providing a grant to support Chris Dolan's project to implement twenty PBP policies. ๐Ÿ‘‘

http://www.perlfoundation.org/april_1_2007_new_grant_awards

โœจ AUTHOR โœจ

Jeffrey Ryan Thalhammer <jeff@imaginative-software.com>


Copyright (c) 2005-2021 Imaginative Software Systems. All rights reserved.

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. The full text of this license can be found in the LICENSE file included with this module.


๐Ÿ’œ Okay so that's the whole page, bestie. Go forth, lint some Perl, and remember: the machine is judging your code so that a human doesn't have to.

And that's a wrap on this one! ๐ŸŒˆ This beauty came from perl v5.40.0 and got dated 2024-10-28, and it lives under the name PERLCRITIC(1p). Stay slay, keep your policies tight, and may your exit status always be 0. ๐ŸŽ€๐Ÿ’–โœจ

๐Ÿ“ฆ where this page comes from