- Published on
EXIT-PERFORM
When to use EXIT PERFORM?
1000-COBOL-SEARCH SECTION.
MOVE 'WIDGET' TO WS-SEARCH-VALUE
MOVE 0 TO WS-INDEX
PERFORM 999999999 TIMES *> Endless inline perform
ADD 1 TO WS-INDEX
IF WS-INDEX > WS-ARRAY-SIZE *> Avoid array overflow
DISPLAY "Reached end of array. None found."
EXIT PERFORM *> Exit inline perform
END-IF
IF WS-ARRAY(WS-INDEX) = WS-SEARCH-VALUE *> Search text
DISPLAY "Value found!"
EXIT PERFORM *> Mission accomplished.
END-IF
IF WS-ARRAY(WS-INDEX) = SPACES *> No more values
DISPLAY "Reached end of array values. None found."
EXIT PERFORM *> Exit inline perform
END-IF
END-PERFORM
.
1000-EXIT.
EXIT.
What's the story?
The provided COBOL code executes a sequential search within an array. The search operation terminates under three conditions: when it locates the desired text, encounters an empty array element, or reaches the end of the array.
It's important to note that, as of November 2020, the maximum limit for inline 'PERFORM' statements is set at 999,999,999 iterations.
How about GO TO?
If your workplace doesn't mind using GO TO, here's the algorithm's version with GO TO.
1000-COBOL-SEARCH SECTION.
MOVE 'WIDGET' TO WS-SEARCH-VALUE
MOVE 0 TO WS-INDEX
PERFORM 999999999 TIMES *> Endless inline perform
ADD 1 TO WS-INDEX
IF WS-INDEX > WS-ARRAY-SIZE *> Avoid array overflow
DISPLAY "Reached end of array. None found."
GO TO 1000-EXIT *> Exit section
END-IF
IF WS-ARRAY(WS-INDEX) = WS-SEARCH-VALUE *> Search text
DISPLAY "Value found!" *> Mission accomplished.
GO TO 1000-EXIT *> Exit section
END-IF
IF WS-ARRAY(WS-INDEX) = SPACES *> No more values
DISPLAY "Reached end of array values. None found."
GO TO 1000-EXIT *> Exit section
END-IF
END-PERFORM
.
1000-EXIT.
EXIT.
How about nested IFs?
Sure, we can use nested IFs, but personally, it's not my favorite. I find it more challenging to achieve 100% coverage testing and handle future code revisions, such as adding a few more nested IFs or complex conditions.
1000-COBOL-SEARCH SECTION.
MOVE 'WIDGET' TO WS-SEARCH-VALUE
MOVE 0 TO WS-INDEX
SET END-OF-LOOP TO FALSE
PERFORM UNTIL END-OF-LOOP *> Loop indicator flag
ADD 1 TO WS-INDEX
IF WS-INDEX > WS-ARRAY-SIZE *> Avoid array overflow
DISPLAY "Reached end of array. None found."
SET END-OF-LOOP TO TRUE *> Exit loop
ELSE
IF WS-ARRAY(WS-INDEX) = WS-SEARCH-VALUE *> Search text
DISPLAY "Value found!" *> Mission accomplished.
SET END-OF-LOOP TO TRUE *> Exit loop
ELSE
IF WS-ARRAY(WS-INDEX) = SPACES *> No more values
DISPLAY "Reached end of array values. None found."
SET END-OF-LOOP TO TRUE *> Exit loop
END-IF
END-IF
END-IF
END-PERFORM
.
1000-EXIT.
EXIT.
How about COBOL SEARCH command?
True, you've got me.