manpagez: man pages & more
info guile
Home | html | info | man
[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.4.1 A Short getopt-long Example

This section illustrates how getopt-long is used by presenting and dissecting a simple example. The first thing that we need is an option specification that tells getopt-long how to parse the command line. This specification is an association list with the long option name as the key. Here is how such a specification might look:

(define option-spec
  '((version (single-char #\v) (value #f))
    (help    (single-char #\h) (value #f))))

This alist tells getopt-long that it should accept two long options, called version and help, and that these options can also be selected by the single-letter abbreviations v and h, respectively. The (value #f) clauses indicate that neither of the options accepts a value.

With this specification we can use getopt-long to parse a given command line:

(define options (getopt-long (command-line) option-spec))

After this call, options contains the parsed command line and is ready to be examined by option-ref. option-ref is called like this:

(option-ref options 'help #f)

It expects the parsed command line, a symbol indicating the option to examine, and a default value. The default value is returned if the option was not present in the command line, or if the option was present but without a value; otherwise the value from the command line is returned. Usually option-ref is called once for each possible option that a script supports.

The following example shows a main program which puts all this together to parse its command line and figure out what the user wanted.

(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)))))

[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

This document was generated on April 20, 2013 using texi2html 5.0.

© manpagez.com 2000-2024
Individual documents may contain additional copyright information.