cobol

Removing trailing space in COBOL


I'm trying to autogenerate some COBOL code.

       IDENTIFICATION DIVISION.
       PROGRAM-ID. Generator.
       AUTHOR. Scimitaria.

       ENVIRONMENT DIVISION.
       INPUT-OUTPUT SECTION.
       FILE-CONTROL.
       SELECT dumb ASSIGN TO "dumb.cbl"
           ORGANIZATION IS LINE SEQUENTIAL.

       DATA DIVISION.
       FILE SECTION.
       FD dumb.
       01 lineText PIC X(180).
       WORKING-STORAGE SECTION.
       01 Arg    PIC X(18).
       01 num    PIC 9(18).
       01 idx    PIC 9(18).
       01 idx-text PIC Z(18).
       01 isEven PIC X(4)  VALUE "odd".
       01 toggle PIC S9    VALUE 1.
       01 minus-one PIC S9 VALUE -1.

       PROCEDURE DIVISION.
      *Clear file
           OPEN OUTPUT dumb.
           CLOSE dumb.     
      *Prep file for appending
           OPEN EXTEND dumb.
           ACCEPT Arg FROM COMMAND-LINE.
           UNSTRING Arg DELIMITED BY SPACE INTO Num.

      *Generate isEvenOrOdd
           PERFORM VARYING idx FROM 1 BY 1 UNTIL idx > num
             *>convert index to string
             MOVE idx TO idx-text

             IF toggle = 1
               MOVE "odd" TO isEven
             ELSE
               MOVE "even" TO isEven
             END-IF

             MULTIPLY toggle BY minus-one GIVING toggle

             STRING
               "             WHEN " DELIMITED BY SIZE
               FUNCTION TRIM(idx-text) DELIMITED BY SPACE
               " DISPLAY """        DELIMITED BY SIZE
               FUNCTION TRIM(idx-text) DELIMITED BY SPACE
               " is "               DELIMITED BY SIZE
               isEven               DELIMITED BY SIZE
               """"                 DELIMITED BY SIZE
               INTO lineText
            WRITE lineText
           END-PERFORM.

      *Close off
           CLOSE dumb.
           STOP RUN.

This results in the output:

             WHEN 1 DISPLAY "1 is odd "
             WHEN 2 DISPLAY "2 is even"
             WHEN 3 DISPLAY "3 is odd "
             WHEN 4 DISPLAY "4 is even"
             WHEN 5 DISPLAY "5 is odd "
             WHEN 6 DISPLAY "6 is even"
             WHEN 7 DISPLAY "7 is odd "
             WHEN 8 DISPLAY "8 is even"
             WHEN 9 DISPLAY "9 is odd "
             WHEN 10 DISPLAY "10 is even"

I'm having an unreasonably difficult time getting rid of those trailing spaces in the odd lines. I've tried:

FUNCTION TRIM(isEven) DELIMITED BY SPACE

but that changes the space to a quote, which opens up a whole other can of worms. I also tried trimming the spaces manually with a PERFORM-VARYING loop, but couldn't get it to work.


Solution

  • I solved it. In the IF block:

                 IF toggle = 1
                   MOVE " odd'" TO isEven
                   MOVE isEven(2:4) TO isEven
                 ELSE
                   MOVE "even'" TO isEven
                 END-IF