Thursday 25 November 2010

Generating a Random number on an iSeries in CL

This i have to admit is very very esoteric and even the iSeries Geeks out there may not be that interested however if you ever need to get a Random Number in CLP or RPG on an iSeries here is a way to do it.

Neither CLP nor RPG has a Pseudo Random Number generator built in, so we have to kludge it to get it to work. You can link the QLEMF C library and use the CERNAN0 api which is the method I found when I went and Googled it the other day.

The other way which I didnt find is to use the QSH shell to do it. This method generates a random number between 0 - 32767 inside the QSH shell env and then stores the result in a DTAARA so that the calling program can access the value, as there in no native way to return vars from QSH environment

01. CRTDTAAARA MyRand *CHAR 5
02. Insert the following code into your PGM

DCL &CMD *CHAR 40
DCL &MYRAND *CHAR 5
CHGVAR VAR(&CMD) VALUE('print $RANDOM|datarea -lw MYRAND')
QSH CMD(&CMD)
RTVDTAARA DTAARA(SX002A) RTNVAR(&MYRAND)

The Print $RANDOM generates the random number

The | separates the two commands

The datarea -lw  MYRAND takes the random number and stores it in the DTAARA

Simples

Disqus for Domi-No-Yes-Maybe