Figure 16-2 and Figure 16-3 demonstrate how to use the parse-arguments library in a simple application.
Figure 16-2. Library declaration for a sample application using parse-arguments.
Module: dylan-user define library sample-application use dylan; use format-out; use parse-arguments; end library; define module sample-application use dylan; use extensions; use format-out; use parse-arguments; end module;
Figure 16-3. Source code for a sample application using
parse-arguments, making use of the define argument-parser
macro.
Module: sample-application define argument-parser <sample-parser> () option verbose?, long: "verbose", short: "v"; option logfile, kind: <parameter-option-parser>, long: "logfile", short: "L"; regular-arguments file-names; end; define method main(program-name :: <string>, #rest arguments) let parser = make(<sample-parser>); unless (parse-arguments(parser, arguments)) format-out("Usage: %s [-v] [-Llogfile] files...\n", program-name); exit(exit-code: 1); end; // Body of program. end;
In Figure 16-3, the
variable parser.verbose?
will be set to #t
if
either --verbose or -v appears
on the command line. Otherwise, it will be set to
#f
. Similarly, if -Lfilename or
--logfile=filename appears on the command line,
the variable parser.logfile
will be set the string
"filename". Otherwise, it too will be set to
#f
.
Any other arguments will be collected and placed in the
variable parser.file-names
.
Figure 16-4 shows
how to use the Parse-Arguments
library
without using the define argument-parser
macro. Here the various arguments are added manually, and
accessed using the option-value-by-long-name
method.
Figure 16-4. Source code for a sample application using parse-arguments.
Module: sample-application define method main(program-name :: <string>, #rest arguments) let parser = make(<argument-list-parser>); add-option-parser-by-type(parser, <simple-option-parser>, long-options: #("verbose"), short-options: #("v")); add-option-parser-by-type(parser, <parameter-option-parser>, long-options: #("logfile"), short-options: #("L")); unless (parse-arguments(parser, arguments)) format-out("Usage: sample-application [-v] [-Llogfile] files...\n"); exit(exit-code: 1); end; let verbose? = option-value-by-long-name(parser, "verbose"); let logfile = option-value-by-long-name(parser, "logfile"); let file-names = parser.regular-arguments; // Body of program. end;
Using the define argument-parser
is the
preferred way of using the Parse-Arguments
library. It is both more convenient and better readable. The
manual way is documented both for users of Mindy, which doesn't
have macro capabilities, and for advanced users who wish to
extend the functionality of the option parsers.