Reading — step 1 of 5
Learn
REDEFINES lets two data items occupy the SAME memory. Useful for parsing fixed-width records that have different shapes.
01 RECORD-IN.
05 REC-TYPE PIC X.
05 REC-DATA PIC X(100).
05 PERSON-DATA REDEFINES REC-DATA.
10 P-NAME PIC X(30).
10 P-AGE PIC 9(3).
10 P-FILLER PIC X(67).
05 ORDER-DATA REDEFINES REC-DATA.
10 O-ID PIC X(10).
10 O-AMOUNT PIC 9(7)V99.
10 O-FILLER PIC X(81).
The same 100 bytes (REC-DATA) are interpreted three ways:
- As raw text
- As a person record (name + age)
- As an order record (ID + amount)
You pick the interpretation based on REC-TYPE:
PROCEDURE DIVISION.
READ INPUT-FILE INTO RECORD-IN
IF REC-TYPE = "P" THEN
DISPLAY "Person: ", P-NAME
ELSE IF REC-TYPE = "O" THEN
DISPLAY "Order: ", O-ID
END-IF.
Equivalent to a C union — but more declarative.
COMP / COMP-3 / BINARY — different storage formats:
PIC 9(5)— display (1 byte per digit, 5 bytes total)PIC 9(5) COMP— binary (4 bytes for an int)PIC 9(5) COMP-3— packed decimal (3 bytes; 2 digits per byte + sign nibble)
Mainframe data files often use COMP-3 to save space. REDEFINES + COMP-3 lets you parse them.
Implicit decimal point with V:
01 PRICE PIC 9(5)V99 COMP-3.
Stores 7 digits with 2 implied decimals — e.g., the value 12345.67 is stored as bytes 12 34 56 7+.
PIC editing characters for output formatting:
01 DISPLAY-PRICE PIC $$$,$$9.99.
MOVE PRICE TO DISPLAY-PRICE.
DISPLAY DISPLAY-PRICE. *> $1,234.56
Z— zero suppress*— fill with asterisks$— currency,.— separators+-— sign
This is COBOL's killer reporting feature — built-in formatting templates that financial reports rely on.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…