MainframeSupports
tip week 43/2010:

I have been coding in COBOL for many years, but until recently I did not have to use the functionality provided by INDEX in PL/I, POS in REXX and POSSTR in SQL. COBOL is equipped with a very limited set of functions and not one of them looks like the mentioned ones. I had to ask more experienced COBOL programmers for help and I was told that INSPECT might do the trick.

The descriptions in the COBOL manual are not famous for readability, so we had to find an example before I could create some usable code. I hope this tip may save you some time compared to the frustrations I had to go through. Just to find out that INSPECT is the COBOL statement that will help is not exactly intuitive. And here is how to do it:

01 needle PIC X(5).
01 haystack PIC X(50).
01 needlePos PIC S9(9) BINARY.

MOVE 'COBOL' TO needle
MOVE 'ITISNOTEASYTOCODEINDEXORPOSORPOSSTRINCOBOLIDOTHINK' TO haystack

MOVE 1 TO needlePos
INSPECT haystack TALLYING needlePos FOR CHARACTERS BEFORE needle

IF needlePos > LENGTH OF haystack
  DISPLAY 'NEEDLE ' needle ' NOT FOUND IN HAYSTACK ' haystack
ELSE
  DISPLAY 'NEEDLE ' needle ' FOUND IN POSITION ' needlePos
END-IF

INSPECT counts the number of bytes before the first occurence of NEEDLE and adds the count to NEEDLEPOS. That is why I start by initializing NEEDLEPOS with 1 before executing the INSPECT statement. If NEEDLE is not found in HAYSTACK then NEEDLEPOS ends up by being the number of bytes in HAYSTACK plus one, very unlike INDEX/POS/POSSTR where NEEDLEPOS would be set to zero. By the way INSPECT is capable of many other things than just scanning strings.

Previous tip in english        Sidste danske tip        Tip list