Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 212
Ankur Gupta Avatar asked Oct 16 '10 08:10

Ankur Gupta


4 Answers

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

like image 52
rafl Avatar answered Oct 11 '22 10:10

rafl


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 !

like image 30
justintime Avatar answered Oct 11 '22 08:10

justintime


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
    
like image 35
Zaid Avatar answered Oct 11 '22 09:10

Zaid


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.

like image 31
brian d foy Avatar answered Oct 11 '22 09:10

brian d foy