How can I automatically tidy up Perl source code?

A cat at my company walked over a keyboard and has left a valid 1000+ line of executable Perl code for me to maintain.

Thanks to Perl's TMTOWTDI philosophy I find myself searching Google to make sense of every line of code she has produced.

To add to my misery the code is not indented and one find frequent occurrence of the two statements on one line, inability figure out whether a loop is outer/inner.

How can I auto-intend this Perl code to sanity? Yes I bet there would be some CPAN module that does that. How about some external tool? Any clues?

Answers


Perl::Tidy can do that, and much more. It's usually used through the perltidy executable it installs.


Perl Tidy is a really useful utility. It comes with an offputting array of options. There is some guidance at http://perltidy.sourceforge.net/ and http://perltidy.sourceforge.net/tutorial.html

For example -i=8 overides the number of spaces to indent (default=4) and -bl puts braces on a new line :

 if ( $something )
 {
     print ".....";
 }

I would suggest playing on a copy of the code and seeing which option you like the best.

You can either install it from CPAN, or varioujs other options on http://perltidy.sourceforge.net/ depending on your platform and taste !


Here are a few examples of how to use perltidy with non-default behavior:

  • Enable cuddled-elses ( eg. } else { ), limit line lengths to 300 characters for all .pl files

    $ perltidy -ce -l=300 *.pl
    
  • Maintain old comma breakpoints, freeze existing whitespaces in script.pl

    $ perltidy -boc -fws script.pl
    
  • Backup script and modify script1.pl, script2.pl in-place

    $ perltidy -b script1.pl script2.pl
    
  • 'Obfuscate' script by stripping it of as much whitespace as possible.

    $ perltidy --mangle scipt.pl
    

As with most things, if you search CPAN, you have your answer faster than it takes you to login to Stack Overflow. :)

In this case, it's Perl::Tidy as other people have already mentioned. We have some longer advice about this in Effective Perl Programming too.


You can use also online tool http://www.cleancss.com/perl-beautify/ .


Need Your Help

What is LINQ and what does it do?

c# linq

What is LINQ? I know it's for databases, but what does it do?

Is it possible to use irrefutable tilde (`~`) patterns in lambda expressions?

haskell pattern-matching

GHC gives me a parse error on input \~ if I try to put a tilde on the pattern of a lambda expression like I can do with named functions