OSCON 2007: Taming Legacy Perl, by Peter Scott
- Mon Jul 23 2007
- OSCON 2007
- 2 comments
I arrived late to this tutorial because I set my alarm for 6:30PM instead of 6:30AM. I know now that it’s possible to wake up, shower, get stuff together, and get to the convention center in 25 minutes.
I arrived to Peter Scott talking about Test::More, which isn’t all that surprising given the topic: taming legacy Perl. I use Test::More in my modules (sometimes not very well), but I did learn that Test::More has functions like eq_hash for hash testing. Other useful modules he touched upon include Test::NoWarnings, Test::MockObject, and Test::MockModule.
Getting a bit away from legacy code, he recommends using h2xs when you’re starting to write a module, if only to get your Makefile.PL for free. Or you could use ExtUtils::ModuleMaker, Module::Start, or Module::Starter. Create a t directory, stick your test programs in there, then if you do perl Makefile.PL; make test it’ll run your tests.
Remember that your tests are programs: use good development practices, use strict and use warnings, keep them small, refactor as necessary, etc.
To test web apps, check out the WWW::Mechanize module, which mimics a webserver, and Test::WWW::Mechanize to test for HTML-y things.
Should you rewrite legacy code? The major advantages to doing this include:
- you own the new code
- you understand it
- you remember it
- testing is much more fun
- it probably won’t take as long as you think…
- …or, not rewriting will take longer than you think
The tutorial seems to be moving away from legacy code and towards good coding habits now… Code should be pretty to look at. You should add comments where you had to think a lot. You can use perltidy to fix up even the worst layout.
Analyzing code can be done using Devel::Cover and Devel::Coverage. These modules look at branching, code line touches, etc., to make sure that your tests adequately cover all possible conditions in your code.
Moving back to inherited code, you have to watch for the apparent level of Perl expertise: does it use Perl-ish structures such as regular expressions or hashes? Does it call parallel arrays or hashes instead of lists of lists? Does it call unnecessary external programs instead of using modules? Does it use my, local, or use? To reduce bloat, look for opportunities to use third-party modules, put duplicated code into subroutines, put duplicated subroutines into modules, don’t optimize for speed before optimizing the code for clarity.
Replace magic numbers with symbolic names. HTML strings should be replaced with a templating system (like HTML::Template or Text::Template). Use the /x modifier to document large regular expressions, or build them up using the qr// operator. Move variable declaration to the latest possible point. Use use strict. Use CPAN.
…and document using POD.

