Option Handling in Perl

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 ();
Getopt::Long::Configure('pass_through');

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.

Comments are closed.