The INSPECT statement examines and optionally modifies a string in place. You can TALLY (count characters or substrings), REPLACING (replace characters), or CONVERTING (character-by-character mapping). INSPECT is a single statement that does the work of a loop, so it is efficient and readable for cleaning data or counting occurrences.
| Phrase | Meaning |
|---|---|
| TALLYING ... FOR CHARACTERS | Count every character in the string |
| TALLYING ... FOR ALL literal | Count each occurrence of the literal |
| TALLYING ... FOR LEADING literal | Count only leading contiguous occurrences |
| REPLACING ALL a BY b | Replace every occurrence of a with b |
| REPLACING LEADING a BY b | Replace only leading occurrences of a with b |
| REPLACING FIRST a BY b | Replace only the first occurrence of a with b |
| CONVERTING a TO b | Map each character in set a to corresponding character in set b |
INSPECT identifier REPLACING ... changes characters in the string. ALL literal-1 BY literal-2 replaces every occurrence of literal-1 with literal-2 (lengths must match). LEADING affects only the leftmost run of the character; FIRST affects only the first occurrence.
123456789*> Replace every comma with a space MOVE "A,B,C,D" TO WS-TEXT INSPECT WS-TEXT REPLACING ALL "," BY " ". *> WS-TEXT is now "A B C D" *> Replace only leading spaces with zeros MOVE " 123" TO WS-NUM INSPECT WS-NUM REPLACING LEADING " " BY "0". *> WS-NUM is now "0000123"
INSPECT identifier TALLYING counter FOR ... adds a count to the numeric counter field. FOR CHARACTERS counts every character. FOR ALL literal counts how many times the literal appears. FOR LEADING literal counts only the contiguous occurrences at the start. The counter is increased (not set); initialize it to zero first if you want a fresh count.
1234567MOVE ZEROS TO WS-COUNT INSPECT WS-LINE TALLYING WS-COUNT FOR ALL ",". *> WS-COUNT now holds the number of commas in WS-LINE MOVE ZEROS TO WS-LEN INSPECT WS-NAME TALLYING WS-LEN FOR CHARACTERS. *> WS-LEN holds the length of WS-NAME (if WS-NAME is the target)
You can combine both in one INSPECT: first TALLYING is done, then REPLACING. Both operate on the same identifier. Use BEFORE INITIAL or AFTER INITIAL to limit the region (e.g. only before the first period).
12345MOVE ZEROS TO WS-COMMA-COUNT INSPECT WS-BUFFER TALLYING WS-COMMA-COUNT FOR ALL "," REPLACING ALL "," BY " ". *> Count commas and replace them with spaces in one pass
CONVERTING literal-1 TO literal-2 maps each character in literal-1 to the character at the same position in literal-2. So INSPECT WS-TEXT CONVERTING "abc" TO "ABC" converts every 'a' to 'A', every 'b' to 'B', every 'c' to 'C'. Useful for case conversion or simple substitution tables.
1. What does INSPECT ... TALLYING ... FOR ALL "," do?
2. What does REPLACING ALL " " BY "-" do?