ARG(2) ARG(2) NAME arg - parse program arguments SYNOPSIS 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; DESCRIPTION Arg parses a program's argument list in a traditional form, as received from a shell or other program (see command(2)). The list must be passed to init to set the state for the other functions. Arg takes the first argument to be the program name. Subse- quent calls to progname return it. Options are arguments containing one or more letters pre- ceded 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 pro- grams 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. Page 1 Plan 9 (printed 11/27/24) ARG(2) ARG(2) EXAMPLE The following Limbo program takes options b, c and f, where f takes a file name argument. 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); arg->setusage("prog [-bc] [-f file] args ..."); while((c := arg->opt()) != 0) case c { 'b' => bflag = 1; 'c' => cflag = 1; 'f' => file = arg->earg(); * => sys->print("unknown option (%c)\n", c); arg->usage(); } 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: prog -bc -ffile a b c the output is: prog 1 1 file a b c and when invoked by: Page 2 Plan 9 (printed 11/27/24) ARG(2) ARG(2) ./prog -b -f file -z -- -bc the output is: unknown option (z) ./prog 1 0 file -bc SOURCE /appl/lib/arg.b SEE ALSO sh(1), mash(1), command(2) Page 3 Plan 9 (printed 11/27/24)