Friday, February 01, 2008

Scheme For Enlightenment Part Nine - Command Line Parsing

Hello, World is not a real program. Often, real programs have to deal with the command line. Guile has facilities to make this easy. The following allows getopt style command line syntax to be supported. It does so in a way that illustrates how command line parsing may be done.

#!/usr/bin/guile \
-e main -s
!#
(use-modules (ice-9 getopt-long))
(define (main args)
(let* ((option-spec '((version (single-char #\v) (value #f))
(help (single-char #\h) (value #f))))
(options (getopt-long args option-spec))
(help-wanted (option-ref options 'help #f))
(version-wanted (option-ref options 'version #f)))
(if (or version-wanted help-wanted)
(begin
(if version-wanted
(display "getopt-long-example version 0.3\n"))
(if help-wanted
(display "\
getopt-long-example [options]
-v, --version Display version
-h, --help Display this help
")))
(begin
(display "Hello, World!") (newline)))))


The 2nd line uses Guile's -e option to call the function main once Guile reads the script into memory. Scheme has no equivalent to C's main. There is no starting function. But Guile allows one to name one in it's startup with an option. It doesn't need to be called main.

In the 6th line, option-spec is defined. It defines two command line options, version and help, with single character short cuts that do not take option arguments. If version is given, the version 0.3 message is displayed. If help is given, a usage list is displayed. If neither option is given, the usual Hello, World! message is displayed. This can be used as a template for more complex scripts.

Line 8 actually calls getopt-long to do the parsing. The parameter args is a list of strings from the command line, provided by Guile, starting with argv[0].

Note that another way to display newlines is embodied in this example. In the bit where it displays help, the newlines are inserted into the string literally. Apparently strings in Guile can span multiple lines. No line continuations are needed, as is C.

This essentially trivial program is 22 lines long. While Scheme is touted as being terse and concise, it appears that when it needs to deal with the real world, it can be as verbose as the best of languages.

No comments: