Wednesday 24 March 2010

perl get-options good practices

Rading a recent post at  http://perlbuzz.com/ :
The horrible bug your command line Perl program probably has 

 It talks about the best practice to test always system call return values. But also make a good point that many user forget about to test the result of get-option. If you don't know what get_option is, and you are writing perl scripts for comand line usage, then you are missing a very important tool.


For the record, I am putting here my standard get_option scaffold (I have it as a template in my .emacs)

use Getopt::Long;  

my $prog = $0;
my $usage = <<eoq;
Usage for $0:

  >$prog [-test -help -verbose]

EOQ

my $help;
my $test;
my $debug;
my $verbose =1;
my $log;
my $stdout;
my $ok = GetOptions(
                    'test'      => \$test,
                    'debug:i'   => \$debug,
                    'verbose:i' => \$verbose,
                    'help'      => \$help,
                    'log'       => \$log,
                    'stdout'    => \$stdout,
                   );

if ($help || !$ok ) {
    print $usage;
    exit;
}

I am capturing the return value of the getoptions and printing a 'usage' message if error or help

I encourage you to put this in your editor's perl templates.

2 comments:

oylenshpeegul said...

Instead of a usage string, why not add Pod::Usage? Then your usage statement comes right from your man page.

Pablo Marin-Garcia said...

[to oylenshpeegul] Yes Pod::Usage is nice, the thing is that I want to separate the usage string from the pod (rendering the pod takes time). So I can do 'perl myprogram.pl -h' and find quickly the options for the program.

I heard about it but I have never used it. Reading again now the pod for Pod::Usage I see that with verbosity 0 it prints only the synopsis. I will see if this is fast enough.

Thanks