Method Getopt.find_option()
- Method
find_option
void|string|boolfind_option(array(string|zero)argv,array(string)|stringshortform,array(string)|string|voidlongform,array(string)|string|voidenvvars,string|bool|voiddef,int|voidthrow_errors)- Description
This is a generic function to parse command line options of the type -f, --foo or --foo=bar.
- Parameter
argv The first argument should be the array of strings that was sent as the second argument to your
main()function.- Parameter
shortform The second is a string with the short form of your option. The short form must be only one character long. It can also be an array of strings, in which case any of the options in the array will be accepted.
- Parameter
longform This is an alternative and maybe more readable way to give the same option. If you give
"foo"aslongformyour program will accept --foo as argument. This argument can also be an array of strings, in which case any of the options in the array will be accepted.- Parameter
envvars This argument specifies an environment variable that can be used to specify the same option, to make it easier to customize program usage. It can also be an array of strings, in which case any of the mentioned variables in the array may be used.
- Parameter
def This argument has two functions: It specifies if the option takes an argument or not, and it informs find_option() what to return if the option is not present.
The value may be one of:
int(0)|zeroThe option does not require a value.
int(1)|stringThe option requires a value, and
defwill be returned if the option is not present. If the option is present, but does not have an argument find_option() will fail.Note that a set option will always return a
string, so settingdefto1can be used to detect whether the option is present or not.- Parameter
throw_errors If
throw_errorshas been specified find_option() will throw errors on failure. If it has been left out, or is0(zero), it will instead print an error message on Stdio.stderr and exit the program with result code 1 on failure.- Returns
Returns the value the option has been set to if any.
If the option is present, but has not been set to anything
1will be returned.Otherwise if any of the environment variables specified in
envvarshas been set, that value will be returned.If all else fails,
defwill be returned.- Throws
If an option that requires an argument lacks an argument and
throw_errorsis set an error will be thrown.- Note
find_option() modifies
argv. Parsed options will be removed fromargv. Elements ofargvthat have been removed entirely will be replaced with zeroes.This function reads options even if they are written after the first non-option on the line.
Index
0(zero) ofargvis not scanned for options, since it is reserved for the program name.Only the first ocurrance of an option will be parsed. To parse multiple ocurrances, call find_option() multiple times.
- See also