MODULE 7 · WORKING WITH TEXT · 1/8

Text in a fixed-width world

10 min10 XPQuiz

Most languages have a string type that grows and shrinks. COBOL does not. A text field is a PIC X(n) item: exactly n bytes, always. Everything in this module is about working inside that constraint.

Padding and truncation

       IDENTIFICATION DIVISION.
       PROGRAM-ID. PADDING.
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  WS-CODE      PIC X(6).
       01  WS-SHORT     PIC X(3).
       PROCEDURE DIVISION.
           MOVE "AB" TO WS-CODE
           DISPLAY "[" WS-CODE "]"
           MOVE WS-CODE TO WS-SHORT
           DISPLAY "[" WS-SHORT "]"
           IF WS-CODE = "AB"
               DISPLAY "EQUAL"
           END-IF
           STOP RUN.

Output:

[AB    ]
[AB ]
EQUAL

A short value is padded with spaces on the right; a long one is cut off on the right. When two alphanumeric values of different lengths are compared, the shorter is padded with spaces, so "AB " equals "AB". Trailing spaces are normally invisible to your logic, but they are always there, and they matter when you glue fields together or count characters.

Why fixed width?

COBOL grew up with punched cards and tape: 80-column cards, fixed-length records. A record layout such as

       01  CUSTOMER-REC.
           05  CUST-ID        PIC X(6).
           05  CUST-NAME      PIC X(20).
           05  CUST-CITY      PIC X(15).

says that the city is always bytes 27 to 41. No program ever has to search for it. That is fast, simple and very hard to get wrong, which is why banks still exchange files this way.

The trouble starts at the edges of the system: web forms, spreadsheets and partner feeds send you delimited text, such as C00042,Grace Hopper,Arlington. Your COBOL program has to turn that into fixed-width fields (and sometimes back again).

Your toolkit

Tool What it does
Reference modification X(start:len) Look at or change part of a field
STRING Join pieces into one field
UNSTRING Split one field into pieces
INSPECT Count, replace or translate characters
FUNCTION TRIM, UPPER-CASE, ... Return a transformed copy of a value
FUNCTION NUMVAL, NUMVAL-C Turn text like "1,234.50" into a number

The next lessons take these one at a time, then combine them to parse and validate a customer feed.

On the job

A large share of real COBOL maintenance is interface work: a new partner sends a CSV file, and someone has to write the program that validates it and loads it into the fixed-width master file. The tools in this module are exactly what that job needs.

Check your understanding

1. WS-CODE is PIC X(6). After MOVE "AB" TO WS-CODE, what does it hold?
2. WS-CODE (PIC X(6)) holds "AB ". Is the condition WS-CODE = "AB" true?
3. Why do mainframe files use fixed-width fields rather than delimited text?