|Syntactic Confectionery Delight|
Getopt::Declareby danger (Priest)
|on Feb 02, 2001 at 22:25 UTC ( #56048=modulereview: print w/replies, xml )||Need Help??|
Item Description: Declarative command line argument parser
Getopt::Declare A quickie overview.
Getopt::Declare is a module for parsing command line options -- and like many of Damian Conway's modules, this one has obviously been eating its wheaties with large doses of steroids (and it arrives with circa 1,500 lines of documentation to prove it). In short, this is not your mother's command line parser.
Not satisfied with giving us yet another command line parser, Damian has given us a declarative language to specify not only command line options, but descriptions, parameter types, and actions as well. But don't let the size of the docs intimidate you, it is surprisingly simple to use.
The basic mechanics of using the module are as follows:
Obviously, it is the specification we are really interested in. So let's look a very trivial greplike script using the module:
An option declaration is comprised of a few components: the option specification itself (followed by one or more tabs); the option description (with optional directives); and an optional action block to be executed if the option is found. Let's break out the -f option above and look at each component:
The option variable is available as a lexical variable within the action block, and you may set or access any globals that are available at the time of parsing. In our example above we set the global $re and $not variables in the action blocks so we can access those later rather than accessing those options via the $opts object. We deferred our file processing action because we want to ensure all options have been parsed (and all globals set) before we start grepping our files.
You can also restrict parameter types when specifying parameter variables using a few predefined parameter types:
And, because this is Perl, you can also specify your own regex to limit the types of things a parameter should accept or define new types:
This module also gives us a -help option for free, and a -v option (if you've defined a $VERSION variable). Here's what we get with those:
And, with 1,500 lines of documentation I've clearly only scratched the surface in this little overview. Go ahead and grab it, read the docs, and play around (and, if you're feeling brave, read the code too).