include "arg.m"; arg := load Arg Arg->PATH; init: fn(argv: list of string); setusage: fn(s: string); usage: fn(); progname: fn(): string; opt: fn(): int; arg: fn(): string; earg: fn(): string; argv: fn(): list of string;
Arg takes the first argument to be the program name. Subsequent calls to progname return it.
Options are arguments containing one or more letters preceded by - (dash, hyphen, minus). The list of options ends before the first argument that does not begin with a -. Option lists also end after an argument --, to allow programs to accept arguments that would otherwise look like options (eg, file names for rm(1) or a pattern for grep(1)). Finally, option lists end before an argument -, which is traditionally interpreted by some commands as referring to the standard input or output (depending on context).
Successive calls to opt return option characters in turn; 0 is returned at the end of the list. A program might take a parameter to a given option (eg, an option of the form -ffile or -f file). Following a call to opt, a call to arg will return the rest of the current argument string if not empty, failing that, the next argument string if any, and otherwise nil. Earg is like arg except that if there is no argument associated with the option, an error message is printed to standard error, and a "fail:usage" exception raised. Setusage sets the error message that will be printed in this case (preceded by `usage:' and followed by a newline).
The argument list remaining after the last call to opt is returned by argv.
implement Prog; include "sys.m"; sys: Sys; include "draw.m"; include "arg.m"; arg: Arg; Prog: module { init: fn(nil: ref Draw->Context, nil: list of string); }; init(nil: ref Draw->Context, args: list of string) { sys = load Sys Sys->PATH; arg = load Arg Arg->PATH; bflag := cflag := 0; file := ""; arg->init(args); while((c := arg->opt()) != 0) case c { 'b' => bflag = 1; 'c' => cflag = 1; 'f' => file = arg->arg(); * => sys->print("unknown option (%c)\n", c); } args = arg->argv(); sys->print("%s %d %d %s\n", arg->progname(), bflag, cflag, file); for(; args != nil; args = tl args) sys->print("%s\n", hd args); }
When invoked as follows:
the output is:
prog 1 1 file a b c
and when invoked by:
the output is:
unknown option (z) ./prog 1 0 file -bc
ARG(2 ) | Rev: Tue Mar 31 02:42:39 GMT 2015 |