Perl::Critic is your friend

January 29th 2012

Tags: perl, utilities

I've been writing Perl for a few years, but only recently did I hear about the amazing Perl::Critic. After using it for a couple of weeks, I'm starting to crave a similar tool for every language I work with.

For those unfamiliar with Perl::Critic, it isn't just another lint. It doesn't just show you where you screwed up in your code, but it tells you why that particular screwup was a bad idea.

Here is some Perl::Critic output from an older script I wrote:

$ perlcritic somescript.pl
Bareword file handle opened at line 4, column 1.  See pages 202,204 of PBP.  (Severity: 5)
Two-argument "open" used at line 4, column 1.  See page 207 of PBP.  (Severity: 5)
Bareword file handle opened at line 21, column 1.  See pages 202,204 of PBP.  (Severity: 5)
Two-argument "open" used at line 21, column 1.  See page 207 of PBP.  (Severity: 5)

By default, Perl::Critic will only complain about the worst offenses it finds (Severity: 5), to receive more abuse you can alter this behavior with command line flags:

$ perlcritic -3 somescript.pl
Code not contained in explicit package at line 1, column 1.  Violates encapsulation.  (Severity: 4)
Bareword file handle opened at line 4, column 1.  See pages 202,204 of PBP.  (Severity: 5)
Two-argument "open" used at line 4, column 1.  See page 207 of PBP.  (Severity: 5)
Return value of "open" ignored at line 4, column 1.  Check the return value of "open" for success.  (Severity: 3)
Split long regexps into smaller qr// chunks at line 10, column 14.  See page 261 of PBP.  (Severity: 3)
Regular expression without "/x" flag at line 10, column 14.  See page 236 of PBP.  (Severity: 3)
Regular expression without "/x" flag at line 15, column 14.  See page 236 of PBP.  (Severity: 3)
Regular expression without "/x" flag at line 16, column 17.  See page 236 of PBP.  (Severity: 3)
Bareword file handle opened at line 21, column 1.  See pages 202,204 of PBP.  (Severity: 5)
Two-argument "open" used at line 21, column 1.  See page 207 of PBP.  (Severity: 5)
Close filehandles as soon as possible after opening them at line 21, column 1.  See page 209 of PBP.  (Severity: 4)
Return value of "open" ignored at line 21, column 1.  Check the return value of "open" for success.  (Severity: 3)
Module does not end with "1;" at line 27, column 1.  Must end with a recognizable true value.  (Severity: 4)

Some of these responses reference PBP, these are page numbers in Perl Best Practices. With this essential tome in hand, every mistake is transformed into a learning opportunity.

You can easily run Perl::Critic against an entire source tree by using find. For example:

$ find -E . -iregex ".+\.p(m|l)$" -print -exec perlcritic -4 {} \;

You not only get better at writing Perl, but you will understand why your code is correct.

By Colin Kennedy