Getopt module usage
The getopt.4gl module provides command line argument processing.
Features of getopt.4gl
The getopt.4gl module implements types, functions and methods to process command line arguments in a standard way.
Use this library to implement arguments processing, and provide a common command line option syntax for all your programs.
The options can be defined with a short name (like -c) and a long name (like
--compare).
Partial option specification is supported. For example if --compare is defined,
a command line argument --comp will match --compare. If the
partial option matches several long option names, the error "ambiguous match" is displayed.
--option-name=option-value
form:$ fglrun myprog --verbose --level=5If an argument on the command line is in the form @filename,
options will be read from the file:
$ fglrun myprog @myoptions
$ fglrun myprog capture --verbose --filename=file1
$ fglrun myprog duplicate --source=file1 --destination=file2$ fglrun myprog capture --verbose file1 file2 file3Steps to implement arguments processing
getopt, do the following steps:- Import the
getoptmodule:IMPORT FGL getopt - Define a variable with the
Getopttype:DEFINE g getopt.Getopt - Define a variable with the
GetoptOptionstype that will contain the definition of the options (fill this array of options with a variable initializer):DEFINE _options getopt.GetoptOptions = [(name: "version", description: "Version information", opt_char: 'v', arg_type: getopt.NONE), ... - Initialize the
Getoptvariable with theinitialize()orinitDefault()method, passing the GetoptOptions array as parameter:
If needed, use theCALL g.initialize("myprog", getopt.copyArguments(2), _options)copyArguments(index)function, to provide the second parameter of theinitialize()method, to start command line argument parsing at a given index. - Use the
getopt()method in aWHILEloop, to process all command line arguments that correspond to an option definition:
Additionally, theWHILE g.getOpt() == getopt.SUCCESS CASE g.opt_char WHEN 'v' DISPLAY "Version 1.50" EXIT PROGRAM 0 WHEN 'h' CALL g.displayUsage("file ...") EXIT PROGRAM 0 WHEN 'o' LET outfile = g.opt_arg END CASE END WHILEisEof()method can be used to check if all possible options are processed. - After the
WHILEloop, check for the processing status with the methodsinvalidOptionSeen()orisSuccess():IF g.invalidOptionSeen() THEN CALL g.displayUsage("file ...") EXIT PROGRAM 1 END IF - If additional arguments are possible, use the
getMoreArgumentCount()andgetMoreArgument()methods, to process these non-option arguments:LET cnt = g.getMoreArgumentCount() IF cnt == 0 THEN DISPLAY "ERROR: No files were provided..." EXIT PROGRAM 1 ELSE FOR ind = 1 TO cnt DISPLAY SFMT("File to process: %1", g.getMoreArgument(ind)) END FOR END IF
For a complete example, see getopt().