playing with ppi and perl critic

rjbs on 2006-11-10T15:36:31

I've heard a lot about Perl::Critic, and it has always sounded neat. Chris Dolan gave a talk about it at YAPC, and I decided I should give it a go. I didn't get around to it until this week. I went through and installed a perl-critic.t in all my distributions, then started testing them. Nearly all the violations it found were in a few groups.

"Don't use stringy eval!" Ok, but I'm trying to load a module by name, and I don't want to use UNIVERSAL::require. I need to use stringy eval!

"Don't put any code before use strict!" Ok, that's reasonable. I'll just move use strict to the very top of every file. "Now don't put any code before the package declaration!" What? No, it doesn't matter! It's lexical to the file!

The other things it caught were pretty reasonable, and I fixed them. I just didn't like the idea of putting no critic comments at places where I wanted to keep my code the same. When I looked at the code for policies, I was surprised at how simple it was. PPI exposes a really reasonable DOM, and I was able to code lots of fiddly little policy tweaks for my own use.

I have a few more policies I want to write, but so far I'm pretty happy with Perl::Critic and my own attempts to train its taste.


Perl::Critic++

jk2addict on 2006-11-10T15:59:24

I caught the P::C bug about 4 weeks ago.

One test checks the core modules. In my case, I set severity to 1, and then commented out policies in the rc that I don't agree with.

My second test file simply uses the RequireTestLabels and RequireRcsKeywords to make sure all of my test files at least meet those two requirements.

Other than being an anal retentive freakjob, my main goal is to have a set of policies and test coverage in place for Handel 1.0 before others start contributing to the codebase. Then I have something to point to and blame others when coverage or code style starts to suck. :-)

Perl::Critic's RequireExplicitPackage Policy

thaljef on 2006-11-15T08:59:20

The RequireExplicitPackage policy arose out of some code really bad legacy code that I have at work. A lot of it was written for Perl 4, and the author's didn't really understand how to use namespaces. Consider this example:

In file Foo.pm:
sub frobulator{ print shift; }
our $SHIZZLE = 42;

package Foo;

sub foo { return main::frobulator( @_ ) }


In file my_script.pl:
use Foo;
Foo::foo( $SHIZZLE );

Since $SHIZZLE and &frobulator are declared before the package statement in Foo.pm, they wind up in the caller's namespace (main). So Foo::foo will only work if it is loaded by main. And when my_script starts loading other libraries that might also load Foo, then it become a big steaming pile.

I trully hope that sane developers will never encounter this problem. But I'm frequently surprised how much insanity there is in the world :)