5 minimums for any perl script?

Kaoru kaoru at slackwise.net
Mon Jan 30 09:39:55 GMT 2012


On Sun, Jan 29, 2012 at 9:02 PM, Leo Lapworth <leo at cuckoo.org> wrote:
> I've been asked what would be a good minimum to have as a coding police
> for a company that isn't focused on Perl, but uses it occasionally. So if
> Perl Best Practices is too much, and you could only have 5 rules for any
> perl script, what would they be?

Here goes then...

1) Have sensible exit codes

0 on success, 1 on failure. You can use exit() and die() in Perl to
get this right.

Be careful with usage messages. If I ask for help with "--help" then
that's a good (zero) exit, if I mess up and get the flags wrong that's
a bad (non-zero) exit.

======================================

2) Have a good --help message

Where possible/sensible the usage message should be printed by default
if no flags are given at all, ie. the script should not do anything if
you run it "blind".

I usually use Pod::Usage and Getopt::Long together to get this.

use Getopt::Long;
use Pod::Usage;
GetOptions('help|h' => sub { pod2usage(0); });

=head1 NAME

...

=head1 SYNOPSIS

...

======================================

3) Pass at least Perl::Critic severity level 4 ("stern".)

This gets you "use strict" and "use warnings" for free, along with a
host of other good practices :-)

======================================

4) Modularize for unit testability

Where possible the script itself should contain very little logic. A
good template is:

use strict;
use warnings;

use My::Script::Module;

use Getopt::Long;
use Pod::Usage;

GetOptions(
    ...
);

my $Obj = My::Script::Module->new(...);

$Obj->run();

exit 0;


Note that you can use pod2usage(-input => "My/Script/Module.pm");

If you want to keep your docs close to the actual code.

Inside My::Script::Module split up the code into logical segments that
are easily unit tested, and of course write those unit tests!

======================================

5) Consider the script's audience carefully when deciding on the
amount and level of output

I think there are probably two kinds of scripts - one is designed to
be run via cron, and the other is designed to be run by a person.

For the "designed to be run by a person" scripts use say(),
Term::ProgressBar, IO::Prompter, Term::ANSIColor, etc to make the
output and interactivity as user-friendly as a Perl script can
possibly be.

For the "cron (etc.)" scripts make them silent, or use Log::Log4perl
or similar to log to a file. However consider also providing a "run by
a person" mode (via a --verbose or --debug flag) where it gives good
output to the terminal too. You'll use it one day :-)


- Alex


More information about the london.pm mailing list