Getopt
http://www.eleves.ens.fr/home/frisch/soft#Getopt
インストール
make all allopt make install
findlibをあらかじめインストールしておくこと.
使い方
let filename = ref (None: string option) let specs = [ ('f', "file", None, Some (fun x -> filename := Some x))] let params = ref ([]: string list) let appendd list s = begin list := (!list)@[s]; end let _ = begin Getopt.parse_cmdline specs (appendd params); print_endline (match !filename with None -> "nofile" | Some x -> x); List.iter print_endline !params; end
とか書く.
$ ocamlfind ocamlc -packages getopt -linkpkg -o example example.ml $ ./example nofile $ ./example -f abc abc $ ./example --file=foobar foobar $ ./example 1 2 3 nofile 1 2 3 $ ./example -a bc Fatal error: exception Getopt.Error("Unknown option -a") $ ./example 1 2 3 -a bcd Fatal error: exception Getopt.Error("Unknown option -a")
こんな感じ.
specは,
一文字のオプション×長いオプション名×デフォルトの動作:None×指定ありの場合の関数:(string -> string option) option
になっている.オプションが指定されなかった場合は,指定なしの場合の値になり,指定されていた場合は指定ありの場合の関数が呼ばれる.この関数には,Getopt.setとかのユーティリティ関数が使えて便利.
Getopt.parse_cmdlineの二つ目のオプションは,オプション指定以外のコマンドライン引数を処理する関数.例では,appenddとして,param : ref (string list)にパラメータを一つずつ登録していくようにした.
不正なオプションが指定された場合は,例外が投げられるので,適当に拾ってやる必要がある.