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 -f file or -f " file" \f1).\f0 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 "\f5fail: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 .
.EX .vs -1 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)\en", c); } args = arg->argv(); sys->print("%s %d %d %s\en", arg->progname(), bflag, cflag, file); for(; args != nil; args = tl args) sys->print("%s\en", hd args); } .vs +1
When invoked as follows:
"prog -bc -ffile a b c"the output is:
.EX prog 1 1 file a b cand when invoked by:
"./prog -b -f file -z -- -bc"the output is:
.EX unknown option (z) ./prog 1 0 file -bc