Option Handling and Moose

May 28, 2008

Further to my previous post on option handling in Perl. There is a rather useful Moose extension named MooseX::Getopt which allows the building of an object directly from a set of command line options. The class attributes are directly translated into an option profile for Getopt::Long. Here’s a simple example class:

package LCFG::Foo;
use Moose;

with 'MooseX::Getopt';

has 'logname' => ( is => 'rw', isa => 'Str' );

has 'quiet' => ( is => 'rw', isa => 'Bool', default => 0 );

no Moose;

In the script you can then just do:

use strict;
use warnings;

use LCFG::Foo;

my $foo = LCFG::Foo->new_with_options();

if ( !$foo->quiet) {
   print $foo->logname . "\n";

The script can then be called like:

my_script.pl --logname Changes --quiet

Option Handling in Perl

May 28, 2008

I’ve often used the Perl module Getopt::Long to handle options for scripts. This time I wanted something a bit more complex, I was aiming for something akin to the command-line interface to cvs. Basically, there are options which apply globally then a command and then command specific options. e.g.

lcfg-reltool --quiet --dir dice/lcfg-foo release --checkcommitted --genchangelog

Normally Getopt::Long expects to handle the whole argument list and will throw an error when it sees unknown options. I discovered that it is possible to configure it instead to pass-through any unknown options.

use Getopt::Long ();

my $dir = '.';
my $quiet = 0;
Getopt::Long::GetOptions( 'dir=s' => \$dir,
                                       'quiet' => \$quiet);

Getopt::Long::Configure('no_pass_through'); # revert to normal behaviour

All matched options will be removed from the @ARGV list and it is then possible to call Getopt::Long for a second time with a command-specific option profile.