Range Over Channels in COBOL

In a previous example, we saw how loops provide iteration over basic data structures. COBOL doesn’t have built-in channel concepts like some modern languages, but we can simulate similar behavior using file handling for inter-program communication. Here’s an example that demonstrates reading from a sequential file, which is somewhat analogous to receiving values from a channel.

IDENTIFICATION DIVISION.
PROGRAM-ID. RANGE-OVER-FILE.

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
    SELECT QUEUE-FILE ASSIGN TO "queue.txt"
        ORGANIZATION IS LINE SEQUENTIAL.

DATA DIVISION.
FILE SECTION.
FD QUEUE-FILE.
01 QUEUE-RECORD.
    05 QUEUE-ITEM PIC X(20).

WORKING-STORAGE SECTION.
01 WS-EOF PIC A(1).

PROCEDURE DIVISION.
MAIN-PROCEDURE.
    OPEN INPUT QUEUE-FILE
    PERFORM READ-QUEUE UNTIL WS-EOF = 'Y'
    CLOSE QUEUE-FILE
    STOP RUN.

READ-QUEUE.
    READ QUEUE-FILE
        AT END
            MOVE 'Y' TO WS-EOF
        NOT AT END
            DISPLAY QUEUE-ITEM
    END-READ.

This COBOL program simulates iterating over values received from a “channel” by reading from a sequential file named “queue.txt”. The file is expected to contain the values we want to process, one per line.

To run the program:

$ cobc -x range-over-file.cob
$ ./range-over-file
one
two

Before running the program, you need to create a file named “queue.txt” with the following content:

one
two

This example demonstrates reading from a file until it reaches the end, which is analogous to receiving values from a channel until it’s closed. While COBOL doesn’t have built-in channel concepts, file handling can be used for similar purposes in inter-program communication scenarios.