Master Mainframe Technologies - COBOL, JCL, DB2, VSAM, CICS & More
ABEND Codes SQLCODEs File Status Interview Prep Contact
💻 COBOL

COBOL Reference Modification

Intermediate 🕑 10 min read 👁 0 views

COBOL Reference Modification

Reference modification allows accessing a substring of a data item using position and length.

Syntax

identifier(start-position:length)
  • start-position: 1-based starting position
  • length: Number of characters (optional)

Example Program

       IDENTIFICATION DIVISION.
       PROGRAM-ID. REFMOD-DEMO.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 WS-STRING      PIC X(20) VALUE 'HELLO WORLD COBOL'.
       01 WS-RESULT      PIC X(10).
       01 WS-DATE        PIC X(10) VALUE '2024-01-15'.
       01 WS-YEAR        PIC X(4).
       01 WS-MONTH       PIC X(2).
       01 WS-DAY         PIC X(2).
       01 WS-POS         PIC 99 VALUE 1.
       01 WS-LEN         PIC 99 VALUE 5.

       PROCEDURE DIVISION.
      * Extract substring
           MOVE WS-STRING(1:5) TO WS-RESULT
           DISPLAY 'First 5 chars: ' WS-RESULT

           MOVE WS-STRING(7:5) TO WS-RESULT
           DISPLAY 'Chars 7-11: ' WS-RESULT

      * Variable position and length
           MOVE WS-STRING(WS-POS:WS-LEN) TO WS-RESULT
           DISPLAY 'Dynamic extract: ' WS-RESULT

      * Parse date
           MOVE WS-DATE(1:4) TO WS-YEAR
           MOVE WS-DATE(6:2) TO WS-MONTH
           MOVE WS-DATE(9:2) TO WS-DAY
           DISPLAY 'Year: ' WS-YEAR
           DISPLAY 'Month: ' WS-MONTH
           DISPLAY 'Day: ' WS-DAY

      * Modify substring in place
           MOVE 'GOODBYE' TO WS-STRING(1:7)
           DISPLAY 'Modified: ' WS-STRING

      * Without length (to end of field)
           MOVE WS-STRING(9:) TO WS-RESULT
           DISPLAY 'From pos 9: ' WS-RESULT

           STOP RUN.

Expected Output

First 5 chars: HELLO
Chars 7-11: WORLD
Dynamic extract: HELLO
Year: 2024
Month: 01
Day: 15
Modified: GOODBYE WORLD COBOL
From pos 9: RLD COBOL

Key Points

  • Position starts at 1, not 0
  • Length is optional (defaults to end)
  • Can use variables for position/length
  • Can modify substring in place
  • Works with group and elementary items