The following simple utility function is used by some of the examples
to parse the arguments to a REXX program that is run from a shell.
This function parses the stem
__argv for options
in the format used by most POSIX commands.
/*********************************************************************/
/* Function: getopts */
/* This function parses __argv. stem for options in the format */
/* used by most POSIX commands. This supports simple option */
/* letters and option letters followed by a single parameter. */
/* The stem OPT. is setup with the parsed information. The */
/* options letter in appropriate case is used to access the */
/* variable: op='a'; if opt.op=1 then say 'option a found' */
/* or, if it has a parameter: */
/* op='a'; if opt.op<>' then say 'option a has value' opt.op */
/* */
/* Parameters: option letters taking no parms */
/* option letters taking 1 parm */
/* */
/* Returns: index to the first element of __argv. that is not */
/* an option. This is usually the first of a list of files.*/
/* A value of 0 means there was an error in the options and */
/* a message was issued. */
/* */
/* Usage: This function must be included in the source for the exec */
/* */
/* Example: the following code segment will call GETOPTS to parse */
/* the arguments for options a, b, c, and d. Options a */
/* and b are simple letter options and c and d each take */
/* one argument. It will then display what options were */
/* specified and their values. If a list of files is */
/* specified after the options, they will be listed. */
/* */
/* parse value 'a b c d' with, */
/* lca lcb lcc lcd . */
/* argx=getopts('ab','cd') */
/* if argx=0 then exit 1 */
/* if opt.0=0 then */
/* say 'No options were specified' */
/* else */
/* do */
/* if opt.lca<>' then say 'Option a was specified' */
/* if opt.lcb<>' then say 'Option b was specified' */
/* if opt.lcc<>' then say 'Option c was specified as' opt.lcc */
/* if opt.lcd<>' then say 'Option d was specified as' opt.lcd */
/* end */
/* if __argv.0>=argx then */
/* say 'Files were specified:' */
/* else */
/* say 'Files were not specified' */
/* do i=argx to __argv.0 */
/* say __argv.i */
/* end */
/* */
/*********************************************************************/
getopts: procedure expose opt. __argv.
parse arg arg0,arg1
argc=__argv.0
opt.='
opt.0=0
optn=0
do i=2 to argc
if substr(__argv.i,1,1)<>'-' then leave
if __argv.i='-' then leave
opt=substr(__argv.i,2)
do j=1 to length(opt)
op=substr(opt,j,1)
if pos(op,arg0)>0 then
do
opt.op=1
optn=optn+1
end
else
if pos(op,arg1)>0 then
do
if substr(opt,j+1)<>' then
do
opt.op=substr(opt,j+1)
j=length(opt)
end
else
do
i=i+1
if i>argc then
do
say 'Option' op 'requires an argument'
return 0
end
opt.op=__argv.i
end
optn=optn+1
end
else
do
say 'Invalid option =' op
say 'Valid options are:' arg0 arg1
return 0
end
end
end
opt.0=optn
return i