[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

plan9 style arg parse module



as a counter to the sysV style getopt, in the
style of alef's Arg interface...

(out of interest, how efficient is the idiom :
	str = str[1:];
  anyway ?)

    rog.


# begin arg.m

Arg : module
{
	PATH : con "/dis/arg.dis";

	init : fn(argv : list of string);
	arg : fn() : string;
	opt : fn() : int;

	progname : fn() : string;
	argv : fn() : list of string;
};

# begin arg.b

implement Arg;

include "arg.m";

name 		: string;
args 		: list of string;

curropt		: string;

init(argv : list of string)
{
	if (argv == nil) {
		return;
	}

	name = hd argv;
	args = tl argv;
}

progname() : string
{
	return name;
}

argv() : list of string
# don't allow any more options after this
# function is invoked
{
	ret := args;
	args = nil;
	return ret;
}

arg() : string
# get next option argument
{
	if (curropt != "") {
		ret := curropt;
		curropt = nil;
		return ret;
	}

	if (args == nil)
		return nil;

	ret := hd args;
	if (ret[0] == '-')
		ret = nil;
	else
		args = tl args;
	return ret;
}

opt() : int
# get next option letter
# return 0 at end of options
{
	if (curropt != "") {
		opt := curropt[0];
		curropt = curropt[1:];
		return opt;
	}

	if (args == nil) {
		return 0;
	}

	nextarg := hd args;
	if (nextarg[0] != '-' || len nextarg < 2)
		return 0;

	if (nextarg == "--") {
		args = tl args;
		return 0;
	}

	opt := nextarg[1];
	if (len nextarg > 2)
		curropt = nextarg[2:];
	args = tl args;
	return opt;
}