Is there a way to use INSPECT TALLYING with a check for multiple characters?

ikartik90 picture ikartik90 · Jan 8, 2013 · Viewed 18.1k times · Source

I have a string for which I wish to tally the count of characters till a certain pattern of characters is found.

For example:

Give a string: askabanskarkartikrockstar
I would like to know how many characters are there before the kartik in the string.

In a normal scenario where I need to find the number of characters before, say k, in the given string, I would write the code somewhat as:

INSPECT WS-INPUT-STRING TALLYING CT-COUNTER FOR CHARACTERS BEFORE LT-K

Where

  • WS-INPUT-STRING is alphanumeric with a value of askabanskarkartikrockstar,
  • CT-COUNTER is the counter used to count the number of characters
  • LT-K is a literal with the value k.

But here, if I wish to do the same for a sub-string, like kartik in the above example, would replacing the value of LT-K with kartik instead of just k work? If yes, is the same applicable for alphanumeric literals that have values in the form of hexadecimal numbers (for example, in a literal X(02) one stores a new-line character as x'0D25')?

I'm trying to implement the above code in zOS IBM mainframe v10. Thanks.

Answer

NealB picture NealB · Jan 8, 2013

You have pretty much answered your own question... The answer is yes you can do this. Here is a working example program:

  IDENTIFICATION DIVISION.
  PROGRAM-ID. EXAMPLE.
  DATA DIVISION.
  WORKING-STORAGE SECTION.
  01    WS-INPUT-STRING PIC X(80).
  01    WS-COUNTER      PIC 9(4).
  01    WS-TAG          PIC X(10).
  PROCEDURE DIVISION.
  MAIN-PARAGRAPH.
       MOVE 'askabanskarkartikrockstar' TO WS-INPUT-STRING
       MOVE ZERO                        TO WS-COUNTER
       MOVE 'kartik'                    TO WS-TAG
       INSPECT WS-INPUT-STRING
       TALLYING WS-COUNTER
       FOR CHARACTERS BEFORE WS-TAG(1:6)
       DISPLAY WS-COUNTER
       GOBACK
       .

WS-COUNTER displays as 11, there are 11 characters before the WS-TAG string.

Notice that I defined WS-TAG as PIC X(10). This variable is longer than the actual tag value you are looking for. To prevent the INSPECT verb from trying to match on trailing spaces introduced by:

      MOVE 'kartik' TO WS-TAG

I had to specify a reference modified value for INSPECT to search for. Had I simply used:

      FOR CHARACTERS BEFORE WS-TAG

without reference modification, WS-COUNTER would have been 80 - the length of WS-INPUT-STRING. This is because the string 'kartik ' is not found and the counter tallies the length of the entire input string.

Another approach would be to specify the tag as a literal:

      FOR CHARACTERS BEFORE 'kartik'

You can move hexadecimal constants into PIC X fields as follows:

      MOVE X'0D25' TO WS-TAG

This occupies 2 characters so you would use WS-TAG(1:2) when INSPECTing it.