Monday, July 31, 2017

CL data structures

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 subroutine
  • ENDSUBR – marks the end of a subroutine
  • CALLSUBR – invokes a subroutine by name
  • RTNSUBR – 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.
  • &RESULT captures the return code.
  • If RTNSUBR RTNVAL(-1) is executed, &RESULT will hold -1.
  • If the subroutine ends normally with ENDSUBR, the return value defaults to 0.

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