Easy CLI option parsing with Getopt::Lucid
by bigpresh on Jan.31, 2009, under Perl, Programming, reviews, Uncategorized
I often write Perl scripts which need to read options given on the command line. Normally I turn to the venerable old Getopt::Long which does the job.
However, I was writing a script which needed to be able to accept only certain parameters, which were mostly optional, and also take a list of filenames. I wanted this to be possible in any order, e.g.:
myscript --foo=foo --bar=bar file1 file2 myscript file1 file --foo foo
Getopt::Lucid makes this all pretty easy, and also makes the code pretty self-documenting, too. Straight from the documentation, showing the various types of parameters it can parse:
@specs = ( Switch("version|V"), Counter("verbose|v"), Param("config|C"), List("lib|l|I"), Keypair("define"), Switch("help|h"), ); $opt = Getopt::Lucid->getopt( \@specs ); $verbosity = $opt->get_verbose; @libs = $opt->get_lib; %defs = $opt->get_define;
A real-world example,from one of my scripts which handles ID3-tagging:
# The options we can take - these correspond to the name of the tag that # they'll set: my @options = qw(track title artist album comment); my @option_specs = ( Getopt::Lucid::Switch('verbose|v'), map { Getopt::Lucid::Param($_) } @options, ); my $opt = Getopt::Lucid->getopt(\@option_specs); my @tags_to_set = grep { $opt->{seen}{$_} } @options; my @files = @{ $opt->{target} }; if (!@tags_to_set) { say "Nothing to do. Use one or more of the options:\n" . join ', ', map {'--'.$_} @options; exit; }
(The script then goes on to loop over all files, and use Music::Tag to set the ID3 tags requested).