Hidden Features in CL: Data Structures and Subroutines
🌟 Data Structures in CL
Control Language (CL) has more capabilities than many programmers realize. One lesser-known addition is data structure support, introduced in both OPM and ILE CL starting with IBM i 5.4.
This allows you to break down a single variable into smaller, addressable parts. For example, a four-character string can be defined once, and then referenced piece by piece:
PGM PARM(&INPUT)
DCL VAR(&INPUT) TYPE(*CHAR) LEN(4)
DCL VAR(&WORK) TYPE(*CHAR) LEN(4)
DCL VAR(&PART1) TYPE(*CHAR) LEN(1) STG(*DEFINED) DEFVAR(&WORK 1)
DCL VAR(&PART2) TYPE(*CHAR) LEN(1) STG(*DEFINED) DEFVAR(&WORK 2)
DCL VAR(&PART3) TYPE(*CHAR) LEN(1) STG(*DEFINED) DEFVAR(&WORK 3)
DCL VAR(&PART4) TYPE(*CHAR) LEN(1) STG(*DEFINED) DEFVAR(&WORK 4)
CHGVAR VAR(&WORK) VALUE(&INPUT)
ENDPGM
Here, &WORK mirrors the input string, while &PART1 through &PART4 give direct access to each character. This is a simple but powerful way to treat a string like a structured record.
🔄 Subroutines in CL
Another enhancement to CL is the introduction of subroutine commands, which bring structured programming concepts into the language. These commands include:
SUBR– marks the beginning of a subroutineENDSUBR– marks the end of a subroutineCALLSUBR– invokes a subroutine by nameRTNSUBR– exits a subroutine, optionally returning a value
A minimal example looks like this:
PGM
CALLSUBR SUBR(MYROUTINE)
SUBR SUBR(MYROUTINE)
ENDSUBR
ENDPGM
You can also exit early using RTNSUBR, similar to LEAVESR in RPG:
PGM
CALLSUBR SUBR(MYROUTINE)
SUBR SUBR(MYROUTINE)
RTNSUBR
ENDSUBR
ENDPGM
📦 Using Return Values
CL subroutines can return values to the caller. This is managed with the RTNVAL parameter and a receiving variable. For example:
PGM
DCLPRCOPT SUBRSTACK(25)
DCL VAR(&RESULT) TYPE(*INT) LEN(4)
CALLSUBR SUBR(ROUTINE1) RTNVAL(&RESULT)
SUBR SUBR(ROUTINE1)
RTNSUBR RTNVAL(-1)
ENDSUBR
ENDPGM
DCLPRCOPT SUBRSTACK(25)reserves space for up to 25 subroutine calls.&RESULTcaptures the return code.- If
RTNSUBR RTNVAL(-1)is executed,&RESULTwill hold-1. - If the subroutine ends normally with
ENDSUBR, the return value defaults to0.
✅ Summary:
- CL supports data structures, letting you define subfields within a variable.
- CL now includes subroutine commands, enabling modular and reusable code.
- Subroutines can return values, making them more versatile for structured programming.
No comments:
Post a Comment