PERLCRITIC(1p)
๐ 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 FILEor-p FILEโ tellsperlcriticto use a profile named by FILE instead of going hunting for the default.perlcriticrcfile in the current directory or your home directory. want more deets? see "CONFIGURATION" in Perl::Critic. ๐--noprofileโ tellsperlcriticto load no configuration file at all, which means everything reverts to the default configuration for all Policies. factory settings, periodt โจ--severity Nโ tellsperlcriticto only apply Policies with a severity greater thanN. severity values are integers ranging from1(least severe) to5(most severe). the default is5. for a given--profile, decreasing the--severitywill usually produce more violations. you can set the default value for this option in your.perlcriticrcfile. you can also redefine theseverityfor any Policy in your.perlcriticrcfile. see "CONFIGURATION" for more info. ๐-5|-4|-3|-2|-1โ these are numeric shortcuts for setting the--severityoption. for example,-4is equivalent to--severity 4. if multiple shortcuts are specified, then the most restrictive one wins. if an explicit--severityoption 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--topflag, orperlcriticwill interpret it as the number of violations to report. ๐
--severity NAMEโ if you can never remember whether severity5is 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--severityoption. for example,--cruelis equivalent to--severity 2. if multiple shortcuts are specified, then the most restrictive one wins. if an explicit--severityoption is also given, then all shortcut options are silently ignored. ๐ฆ--theme RULEโ tellsperlcriticto apply only Policies with themes that satisfy theRULE. themes are arbitrary names for groups of related policies. you can combine theme names with boolean operators to create an arbitrarily complexRULE. 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โ tellsperlcriticto 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โ tellsperlcriticto 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 PATTERNor-s PATTERNโ tellsperlcriticto 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--onlyoptions. 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 ]โ tellsperlcriticto report only the topNPolicy violations in each file, ranked by their severity. ifNis not specified, it defaults to20. if the--severityoption (or one of the shortcuts) is not explicitly given, the--topoption implies that the minimum severity level is1(i.e.brutal). users can redefine the severity for any Policy in their.perlcriticrcfile. see "CONFIGURATION" for more info. you can set the default value for this option in your.perlcriticrcfile.
โ ๏ธ NOTE: be careful not to put one of the severity shortcut options immediately after the--topflag, orperlcriticwill interpret it as the number of violations to report. ๐ญ
--forceโ tellsperlcriticto ignore the magical## no criticannotations in the source code. see "BENDING THE RULES" for more info. you can set the default value for this option in your.perlcriticrcfile. ๐ฅ--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--statisticsoption, 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) andperlcriticreports 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--verboseat all? It defaults to either 4 or 5, depending on whether multiple files were given as arguments toperlcritic. And yeah bestie, you can set the default value for this one in your.perlcriticrcfile. ๐
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.perlcriticrcor 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.perlcriticrcfile 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.perlcriticrcfile. Chef's kiss for bootstrapping. ๐--onlyโ tells perlcritic to apply only the Policies that are explicitly mentioned in your.perlcriticrcfile. 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.perlcriticrcfile. ๐--profile-strictness {warn|fatal|quiet}โ tells perlcritic how to treat certain recoverable problems found in a.perlcriticrcor in a file specified via the--profileoption. 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.perlcriticrcfile. ๐ค--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.perlcriticrcfile. ๐๐--pager PAGER_COMMAND_STRINGโ if set, perlcritic will pipe its output to the givenPAGER_COMMAND_STRING. You can set the default value for this option in your.perlcriticrcfile.
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-policyto 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-policyto find files that do not contain violations of a given policy. Can also be specified as--L.--program-extensions file_name_extensionโ tellperlcriticto 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 matchm/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::RequireUpperCaseHeredocTerminatorat the command prompt. Life-saver, fr. ๐--allow-unsafeโ this option directsperlcriticto 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 completeperlcriticmanual and exits. The whole thing. Every last word. Grab a snack. ๐--versionโ displays the version number ofperlcriticand 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โ5sternโ4harshโ3cruelโ2brutalโ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::Criticpbpโ Policies that come directly from "Perl Best Practices"bugsโ Policies that that prevent or reveal bugscertrecโ Policies that CERT recommendscertruleโ Policies that CERT considers rulesmaintenanceโ Policies that affect the long-term health of the codecosmeticโ Policies that only have a superficial effectcomplexityโ Policies that specifically relate to code complexitysecurityโ Policies that relate to security issuestestsโ 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 criticshould 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:
- Menu: View->Command Palette
- Type in "Extensions"
- Select "Extensions: Install Extension"
- In the search box type "perlcritic" and the extensions pane will open.
- perlcritic should be the first entry
- Select the "install" button
- Once installed go to Preferences->Settings
- Type in "perlcritic" in the search box
- 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
perlcritichas any errors itself, exits with status== 1. - If there are no errors, but
perlcriticfinds 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::MorePerl::Critic::BangsPerl::Critic::LaxPerl::Critic::StricterSubsPerl::Critic::SwiftPerl::Critic::Tics
These distributions enable you to use Perl::Critic in your unit tests:
Test::Perl::CriticTest::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 ofPerl::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 ๐
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
- debian trixie: libperl-critic-perl 1.156-1 ยท Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu resolute: libperl-critic-perl 1.156-1 ยท Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu stonking: libperl-critic-perl 1.156-1 ยท Artistic-1.0-Perl OR GPL-1.0-or-later
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms