Quick introduction here so uninterested parties can continue on, this is about not having code in .pl scripts and instead breaking it out into a module and calling the module as the only line in the 'script'
This meditation was written by request, from someone who had seen my short Re: use and require inside subs post on this subject in reply to a question regarding use and require inside subs use and require inside subs. This person was curious about overhead involved and what the .pl files end up looking like.
I believe that all code should be tested. That being the case, having a .pl script with a bunch of code in it that uses my nicely tested modules just feels wrong. I use Devel::Cover as a guide to how much of my code I've bothered to test, and unless all my code is available to my test suite I do not truly know that my code is tested.
Of course, doing this for anything under (say) 20 lines of code is probably not worth the effort, but then that doesn't fall under my category of serious scripts either. This is not to knock some of the awesome things in 20 lines, but more to acknowledge that there are situations where it isn't really much use.
So let's look at what it takes to take a script and make it a module. Say I have this script, with foo and bar subs
#!/usr/bin/perl sub foo { } sub bar { } foo(bar(@ARGV));
Obviously this falls under my 20 line rule but I'm trying to show how it's done here ;)
The first step is to copy the .pl to a .pm file, in the appropriate namespace. I'll pretend that I use the Mischief namespace for all of my modules, so I put this script in Mischief/Scripts/foobar.pm
package Mischief::Scripts::foobar; use strict; use base 'Exporter'; our @EXPORT = qw/run_script/; sub foo { } sub bar { } sub run_script { foo(bar(@ARGV)); } 1;
Then, we can cut the original .pl script down to
#!/usr/bin/perl use strict; use Mayhem::Script::foobar qw/run_script/; run_script();
And we get the nice benefit of having our script code being an integrated part of the code base, which makes refactoring much easier as well as having benefits for testability and code reuse.
In reply to There Are No Perl Scripts by Tuppence
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |