Command Line Flags in COBOL

Our program demonstrates the use of command-line arguments in COBOL. Here’s the full source code:

       IDENTIFICATION DIVISION.
       PROGRAM-ID. COMMAND-LINE-FLAGS.
       ENVIRONMENT DIVISION.
       INPUT-OUTPUT SECTION.
       FILE-CONTROL.
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 WS-WORD        PIC X(10) VALUE "foo".
       01 WS-NUMB        PIC 9(5) VALUE 42.
       01 WS-FORK        PIC X VALUE "N".
       01 WS-SVAR        PIC X(10) VALUE "bar".
       01 WS-ARGS        PIC X(100).
       01 WS-ARG         PIC X(20).
       01 WS-ARG-LEN     PIC 99.
       01 WS-I           PIC 99.

       PROCEDURE DIVISION.
       MAIN-PROCEDURE.
           ACCEPT WS-ARGS FROM COMMAND-LINE.
           PERFORM PARSE-ARGS.
           PERFORM DISPLAY-RESULTS.
           STOP RUN.

       PARSE-ARGS.
           PERFORM VARYING WS-I FROM 1 BY 1 
             UNTIL WS-I > FUNCTION LENGTH(WS-ARGS)
               UNSTRING WS-ARGS DELIMITED BY SPACE
                 INTO WS-ARG
                 WITH POINTER WS-I
               END-UNSTRING
               IF WS-ARG(1:6) = "-word=" 
                 MOVE WS-ARG(7:) TO WS-WORD
               END-IF
               IF WS-ARG(1:6) = "-numb=" 
                 MOVE WS-ARG(7:) TO WS-NUMB
               END-IF
               IF WS-ARG = "-fork" 
                 MOVE "Y" TO WS-FORK
               END-IF
               IF WS-ARG(1:6) = "-svar=" 
                 MOVE WS-ARG(7:) TO WS-SVAR
               END-IF
           END-PERFORM.

       DISPLAY-RESULTS.
           DISPLAY "word: " WS-WORD.
           DISPLAY "numb: " WS-NUMB.
           DISPLAY "fork: " WS-FORK.
           DISPLAY "svar: " WS-SVAR.

This COBOL program emulates the behavior of command-line flags. It accepts arguments from the command line and parses them to set values for different variables.

To compile and run the COBOL program:

$ cobc -x command-line-flags.cob
$ ./command-line-flags -word=opt -numb=7 -fork -svar=flag
word: opt
numb: 00007
fork: Y
svar: flag

Note that if you omit flags, they automatically take their default values:

$ ./command-line-flags -word=opt
word: opt
numb: 00042
fork: N
svar: bar

In COBOL, we don’t have a built-in flag parsing mechanism like Go’s flag package. Instead, we manually parse the command-line arguments. This example demonstrates a basic implementation of such parsing.

The program uses the ACCEPT WS-ARGS FROM COMMAND-LINE statement to get all command-line arguments as a single string. It then parses this string in the PARSE-ARGS procedure, checking for specific flag patterns and updating the corresponding variables.

While this implementation is simpler than Go’s flag package, it provides similar functionality for basic command-line argument handling in COBOL programs.