PrePAN

Sign in to PrePAN

Perl::Rewrite A set of rules for rewriting/transforming Perl code

Good

Synopsis

use Perl::Rewrite;

my $prw = Perl::Rewrite->new();

$prw->config(
  rule1 => \%config1, # options for rule 1
  rule2 => \%config2, # options for rule 2
  ...
);

# Rules would be in the Perl::Rewrite::Rule namespace

...

foreach my $file (@files) {
  $prw->rewrite($file);
}

Description

The aim of this module is to provide a common API for rules to rewrite Perl scripts. Sample rules might be:

  • ensure every script has a shebang line

  • ensure every script and module specifies a minimum Perl version

  • change occurrances of die/warn to croak/carp, and ensure the Carp module is used

  • change print "...\n" to say "...", and ensure v5.10.1 minimum Perl version is used

  • change complex if/else blocks to for/when blocks

  • change include lines (use/require/etc) so that they are sorted, e.g. perl version, then pragmas (sorted), and then modules (sorted)

  • etc.

The intention of this module is to assist with updating large legacy codebases, or as a companion to Perl::Tidy and Perl::Critic that can enforce coding policies.

Comments

Note that the rule plugins will have a method to indicate the API that they want. Different APIs:
- the entire document
- for each statement in the document (modulo surrounding expressions)
I'm excited about this. What do the rules look like?
At the moment, not much besides what's on GitHub, which are simple rules. I have prototype code (not yet on GitHub) to change die/warn to croak/carp and print "foo\n" to say "foo". The idea is to get a common framework so people can contribute their own rules.

I'm trying to think of a better API that can pick out statements from inside expressions, to make writing some rules easier.
I agree with @briandfoy, this is a great idea. Sometimes Perltidy and Perl::Critic just aren't enough.
Please state very prominently in the documentation that this is *not* to be used as a general source filter after installation! As a semi-automatic code cleaner, companion to perltidy, it can be a great tool. It's also (as all the best tools) very easy to abuse :)
@dakkar: I'm not sure how one could use it as a filter, but it wouldn't make any sense to.
Oh, I realise that it wouldn't make sense, but never underestimate the creativity of Perl people! :) You can always put a coderef in @INC, and use anything you want as a filter.
See also Padre::Document::Perl::QuickFix and its subclasses.
Good looking module so far, and sure to be useful. It will be interesting to see how you handle *very* old Perl. Here There Be Dragons.
@dolmen: thanks for the link.

Please sign up to post a review.