Paragraphs, sections and PERFORM
So far your programs have been one long list of statements. Real COBOL
programs run to thousands of lines, so the PROCEDURE DIVISION is split into
named blocks called paragraphs, and you run them with PERFORM.
Paragraphs
A paragraph is a name in Area A (column 8) followed by a full stop. It contains every sentence from there until the next paragraph name.
IDENTIFICATION DIVISION.
PROGRAM-ID. PARAS.
PROCEDURE DIVISION.
0000-MAIN.
DISPLAY "START"
PERFORM 1000-GREET
PERFORM 1000-GREET
DISPLAY "END"
STOP RUN.
1000-GREET.
DISPLAY "HELLO FROM 1000-GREET".
Output:
START
HELLO FROM 1000-GREET
HELLO FROM 1000-GREET
END
This is an out-of-line PERFORM: control jumps to the paragraph, runs it,
and comes back to the statement after the PERFORM. It works like calling a
function, except there are no parameters or return values: every paragraph
shares the same WORKING-STORAGE.
The number prefix (0000-, 1000-) is a shop convention, not syntax. It
tells a reader where a paragraph sits in the hierarchy and makes it easy to
find in a 5,000-line listing.
Fall-through
COBOL runs paragraphs in source order unless told otherwise. If you forget
STOP RUN, control simply drops into the next paragraph:
0000-MAIN.
DISPLAY "START"
PERFORM 1000-GREET.
1000-GREET.
DISPLAY "HELLO FROM 1000-GREET".
This prints the greeting twice: once from the PERFORM, once by falling
through. That is why the main paragraph always ends with STOP RUN (or
GOBACK).
Sections
A section groups paragraphs. Its header ends with the word SECTION.
Performing a section runs every paragraph in it, then returns:
PROCEDURE DIVISION.
0000-MAIN SECTION.
PERFORM 1000-REPORT
STOP RUN.
1000-REPORT SECTION.
1000-HEADER.
DISPLAY "HEADER".
1000-BODY.
DISPLAY "BODY".
1000-FOOTER.
DISPLAY "FOOTER".
Some shops use sections everywhere, some only paragraphs. Follow whatever the existing program does.
PERFORM THRU and EXIT paragraphs
PERFORM A THRU B runs every paragraph from A down to B in source order.
In older code you will see it paired with an exit paragraph, whose only
statement is EXIT (which does nothing):
0000-MAIN.
PERFORM 2000-VALIDATE THRU 2000-EXIT
DISPLAY "BACK IN MAIN"
STOP RUN.
2000-VALIDATE.
IF WS-AMOUNT < ZERO
DISPLAY "NEGATIVE AMOUNT - REJECTED"
GO TO 2000-EXIT
END-IF
DISPLAY "AMOUNT OK".
2000-EXIT.
EXIT.
With a negative amount this prints NEGATIVE AMOUNT - REJECTED then
BACK IN MAIN. The GO TO 2000-EXIT is an early return: it jumps to the end
of the range, and the PERFORM finishes there.
THRU ranges are fragile
If someone inserts a new paragraph between 2000-VALIDATE and 2000-EXIT,
it silently becomes part of the range. Many modern standards ban THRU
for new code, but you will meet it constantly in maintenance work.
On the job
Shop standards often say "one PERFORM per paragraph, no THRU, no GO TO except to an EXIT paragraph". Read the standards document before your first change. Code reviewers will check it.