Monday, March 23, 2009

Write better Perl with Perl::Critic

I have recently discovered a simple-to-use static code analysis tool for Perl.
It will examine your source file and list a series of warnings when it notices contructs that are different from the recommended practices.

Let me present you the Perl::Critic module, which allows the creation of a very simple script as described in the documentation.
use Modern::Perl;
use Perl::Critic;

die "No file name as argument\n" if (@ARGV == 0);
my $file = $ARGV[0];

my $critic = Perl::Critic->new();
my @violations = $critic->critique($file);
print @violations;
With this bit of code, you can check any Perl file for Policy violations within the program itself.

If you name the above script, you can also analyze external programs by typing "perl".
However, as Chris pointed out in the comments section (thanks!), there is a simpler way: use the perlcritic command line interface provided with the Perl::Critic module.
There are many available options to customize your analysis.

You can apply any policy that you would like. The default is the one described in Damian Conway's "Perl Best Practices" (PBP) book. A summary of all available policies on CPAN can be found here.

There is actually an even better way to use the Perl::Critic tool than the command line: the perlcritic website where you can jump directly to the offending lines in your code. You are also able to click on links taking you to the PBP's page related to the warning being displayed!

I find it a great way to learn good Perl programming tips with very little effort, as all the information is only one click away!

[Edit] For more in-depth information about Perl::Critic, take a look at this article from Perl Training Australia.

Larry Wall quote of the day:
"If someone stinks, view it as a reason to help them, not a reason to avoid them."


  1. Or you could just use the "perlcritic" command line interface that comes pre-installed with Perl::Critic

  2. Thanks Chris!
    Somehow I totally missed that perlcritic command line interface :|
    I'll update the post right away.

  3. Perl::Critic also has a number of useful command-line options to select or exclude warnings, and also to expand the output in case you don't have a copy of PBP sitting on your desk. These can even be rolled into per-project and per-user .perlcriticrc files.

    There's a much longer discussion of these in our Perl-tip at .

    Also, as a small nit-pick, it's "Damian Conway". Damien is his evil twin brother. ;)

  4. @Paul Thanks for the tips! I've added your link at the bottom of the post.

    Concerning the typo on Damian's name, please consider the title of this blog and the name of the author before saying that anyone is evil ;)
    (yes, I know about "The Omen").