PERLCRITIC(1)
π PERLCRITIC(1) π
okay bestie, welcome to the User Contributed Perl Documentation page for perlcritic β yes, that one. This is the command-line interface to critique Perl source, and it's genuinely iconic. π
πΈ NAME πΈ
perlcritic β the command-line interface to critique Perl source. Slay. β¨
β¨ 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 its whole main-character job is trying to identify awkward, hard to read, error-prone, or unconventional constructs in your code. π
Most of the rules are based on Damian Conway's book Perl Best Practices. But no cap: perlcritic is not limited to enforcing PBP, and it will even support rules that contradict Conway. All rules can easily be configured or disabled to your liking. Obsessed. π«Ά
This documentation only covers how to drive this command. For all other information, such as API reference and alternative interfaces, please see the documentation for Perl::Critic itself.
π USAGE EXAMPLES π
Before getting into all the gory details, here are some basic usage examples to help get you started. You're gonna eat these up. π
# 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 may specify multiple files. If an argument is a directory, perlcritic will analyze all Perl files below the directory. If no arguments are specified, then input is read from STDIN.
π OPTIONS π
Option names can be abbreviated to uniqueness and can be stated with single or double dashes, and option values can be separated from the option name by a space or = (as with Getopt::Long). Option names are also case-sensitive. iykyk. β¨
--profile FILEor-p FILEβ Directsperlcriticto use a profile named by FILE rather than looking for the default.perlcriticrcfile in the current directory or your home directory. SeeCONFIGURATIONin Perl::Critic for more information.--noprofileβ Directsperlcriticnot to load any configuration file, thus reverting to the default configuration for all Policies.--severity Nβ Directsperlcriticto 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. SeeCONFIGURATIONfor more information.-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 it is difficult for you to remember whether severity5is the most or least restrictive level, 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β Directsperlcriticto 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 information about themes.
--include PATTERNβ Directsperlcriticto 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β Directsperlcriticto 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β Directsperlcriticto 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 ]β Directsperlcriticto 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. SeeCONFIGURATIONfor more information. 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β Directsperlcriticto ignore the magical## no criticannotations in the source code. SeeBENDING THE RULESfor more information. 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.--statistics-onlyβ Like the--statisticsoption, but suppresses normal output and only shows the statistics.--verbose N | FORMATβ sets the verbosity level or the format used when reporting violations. Give it a number (N) andperlcriticpicks one of the built-in formats listed below. Give it a string (FORMAT) and it's treated as a literal format specification of your very own. If you don't pass--verboseat all, it defaults to either 4 or 5, depending on whether you handedperlcriticmultiple files as arguments. You can set the default value for this option in your.perlcriticrcfile. π
Here's the whole menu of preset verbosity levels β order off the menu, bestie:
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 mix of literal characters and escape characters, kinda like how sprintf does its thing. Want the full lore on what the formatting can do? Peep String::Format. The valid escape characters are, and I'm obsessed with this list:
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 point of these formats is compatibility with text editors that parse certain kinds of input. See EDITOR INTEGRATION for the deets on that. β¨
--listβ shows a condensed listing of everyPerl::Critic::Policymodule chillin' on this machine. And like, all of them β your.perlcriticrcand command line options don't get a vote here. For each Policy you get the name, the default severity, and the default themes. π--list-enabledβ condensed listing of all thePerl::Critic::Policymodules that would be enforced if you were actually gonna critique a file with this exact command. This is the one you want when you've built some unhinged complicated command or tweaked your.perlcriticrcand you're like "okay but which Policies are actually running??" (or not running, as the case may be). For each Policy: name, default severity, default themes. π«Ά--list-themesβ lists every theme from thePerl::Critic::Policymodules found on this machine. That's it, that's the vibe check. π--profile-protoβ an expanded listing of all thePerl::Critic::Policymodules found on this machine. For each Policy you get the name, default severity, default themes, plus the name of any extra parameters that Policy supports. The format is literally built to be a prototype for your.perlcriticrcfile. Chef's kiss for scaffolding. π--onlyβ tells perlcritic to apply only the Policies explicitly mentioned in your.perlcriticrc. Perfect when you want a tiny curated subset without hand-disabling every other Policy one by one. You can set the default value for this option in your.perlcriticrcfile. π--profile-strictness {warn|fatal|quiet}β tells perlcritic how to handle certain recoverable problems it finds in a.perlcriticrcor in a file passed via the--profileoption. Valid values are"warn"(the default),"fatal", and"quiet". Example: perlcritic normally only warns about profiles that reference 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β displays only the number of violations for each file. Use this to get a quick handle on where a big pile of code probably needs the most attention. Diagnostic speedrun, basically. π--color,--colourβ this one's on when output's going to a tty. When set, Severity 5 and 4 get colored red and yellow, respectively. Coloring only happens if Term::ANSIColor is installed. On Windows,Win32::Console::ANSImust 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 pipes its output to whateverPAGER_COMMAND_STRINGyou gave it. You can set the default value for this option in your.perlcriticrcfile.
Heads up tho: setting a pager turns off color by default. You'll have to turn color on explicitly. And 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 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 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 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 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 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β displays only the names of files with violations. Pair this with--single-policyto hunt down files containing violations of a given policy. Can also be specified as--l. π--files-without-violationsβ displays only the names of files without violations. Pair this with--single-policyto find files that don't contain violations of a given policy. Can also be specified as--L. β¨--program-extensions file_name_extensionβ tellsperlcriticto treat files whose names end in the given file name extension as programs, not as modules. If you want a leading'.'you have to specify it explicitly, like:
--program-extensions .pl
Matching is case-sensitive, and you can pass this option as many times as you want, like:
--program-extensions .pl --program-extensions .cgi
You can also do the exact same thing by quoting the file name extensions:
--program-extensions '.pl .cgi'
Files whose name ends in '.PL' will always be considered programs. No cap. π
--doc PATTERNβ displays the perldoc for everyPerl::Critic::Policymodule matchingm/PATTERN/ixms. Policy modules tend to have, like, absurdly long names, so this is just a more convenient way to say something likeperldoc Perl::Critic::Policy::ValuesAndExpressions::RequireUpperCaseHeredocTerminatorat the command prompt. Saving your wrists fr fr. π--allow-unsafeβ directsperlcriticto allow Policies marked as"unsafe".
Real talk, bestie: unsafe Policies may result in risky operations by compiling and executing the code they analyze. π All the Policies shipping in the core Perl::Critic distribution are safe. But third party Policies β like the ones in the Perl::Critic::Dynamic distribution β may not be. Note that "safety" here is honorary: if a Policy author marks a Policy as safe, that is not a guarantee it won't do nasty things. If you don't trust your Policies and the code you're analyzing, don't use this switch. Periodt.
--quietβ suppresses 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. Yeah this output is long, but it is nowhere near the length of what--mandumps on you. π--manβ displays the completeperlcriticmanual and exits. π--versionβ displays the version number ofperlcriticand exits. π
π CONFIGURATION π
okay so bestie, here's the tea: most of the settings for Perl::Critic and for each of the Policy modules can be controlled by a configuration file. the default configuration file is literally called .perlcriticrc. perlcritic will look for this file in the current directory first, and then in your home directory. alternatively, you can set the PERLCRITIC environment variable to explicitly point to a different file in another location. and if none of these files exist, and the --profile option is not given on the command-line, then all Policies will be loaded with their default configuration. slay, defaults! β¨
the format of the configuration file is a series of INI-style blocks that contain key-value pairs separated by =. comments should start with # and can be placed on a separate line or after the name-value pairs if you desire. very chill of them ngl π«Ά
default settings for perlcritic itself can be set before the first named block. for example, putting any or all of these at the top of your .perlcriticrc file will set the default value for the corresponding 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
the remainder of the configuration file is a series of blocks 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 a module that implements the policy. the Policy modules distributed with Perl::Critic have been grouped into categories according to the table of contents in Damian Conway's book Perl Best Practices. for brevity, you can omit the Perl::Critic::Policy part of the module name. iconic shortcut behavior honestly π
severity is the level of importance you wish to assign to the Policy. all Policy modules are defined with a default severity value ranging from 1 (least severe) to 5 (most severe). however, you may disagree with the default severity and choose to give it a higher or lower severity, based on your own coding philosophy. you can set the severity to an integer from 1 to 5, or use one of the equivalent names:
SEVERITY NAME ...is equivalent to... SEVERITY NUMBER
----------------------------------------------------
gentle 5
stern 4
harsh 3
cruel 2
brutal 1
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 information. π
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. see "POLICY THEMES" for more information. (yes it's basically a remix, not a replacement, and that's the whole point π)
the remaining key-value pairs are configuration parameters that will be passed into the constructor of that Policy. the constructors for most Policy modules do not support arguments, and those that do should have reasonable defaults. see the documentation on the appropriate Policy module for more 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. in this manner, the Policy will never be loaded, regardless of the --severity given on the command line. it's giving "blocked, do not perceive" energy π
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, as with Perl numeric literals. for example:
[ValuesAndExpressions::RequireNumberSeparators]
min_value = 1_000
for additional configuration examples, see the perlcriticrc file that is 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. king behavior, honestly π
π THE POLICIES π
a large number of Policy modules are distributed with Perl::Critic. they are described briefly in the companion document Perl::Critic::PolicySummary and in 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. regex matching your way into the docs, we love to see it π₯
there are a number of distributions of additional policies on CPAN. if Perl::Critic doesn't contain a policy that you want, some one may have already written it. see "SEE ALSO" in Perl::Critic for a list of some of these distributions. no cap, the ecosystem is huge π
π¦ POLICY THEMES π¦
each Policy is defined with one or more "themes". themes can be used to create arbitrary groups of Policies. they are intended to provide an alternative mechanism for selecting your preferred set of Policies. for example, you may wish disable a certain set of Policies when analyzing test programs. conversely, you may wish to enable only a specific subset of Policies when analyzing modules. it's giving curated playlist for your code πΈ
the Policies that ship with Perl::Critic are have been divided into the following themes. this is just our attempt to provide some basic logical groupings. you are free to invent new themes that suit your needs. go off, invent your own aesthetic π
coreβ All policies that ship with Perl::Criticpbpβ Policies that come directly from Perl Best Practicesbugsβ 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 that are associated with each one. you can also change the theme for any Policy in your .perlcriticrc file. see the "CONFIGURATION" section for more information about that. π
using the --theme command-line option, you can create an arbitrarily complex rule that determines which Policies to apply. precedence is the same as regular Perl code, and you can use parentheses to enforce precedence as well. supported operators are:
Operator Altertative Example
-----------------------------------------------------------------
&& and 'pbp && core'
|| or 'pbp || (bugs && security)'
! not 'pbp && ! (portability || complexity)'
theme names are case-insensitive. if the --theme is set to an empty string, then it evaluates as true all Policies. yes, literally everything β main character energy for real πβ
π BENDING THE RULES π
Okay so bestie, here's the thing: Perl::Critic is a strict queen. Either your code complies or it doesn't β no in-between, no vibes-based grading. π
But let's be real. In the actual real world it's not always practical (or honestly even possible) to fully comply with coding standards. And in those moments, the move is to make it super obvious that you know you're violating the standards and that you have a Damn Good Reason (DGR) for doing it. Own it. π
To help you out in those situations, 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($_);
}
The ## no critic annotations tell Perl::Critic to ignore the remaining lines of code until it finds a ## use critic annotation. And if the ## no critic annotation is chilling on the same line as a code statement? Then only that one line of code gets overlooked. π«
Oh and β if you want to direct perlcritic to ignore the ## no critic annotations entirely, use the --force option.
A bare ## no critic annotation disables all the active Policies. Which, like, wow, bold. If you only wanna disable specific Policies, 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;
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 shortcuts and we love it:
## no critic (NamingConventions)
# Now exempt from NamingConventions::Capitalization
my $camelHumpVar = 'foo';
# Now exempt from NamingConventions::Capitalization
sub camelHumpSub {}
A couple of rules though, no cap: the argument list must be enclosed in parentheses and must contain one or more comma-separated barewords (i.e. don't use quotes, bestie, please). Also the ## no critic annotations can be nested, and Policies named by an inner annotation will be disabled along with those already disabled by an outer annotation. Layers! π§
Some Policies like Subroutines::ProhibitExcessComplexity apply to an entire block of code. In those cases, ## no critic must appear on the line where the violation is reported. Like so:
sub complicated_function { ## no critic (ProhibitExcessComplexity)
# Your code here...
}
And some Policies like Documentation::RequirePodSections apply to the entire document, in which case violations are reported at line 1. But π if the file requires a shebang line, it is 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. Choose wisely. π
Use this feature wisely, fr fr.## 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.
β¨ 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 to the relevant line of code. Click-and-jump. Iconic behavior honestly. π±οΈβ¨
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.
perlcriticshould 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
perlcriticwill show and you configure the extension here. 9a. If you wantperlcriticto 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. Twenty lines!! That's like, one snack break. π
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 so real talk bestie β scrutinizing Perl code is hard for humans, let alone machines π. Like, we're out here asking a program to have opinions about your unless statements, so yeah, sometimes it gets it wrong.
If you find any bugs β and especially false-positives or false-negatives from a Perl::Critic::Policy β please submit them at <https://github.com/Perl-Critic/Perl-Critic/issues>. Thanks π«Άπ
ngl a good bug report is a love letter to the maintainers. false-positives are the worst offenders and they want to hear about them.
π CREDITS π
time to give the icons their flowers πβ¨
- Adam Kennedy β For creating
PPI, the heart and soul ofPerl::Critic. (literally the main character of this whole operation, no cap π) - Damian Conway β For writing Perl Best Practices, finally :)
- Chris Dolan β For contributing the best features and Policy modules.
- Andy Lester β Wise sage and master of all-things-testing.
- Elliot Shank β The self-proclaimed quality freak. (respect the self-awareness π )
- Giuseppe Maxia β For all the great ideas and positive encouragement.
- and Sharon, my wife β For putting up with my all-night code sessions. π₯Ήπ
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.
iykyk: "same terms as Perl itself" means the Artistic License / GPL dual situation β go read the LICENSE file if you want the whole tea βπ
and that's the whole page, bestie!! you made it to the end, i'm so proud of you fr fr π₯³π this was perl v5.42.0, dated 2024-10-23, and yes β it's PERLCRITIC(1) if you ever need to pull it up again πβ¨ go forth and write iconic Perl ππ¦
π¦ where this page comes from
- opensuse-leap 16.0: perl-Perl-Critic 1.156.0-bp160.1.1 Β· Artistic-1.0 OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms