IBM i (OS400) V5R3 brought what I like to call the Select group of commands, SELECT, WHEN, OTHERWISE, and ENDSELECT. If you are familiar with the Select operation codes in RPG/RPGLE you need little or no introduction to their equivalent in CL. Their introduction has allowed me to write, what I consider to be, better looking and structured code.
Before the Select group of commands I would write some ugly thing like this:
01 IF COND(&FLAG = 'A') THEN(DO) 02 CHGVAR VAR(&STS) VALUE('ACTIVE') 03 GOTO CMDLBL(ENDTEST) 04 ENDDO 05 IF COND(&FLAG = 'I') THEN(DO) 06 CHGVAR VAR(&STS) VALUE('INACTIVE') 07 GOTO CMDLBL(ENDTEST) 08 ENDDO 09 CHGVAR VAR(&STS) VALUE('ERROR') 10 CHGVAR VAR(&ERROR) VALUE('1') 11 ENDTEST:
Line 1 tests if the field &FLAG is ‘A’, if it is then line 2 is executed, and line 3 goes to the label ENDTEST. I have the GOTO as if &FLAG was equal to ‘A’ it does need to execute any of the code before the ENDTEST label. If I did not have the GOTO it would execute the IF at line 5, and I would have had to put another IF statement between lines 8 and 9 too.
Lines 9 and 10 are only executed if &FLAG is not equal or ‘A’ or ‘I’.
With the Select group the same looks like:
01 SELECT 02 WHEN COND(&FLAG = 'A') THEN(+ 03 CHGVAR VAR(&STS) VALUE('ACTIVE')) 04 WHEN COND(&FLAG = 'I') THEN(+ 05 CHGVAR VAR(&STS) VALUE('INACTIVE')) 06 OTHERWISE CMD(DO) 07 CHGVAR VAR(&STS) VALUE('ERROR') 08 CHGVAR VAR(&ERROR) VALUE('1') 09 ENDDO 10 ENDSELECT
That’s much easier to understand.
Why do I do that? As I mentioned in a previous post I indent my code to make it, in my opinion, easier to read.
For those of you who are not familiar with the Select group of statement if works like this:
- When &FLAG = ‘A’ line 3 is executed and processing goes to the ENDSELECT command.
- Line is 4 is only executed if &FLAG is not = ‘A’. When &FLAG = ‘I’ line 5 is executed and processing goes down to the ENDSELECT.
- The OTHERWISE is the equivalent as saying “none of the above”. It is only executed if &FLAG is not = ‘A’ and is not = ‘I’. As I want to execute two commands I have a DO command in the OTHERWISE, then the two statements, lines 7 and 8, and an ENDDO, line 9.
- The ENDSELECT signifies the end of the group.
You can learn about the Select Group commands from the IBM website:
This article was written for IBM i 7.1, and it should work with earlier releases too.