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 FILE or -p FILE β€” Directs perlcritic to use a profile named by FILE rather than looking for the default .perlcriticrc file in the current directory or your home directory. See CONFIGURATION in Perl::Critic for more information.
  • --noprofile β€” Directs perlcritic not to load any configuration file, thus reverting to the default configuration for all Policies.
  • --severity N β€” Directs 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 information.
  • -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 it is difficult for you to remember whether severity 5 is 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 --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 β€” Directs 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 information about themes.

  • --include PATTERN β€” Directs 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 β€” Directs 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 β€” Directs 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 ] β€” Directs 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 information. 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 β€” Directs perlcritic to ignore the magical ## no critic annotations in the source code. See BENDING THE RULES for more information. 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.
  • --statistics-only β€” Like the --statistics option, 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) and perlcritic picks 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 --verbose at all, it defaults to either 4 or 5, depending on whether you handed perlcritic multiple files as arguments. You can set the default value for this option in your .perlcriticrc file. πŸ’–

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 every Perl::Critic::Policy module chillin' on this machine. And like, all of them β€” your .perlcriticrc and 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 the Perl::Critic::Policy modules 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 .perlcriticrc and 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 the Perl::Critic::Policy modules found on this machine. That's it, that's the vibe check. 🌈
  • --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, default themes, plus the name of any extra parameters that Policy supports. The format is literally built to be a prototype for your .perlcriticrc file. 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 .perlcriticrc file. πŸ’…
  • --profile-strictness {warn|fatal|quiet} β€” tells perlcritic how to handle certain recoverable problems it finds in a .perlcriticrc or in a file passed via the --profile option. 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 .perlcriticrc file. πŸ”₯
  • --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::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 pipes its output to whatever PAGER_COMMAND_STRING you gave it. You can set the default value for this option in your .perlcriticrc file.

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-policy to 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-policy to find files that don't contain violations of a given policy. Can also be specified as --L. ✨
  • --program-extensions file_name_extension β€” tells perlcritic to 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 every Perl::Critic::Policy module matching m/PATTERN/ixms. Policy modules tend to have, like, absurdly long names, so this is just a more convenient way to say something like perldoc Perl::Critic::Policy::ValuesAndExpressions::RequireUpperCaseHeredocTerminator at the command prompt. Saving your wrists fr fr. πŸ’–
  • --allow-unsafe β€” directs perlcritic to 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 --man dumps on you. πŸ’€
  • --man β€” displays the complete perlcritic manual and exits. πŸ“–
  • --version β€” displays the version number of perlcritic and 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::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 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 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.

✨ 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:

  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. 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::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 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 of Perl::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 (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