Friday, March 5, 2010

WebSphere(R) Development Studio ILE RPG Reference - Operation Codes -

WebSphere(R) Development Studio ILE RPG Reference


Operation Codes

This chapter describes, in alphabetical order, each operation code.


ACQ (Acquire)


Free-Form Syntax ACQ{(E)} device-name workstn-file

Code Factor 1 Factor 2 Result Field Indicators
ACQ (E) device- name workstn-file
_ ER _

The ACQ operation acquires the program device specified by device-name for the WORKSTN file specified by workstn-file. If the device is available, ACQ attaches it to the file. If it is not available or is already attached to the file, an error occurs.

To handle ACQ exceptions (file status codes greater than 1000), either the operation code extender 'E' or an error indicator ER can be specified, but not both. If no error indicator or 'E' extender is specified, but the INFSR subroutine is specified, the INFSR receives control when an error/exception occurs. If no indicator, 'E' extender, or INFSR subroutine is specified, the default error/exception handler receives control when an error/exception occurs. For more information on error handling, see File Exception/Errors.

No input or output operation occurs when the ACQ operation is processed. ACQ may be used with a multiple device file or, for error recovery purposes, with a single device file. One program may acquire and have the device available to any called program which shares the file and allow the called program to release the device. See the section on "Multiple-Device Files" in the chapter about using WORKSTN files in the WebSphere Development Studio: ILE RPG Programmer's Guide.


ADD (Add)


Free-Form Syntax (not allowed - use the + or += operators)

Code Factor 1 Factor 2 Result Field Indicators
ADD (H) Addend Addend Sum + - Z

If factor 1 is specified, the ADD operation adds it to factor 2 and places the sum in the result field. If factor 1 is not specified, the contents of factor 2 are added to the result field and the sum is placed in the result field. Factor 1 and factor 2 must be numeric and can contain one of: an array, array element, constant, field name, literal, subfield, or table name. For the rules for specifying an ADD operation, see Arithmetic Operations.

Figure 230. ADD Operations


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* The value 1 is added to RECNO.
C ADD 1 RECNO
* The contents of EHWRK are added to CURHRS.
C ADD EHWRK CURHRS
* The contents of OVRTM and REGHRS are added together and
* placed in TOTPAY.
C OVRTM ADD REGHRS TOTPAY

ADDDUR (Add Duration)


Free-Form Syntax (not allowed - use the + or += operators with duration functions such as %YEARS and %MONTHS)

Code Factor 1 Factor 2 Result Field Indicators
ADDDUR (E) Date/Time Duration:Duration Code Date/Time _ ER _

The ADDDUR operation adds the duration specified in factor 2 to a date or time and places the resulting Date, Time or Timestamp in the result field.

Factor 1 is optional and may contain a Date, Time or Timestamp field, subfield, array, array element, literal or constant. If factor 1 contains a field name, array or array element then its data type must be the same data type as the field specified in the result field. If factor 1 is not specified the duration is added to the field specified in the result field.

Factor 2 is required and contains two subfactors. The first is a duration and may be a numeric field, array element or constant with zero decimal positions. If the duration is negative then it is subtracted from the date. The second subfactor must be a valid duration code indicating the type of duration. The duration code must be consistent with the result field data type. You can add a year, month or day duration but not a minute duration to a date field. For list of duration codes and their short forms see Date Operations.

The result field must be a date, time or timestamp data type field, array or array element. If factor 1 is blank, the duration is added to the value in the result field. If the result field is an array, the value in factor 2 is added to each element of the array. If the result field is a time field, the result will always be a valid Time. For example adding 59 minutes to 23:59:59 would give 24:58:59. Since this time is not valid, the compiler adjusts it to 00:58:59.

When adding a duration in months to a date, the general rule is that the month portion is increased by the number of months in the duration, and the day portion is unchanged. The exception to this is when the resulting day portion would exceed the actual number of days in the resulting month. In this case, the resulting day portion is adjusted to the actual month end date. The following examples (which assume a *YMD format) illustrate this point.

  • '98/05/30' ADDDUR 1:*MONTH results in '98/06/30'

    The resulting month portion has been increased by 1; the day portion is unchanged.

  • '98/05/31' ADDDUR 1:*MONTH results in '98/06/30'

    The resulting month portion has been increased by 1; the resulting day portion has been adjusted because June has only 30 days.

Similar results occur when adding a year duration. For example, adding one year to '92/02/29' results in '93/02/28', an adjusted value since the resulting year is not a leap year.

For more information on working with date-time fields, see Date Operations.

An error situation arises when one of the following occurs:

  • The value of the Date, Time or Timestamp field in factor 1 is invalid
  • Factor 1 is blank and the value of the result field before the operation is invalid
  • Overflow or underflow occurred (that is, the resulting value is greater than *HIVAL or less than *LOVAL).

In an error situation,

  • An error (status code 112 or 113) is signalled.
  • The error indicator (columns 73-74) -- if specified -- is set on, or the %ERROR built-in function -- if the 'E' extender is specified -- is set to return '1'.
  • The value of the result field remains unchanged.

To handle exceptions with program status codes 112 or 113, either the operation code extender 'E' or an error indicator ER can be specified, but not both. For more information on error handling, see Program Exception/Errors.

Note:
The system places a 15-digit limit on durations. Adding a Duration with more than 15 significant digits will cause errors or truncation. These problems can be avoided by limiting the first subfactor in Factor 2 to 15 digits.

Figure 231. ADDDUR Operations


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

HKeywords+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
H TIMFMT(*USA) DATFMT(*MDY&)
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++
*
DDateconst C CONST(D'12 31 92')
*
* Define a Date field and initialize
*
DLoandate S D DATFMT(*EUR) INZ(D'12 31 92')
DDuedate S D DATFMT(*ISO)
Dtimestamp S Z
Danswer S T

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
* Determine a DUEDATE which is xx years, yy months, zz days later
* than LOANDATE.
C LOANDATE ADDDUR XX:*YEARS DUEDATE
C ADDDUR YY:*MONTHS DUEDATE
C ADDDUR ZZ:*DAYS DUEDATE

* Determine the date 23 days later
*
C ADDDUR 23:*D DUEDATE
* Add a 1234 microseconds to a timestamp
*
C ADDDUR 1234:*MS timestamp
* Add 12 HRS and 16 minutes to midnight
*
C T'00:00 am' ADDDUR 12:*Hours answer
C ADDDUR 16:*Minutes answer

* Subtract 30 days from a loan due date
*
C ADDDUR -30:*D LOANDUE

ALLOC (Allocate Storage)


Free-Form Syntax (not allowed - use the %ALLOC built-in function)

Code Factor 1 Factor 2 Result Field Indicators
ALLOC (E)
Length Pointer _ ER _

The ALLOC operation allocates storage in the default heap of the length specified in factor 2. The result field pointer is set to point to the new heap storage. The storage is uninitialized.

Factor 2 must be a numeric with zero decimal positions. It can be a literal, constant, standalone field, subfield, table name or array element. The value must be between 1 and 16776704. If the value is out of range at runtime, an error will occur with status 425. If the storage could not be allocated, an error will occur with status 426. If these errors occur, the result field pointer remains unchanged.

The result field must be a basing pointer scalar variable (a standalone field, data structure subfield, table name, or array element).

To handle exceptions with program status codes 425 or 426, either the operation code extender 'E' or an error indicator ER can be specified, but not both. For more information on error handling, see Program Exception/Errors.

For more information, see Memory Management Operations.

Figure 232. ALLOC Operation


 D Ptr1            S               *

D Ptr2 S *
C ALLOC 7 Ptr1

* Now Ptr1 points to 7 bytes of storage
*
C ALLOC (E) 12345678 Ptr2
* This is a large amount of storage, and sometimes it may
* be unavailable. If the storage could not be allocated,
* %ERROR will return '1', the status is set to 00426, and
* %STATUS will return 00426.

ANDxx (And)


Free-Form Syntax (not allowed - use the AND operator)

Code Factor 1 Factor 2 Result Field Indicators
ANDxx Comparand Comparand



This operation must immediately follow a ANDxx, DOUxx, DOWxx, IFxx, ORxx, or WHENxx operation. With ANDxx, you can specify a complex condition for the DOUxx, DOWxx, IFxx, and WHENxx operations. The ANDxx operation has higher precedence than the ORxx operation.

The control level entry (positions 7 and 8) can be blank or can contain an L1 through L9 indicator, an LR indicator, or an L0 entry to group the statement within the appropriate section of the program. The control level entry must be the same as the control level entry for the associated DOUxx, DOWxx, IFxx, or WHENxx operation. Conditioning indicator entries (positions 9 through 11) are not permitted.

Factor 1 and factor 2 must contain a literal, a named constant, a figurative constant, a table name, an array element, a data structure name, or a field name. Factor 1 and factor 2 must be of the same type. For example, a character field cannot be compared with a numeric. The comparison of factor 1 and factor 2 follows the same rules as those given for the compare operations. See Compare Operations.

Figure 233. ANDxx Operations


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* If ACODE is equal to A and indicator 50 is on, the MOVE
* and WRITE operations are processed.
C ACODE IFEQ 'A'
C *IN50 ANDEQ *ON
C MOVE 'A' ACREC
C WRITE RCRSN

* If the previous conditions were not met but ACODE is equal
* to A, indicator 50 is off, and ACREC is equal to D, the
* following MOVE operation is processed.
C ELSE
C ACODE IFEQ 'A'
C *IN50 ANDEQ *OFF
C ACREC ANDEQ 'D'
C MOVE 'A' ACREC
C ENDIF
C ENDIF


BEGSR (Beginning of Subroutine)


Free-Form Syntax BEGSR subroutine-name

Code Factor 1 Factor 2 Result Field Indicators
BEGSR subroutine-name




The BEGSR operation identifies the beginning of an RPG IV subroutine. subroutine-name is the subroutine name. You may specify the same name as the subroutine-name on the EXSR operation referring to the subroutine, in the result field of the CASxx operation referring to the subroutine, or in the entry of an INFSR file specification keyword of the subroutine is a file-error subroutine. The control level entry (positions 7 and 8) can be SR or blank. Conditioning indicator entries are not permitted.

Every subroutine must have a unique symbolic name. The keyword *PSSR used in factor 1 specifies that this is a program exception/error subroutine to handle program-detected exception/errors. Only one subroutine can be defined by this keyword. *INZSR in factor 1 specifies a subroutine to be run during the initialization step. Only one subroutine can be defined *INZSR.

See Figure 156 for an example of coding subroutines; see Subroutine Operations for general information on subroutine operations.


BITOFF (Set Bits Off)


Free-Form Syntax (not allowed - use the %BITAND and %BITNOT built-in functions)

Code Factor 1 Factor 2 Result Field Indicators
BITOFF
Bit numbers Character field


The BITOFF operation causes bits identified in factor 2 to be set off (set to 0) in the result field. Bits not identified in factor 2 remain unchanged. Therefore, when using BITOFF to format a character, you should use both BITON and BITOFF: BITON to specify the bits to be set on (=1), and BITOFF to specify the bits to be set off (=0). Unless you explicitly set on or off all the bits in the character, you might not get the character you want.

If you want to assign a particular bit pattern to a character field, use the MOVE (Move) operation with a hexadecimal literal in factor 2.

Factor 2 can contain:

  • Bit numbers 0-7: From 1 to 8 bits can be set off per operation. They are identified by the numbers 0 through 7. (0 is the leftmost bit.) Enclose the bit numbers in apostrophes. For example, to set off bits 0, 2, and 5, enter '025' in factor 2.
  • Field name: You can specify the name of a one-position character field, table element, or array element in factor 2. The bits that are on in the field, table element, or array element are set off in the result field; bits that are off do not affect the result.
  • Hexadecimal literal or named constant: You can specify a 1-byte hexadecimal literal or hexadecimal named constant. Bits that are on in factor 2 are set off in the result field; bits that are off are not affected.
  • Named constant: A character named constant up to eight positions long containing the bit numbers to be set off.

In the result field, specify a one-position character field. It can be an array element if each element in the array is a one-position character field.

Figure 234. BITOFF Example


 *    Set off bits 0,4,6 in  FieldG.  Leave bits 1,2,3,5,7 unchanged.

* Setting off bit 0, which is already off, results in bit 0 remaining off.
* Factor 2 = 10001010
* FieldG = 01001111 (before)
* FieldG = 01000101 (after)
C BITOFF '046' FieldG
* Set off bits 0,2,4,6 in FieldI. Leave bits 1,3,5,7 unchanged.
* Setting off bit 2, which is already off, results in bit 2 remaining off.
* Factor 2 = 10101010
* FieldI = 11001110 (before)
* FieldI = 01000100 (after)
C BITOFF BITNC FieldI
* HEXNC is equivalent to literal '4567', bit pattern 00001111.
* Set off bits 4,5,6,7 in FieldK. Leave bits 0,1,2,3 unchanged.
* Factor 2 = 11110000
* FieldK = 10000000 (before)
* FieldK = 00000000 (after)
C BITOFF HEXNC2 FieldK
C RETURN


BITON (Set Bits On)


Free-Form Syntax (not allowed - use the %BITOR built-in function)

Code Factor 1 Factor 2 Result Field Indicators
BITON
Bit numbers Character field


The BITON operation causes bits identified in factor 2 to be set on (set to 1) in the result field. Bits not identified in factor 2 remain unchanged. Therefore, when using BITON to format a character, you should use both BITON and BITOFF: BITON to specify the bits to be set on (=1), and BITOFF to specify the bits to be set off (=0). Unless you explicitly set on or off all the bits in the character, you might not get the character you want.

If you want to assign a particular bit pattern to a character field, use the MOVE (Move) operation with a hexadecimal literal in factor 2.

Factor 2 can contain:

  • Bit numbers 0-7: From 1 to 8 bits can be set on per operation. They are identified by the numbers 0 through 7. (0 is the leftmost bit.) Enclose the bit numbers in apostrophes. For example, to set bits 0, 2, and 5 on, enter '025' in factor 2.
  • Field name: You can specify the name of a one-position character field, table element, or array element in factor 2. The bits that are on in the field, table element, or array element are set on in the result field; bits that are off are not affected.
  • Hexadecimal literal or named constant: You can specify a 1-byte hexadecimal literal. Bits that are on in factor 2 are set on in the result field; bits that are off do not affect the result.
  • Named constant: A character named constant up to eight positions long containing the bit numbers to be set on.

In the result field, specify a one-position character field. It can be an array element if each element in the array is a one-position character field.

Figure 235. BITON Example


DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++

D FieldA S 1A INZ(X'00')
D FieldB S 1A INZ(X'00')
D FieldC S 1A INZ(X'FF')
D FieldD S 1A INZ(X'C0')
D FieldE S 1A INZ(X'C0')
D FieldF S 1A INZ(X'81')
D FieldG S 1A INZ(X'4F')
D FieldH S 1A INZ(X'08')
D FieldI S 1A INZ(X'CE')
D FieldJ S 1A INZ(X'80')
D FieldK S 1A INZ(X'80')
D BITNC C CONST('0246')
D HEXNC C CONST(X'0F')
D HEXNC2 C CONST(X'F0')

C*0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* Set on bits 0,4,5,6,7 in FieldA. Leave bits 1,2,3 unchanged.
* Factor 2 = 10001111
* FieldA = 00000000 (before)
* FieldA = 10001111 (after)
C BITON '04567' FieldA
* Set on bit 3 in FieldB. Leave bits 0,1,2,4,5,6,7 unchanged.
* Factor 2 = 00010000
* FieldB = 00000000 (before)
* FieldB = 00010000 (after)
C BITON '3' FieldB
* Set on bit 3 in FieldC. Leave bits 0,1,2,4,5,6,7 unchanged.
* Setting on bit 3, which is already on, results in bit 3 remaining on.
* Factor 2 = 00010000
* FieldC = 11111111 (before)
* FieldC = 11111111 (after)
C BITON '3' FieldC
* Set on bit 3 in FieldD. Leave bits 0,1,2,4,5,6,7 unchanged.
* Factor 2 = 00010000
* FieldD = 11000000 (before)
* FieldD = 11010000 (after)
C BITON '3' FieldD
* Set on bits 0 and 1 in FieldF. Leave bits 2,3,4,5,6,7 unchanged.
* (Setting on bit 0, which is already on, results in bit 0 remaining on.)
* Factor 2 = 11000000
* FieldF = 10000001 (before)
* FieldF = 11000001 (after)
C BITON FieldE FieldF
* X'C1' is equivalent to literal '017', bit pattern 11000001.
* Set on bits 0,1,7 in FieldH. Leave bits 2,3,4,5,6 unchanged.
* Factor 2 = 11000001
* FieldH = 00001000 (before)
* FieldH = 11001001 (after)
C BITON X'C1' FieldH
* HEXNC is equivalent to literal '4567', bit pattern 00001111.
* Set on bits 4,5,6,7 in FieldJ. Leave bits 0,1,2,3 unchanged.
* Factor 2 = 00001111
* FieldJ = 10000000 (before)
* FieldJ = 10001111 (after)
C BITON HEXNC FieldJ
C RETURN


CABxx (Compare and Branch)


Free-Form Syntax (not allowed - use other operation codes, such as LEAVE, ITER, and RETURN)

Code Factor 1 Factor 2 Result Field Indicators
CABxx Comparand Comparand Label HI LO EQ

The CABxx operation compares factor 1 with factor 2. If the condition specified by xx is true, the program branches to the TAG or ENDSR operation associated with the label specified in the result field. Otherwise, the program continues with the next operation in the sequence. If the result field is not specified, the resulting indicators (positions 71-76) are set accordingly, and the program continues with the next operation in the sequence.

You can specify conditioning indicators. Factor 1 and factor 2 must contain a literal, a named constant, a figurative constant, a table name, an array element, a data structure name, or a field name. Factor 1 and factor 2 must be of the same type. The label specified in the result field must be associated with a unique TAG operation and must be a unique symbolic name.

A CABxx operation in the main procedure can specify a branch:

  • To a previous or a succeeding specification line
  • From a detail calculation line to another detail calculation line
  • From a total calculation line to another total calculation line
  • From a detail calculation line to a total calculation line
  • From a subroutine to a detail calculation line or a total calculation line.

A CABxx operation in a subprocedure can specify a branch:

  • From a line in the body of the subprocedure to another line in the body of the subprocedure
  • From a line in a subroutine to another line in the same subroutine
  • From a line in a subroutine to a line in the body of the subprocedure

The CABxx operation cannot specify a branch from outside a subroutine to a TAG or ENDSR operation within that subroutine.

Attention!

Branching from one point in the logic to another may result in an endless loop. You must ensure that the logic of your program or procedure does not produce undesirable results.

Resulting indicators are optional. When specified, they are set to reflect the results of the compare operation. For example, the HI indicator is set when F1>F2, LO is set when F1

See Compare Operations for the rules for comparing factor 1 with factor 2.

Figure 236. CABxx Operations


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* The field values are:
* FieldA = 100.00
* FieldB = 105.00
* FieldC = ABC
* FieldD = ABCDE
*
* Branch to TAGX.
C FieldA CABLT FieldB TAGX
*
* Branch to TAGX.
C FieldA CABLE FieldB TAGX
*
* Branch to TAGX; indicator 16 is off.
C FieldA CABLE FieldB TAGX 16
*
* Branch to TAGX; indicator 17 is off, indicator 18 is on.
C FieldA CAB FieldB TAGX 1718
*
* Branch to TAGX; indicator 19 is on.
C FieldA CAB FieldA TAGX 19
*
* No branch occurs.
C FieldA CABEQ FieldB TAGX
*
* No branch occurs; indicator 20 is on.
C FieldA CABEQ FieldB TAGX 20
*
* No branch occurs; indicator 21 is off.
C FieldC CABEQ FieldD TAGX 21
C :
C TAGX TAG


CALL (Call a Program)


Free-Form Syntax (not allowed - use the CALLP operation code)

Code Factor 1 Factor 2 Result Field Indicators
CALL (E)
Program name Plist name _ ER LR

The CALL operation passes control to the program specified in factor 2.

Factor 2 must contain a character entry specifying the name of the program to be called.

In the result field, specify parameters in one of the following ways:

  • Enter the name of a PLIST
  • Leave the result field blank. This is valid if the called program does not access parameters or if the PARM statements directly follow the CALL operation.

Positions 71 and 72 must be blank.

To handle CALL exceptions (program status codes 202, 211, or 231), either the operation code extender 'E' or an error indicator ER can be specified, but not both. For more information on error handling, see Program Exception/Errors.

Any valid resulting indicator can be specified in positions 75 and 76 to be set on if the called program is an RPG program or main procedure that returns with the LR indicator on.

Note:
The LR indicator is not allowed in a thread-safe environment.

For more information on call operations, see Call Operations.

Figure 237. CALL Operation


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
* The CALL operation calls PROGA and allows PROGA to access
* FieldA and FieldB, defined elsewhere. PROGA is run using the content
* of FieldA and FieldB. When PROGA has completed, control
* returns to the statement following the last PARM statement.
*
*
C CALL 'PROGA'
C PARM FieldA
C PARM FieldB


CALLB (Call a Bound Procedure)


Free-Form Syntax (not allowed - use the CALLP operation code)

Code Factor 1 Factor 2 Result Field Indicators
CALLB (D E)
Procedure name or procedure pointer Plist name _ ER LR

The CALLB operation is used to call bound procedures written in any of the ILE languages.

The operation extender D may be used to include operational descriptors. This is similar to calling a prototyped procedure with CALLP when its parameters have been defined with keyword OPDESC. (Operational descriptors provide the programmer with run-time resolution of the exact attributes of character or graphic strings passed (that is, length and type of string). For more information, see chapter on calling programs and procedures in the WebSphere Development Studio: ILE RPG Programmer's Guide.

Factor 2 is required and must be a literal or constant containing the name of the procedure to be called, or a procedure pointer containing the address of the procedure to be called. All references must be able to be resolved at bind time. The procedure name provided is case sensitive and may contain more than 10 characters, but no more than 255. If the name is longer than 255, it will be truncated to 255. The result field is optional and may contain a PLIST name.

To handle CALLB exceptions (program status codes 202, 211, or 231), either the operation code extender 'E' or an error indicator ER can be specified, but not both. For more information on error handling, see Program Exception/Errors.

An indicator specified in positions 75-76 will be set on when the call ends with LR set on.

Note:
The LR indicator is not allowed in a thread-safe environment.

For more information on call operations, see Call Operations.

Figure 238. CALLB Operation


DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++

* Define a procedure pointer
D
D ProcPtr S * PROCPTR INZ(%PADDR('Create_Space'))
D Extern S 10
D

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
* The following call linkage would be STATIC
C CALLB 'BOUNDPROC'
* The following call linkage would be DYNAMIC
C CALL Extern
* The following call linkage would be STATIC, using a procedure pointer
C CALLB ProcPtr

CALLP (Call a Prototyped Procedure or Program)


Free-Form Syntax {CALLP{(EMR)}} name( {parm1{:parm2...}} )

Code Factor 1 Extended Factor 2
CALLP (E M/R)
name{ (parm1 {:parm2...}) }

The CALLP operation is used to call prototyped procedures or programs.

Unlike the other call operations, CALLP uses a free-form syntax. You use the name operand to specify the name of the prototype of the called program or procedure, as well as any parameters to be passed. (This is similar to calling a built-in function.) A maximum of 255 parameters are allowed for a program call, and a maximum of 399 for a procedure call.

On a free-form calculation specification, the operation code name may be omitted if no extenders are needed.

The compiler then uses the prototype name to obtain an external name, if required, for the call. If the keyword EXTPGM is specified on the prototype, the call will be a dynamic external call; otherwise it will be a bound procedure call.

A prototype for the program or procedure being called must be included in the definition specifications preceding the CALLP.

Note that if CALLP is used to call a procedure which returns a value, that value will not be available to the caller. If the value is required, call the prototyped procedure from within an expression.

To handle CALLP exceptions (program status codes 202, 211, or 231), the operation code extender 'E' can be specified. For more information on error handling, see Program Exception/Errors.

Note:
The E extender is only active during the final call for CALLP. If an error occurs on a call that is done as part of the parameter processing, control will not pass to the next operation. For example, if FileRecs is a procedure returning a numeric value, and an error occurs when FileRecs is called in the following statement, the E extender would have no effect.
CALLP (E) PROGNAME(FileRecs(Fld) + 1)

For more information on call operations, see Call Operations. For information on how operation extenders M and R are used, see Precision Rules for Numeric Operations.

Figure 239. Calling a Prototyped Program Using CALLP


 *..1....+....2....+....3....+....4....+....5....+....6....+....7...+....

*-------------------------------------------------------------
* This prototype for QCMDEXC defines two parameters:
* 1- a character field that may be shorter in length
* than expected
* 2- any numeric field
*-------------------------------------------------------------
D qcmdexc PR extpgm('QCMDEXC')
D cmd 200A options(*varsize) const
D cmdlen 15P 5 const

/FREE
qcmdexc ('WRKSPLF' : %size ('WRKSPLF'));
/END-FREE

The following example of CALLP is from the service program example in WebSphere Development Studio: ILE RPG Programmer's Guide. CvtToHex is a procedure in a service program created to hold conversion routines. CvtToHex converts an input string to its hexadecimal form. The prototyped calls are to the ILE CEE API, CEEDOD (Retrieve Operational Descriptor). It is used to determine the length of the input string.

Figure 240. Calling a Prototyped Procedure Using CALLP


 *..1....+....2....+....3....+....4....+....5....+....6....+....7...+....

*=================================================================*
* CvtToHex - convert input string to hex output string *
*=================================================================*
D/COPY MYLIB/QRPGLESRC,CVTHEXPR

*-----------------------------------------------------------------*
* Main entry parameters *
* 1. Input: string character(n) *
* 2. Output: hex string character(2 * n) *
*-----------------------------------------------------------------*
D CvtToHex PI OPDESC
D InString 16383 CONST OPTIONS(*VARSIZE)
D HexString 32766 OPTIONS(*VARSIZE)

*-----------------------------------------------------------------*
* Prototype for CEEDOD (Retrieve operational descriptor) *
*-----------------------------------------------------------------*
D CEEDOD PR
D 10I 0 CONST
D 10I 0
D 10I 0
D 10I 0
D 10I 0
D 10I 0
D 12A OPTIONS(*OMIT)

* Parameters passed to CEEDOD
D ParmNum S 10I 0
D DescType S 10I 0
D DataType S 10I 0
D DescInfo1 S 10I 0
D DescInfo2 S 10I 0
D InLen S 10I 0
D HexLen S 10I 0
 *-----------------------------------------------------------------*

* Other fields used by the program *
*-----------------------------------------------------------------*
D HexDigits C CONST('0123456789ABCDEF')
D IntDs DS
D IntNum 5I 0 INZ(0)
D IntChar 1 OVERLAY(IntNum:2)
D HexDs DS
D HexC1 1
D HexC2 1
D InChar S 1
D Pos S 5P 0
D HexPos S 5P 0

/FREE
//-------------------------------------------------------------//
// Use the operational descriptors to determine the lengths of //
// the parameters that were passed. //
//-------------------------------------------------------------//
CEEDOD (1 : DescType : DataType :
DescInfo1 : DescInfo2 : Inlen : *OMIT);
CEEDOD (2 : DescType : DataType :
DescInfo1 : DescInfo2 : HexLen : *OMIT);
//-------------------------------------------------------------//
// Determine the length to handle (minimum of the input length //
// and half of the hex length) //
//-------------------------------------------------------------//
if InLen > HexLen / 2;
InLen = HexLen / 2;
endif;
//-------------------------------------------------------------//
// For each character in the input string, convert to a 2-byte //
// hexadecimal representation (for example, '5' --> 'F5') //
//-------------------------------------------------------------//
HexPos = 1;
for Pos = 1 to InLen;
InChar = %SUBST(InString : Pos :1);
exsr GetHex;
%subst (HexString: HexPos: 2) = HexDs;
HexPos = HexPos + 2;
endfor;
//------------------------------//
// Done; return to caller. //
//------------------------------//
return;
//================================================================//
// GetHex - subroutine to convert 'InChar' to 'HexDs' //
// //
// Use division by 16 to separate the two hexadecimal digits. //
// The quotient is the first digit, the remainder is the second. //
//================================================================//
begsr GetHex;
IntChar = InChar;
//-----------------------------------------------------//
// Use the hexadecimal digit (plus 1) to substring the //
// list of hexadecimal characters '012...CDEF'. //
//-----------------------------------------------------//
HexC1 = %subst (HexDigits: %div(IntNum:16) + 1: 1);
HexC2 = %subst (HexDigits: %rem(IntNum:16) + 1: 1);
     endsr;  // GetHex

/END-FREE

CASxx (Conditionally Invoke Subroutine)


Free-Form Syntax (not allowed - use the IF and EXSR operation codes)

Code Factor 1 Factor 2 Result Field Indicators
CASxx Comparand Comparand Subroutine name HI LO EQ

The CASxx operation allows you to conditionally select a subroutine for processing. The selection is based on the relationship between factor 1 and factor 2, as specified by xx. If the relationship denoted by xx exists between factor 1 and factor 2, the subroutine specified in the result field is processed.

You can specify conditioning indicators. Factor 1 and factor 2 can contain a literal, a named constant, a figurative constant, a field name, a table name, an array element, a data structure name, or blanks (blanks are valid only if xx is blank and no resulting indicators are specified in positions 71 through 76). If factor 1 and factor 2 are not blanks, both must be of the same data type. In a CAS operation, factor 1 and factor 2 are required only if resulting indicators are specified in positions 71 through 76.

The result field must contain the name of a valid RPG IV subroutine, including *PSSR, the program exception/error subroutine, and *INZSR, the program initialization subroutine. If the relationship denoted by xx exists between factor 1 and factor 2, the subroutine specified in the result field is processed. If the relationship denoted by xx does not exist, the program continues with the next CASxx operation in the CAS group. A CAS group can contain only CASxx operations. An ENDCS operation must follow the last CASxx operation to denote the end of the CAS group. After the subroutine is processed, the program continues with the next operation to be processed following the ENDCS operation, unless the subroutine passes control to a different operation.

The CAS operation with no resulting indicators specified in positions 71 through 76 is functionally identical to an EXSR operation, because it causes the unconditional running of the subroutine named in the result field of the CAS operation. Any CASxx operations that follow an unconditional CAS operation in the same CAS group are never tested. Therefore, the normal placement of the unconditional CAS operation is after all other CASxx operations in the CAS group.

You cannot use conditioning indicators on the ENDCS operation for a CAS group.

See Compare Operations for further rules for the CASxx operation.

Figure 241. CASxx Operation


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* The CASGE operation compares FieldA with FieldB. If FieldA is
* greater than or equal to FieldB, Subr01 is processed and the
* program continues with the operation after the ENDCS operation.
*
C FieldA CASGE FieldB Subr01
*
* If FieldA is not greater than or equal to FieldB, the program
* next compares FieldA with FieldC. If FieldA is equal to FieldC,
* SUBR02 is processed and the program continues with the operation
* after the ENDCS operation.
*
C FieldA CASEQ FieldC Subr02
*
* If FieldA is not equal to FieldC, the CAS operation causes Subr03
* to be processed before the program continues with the operation
* after the ENDCS operation.
* The CAS statement is used to provide a subroutine if none of
* the previous CASxx operations have been met.
*
C CAS Subr03
*
* The ENDCS operation denotes the end of the CAS group.
*
C ENDCS

CAT (Concatenate Two Strings)


Free-Form Syntax (not allowed - use the + operator)

Code Factor 1 Factor 2 Result Field Indicators
CAT (P) Source string 1 Source string 2: number of blanks Target string


The CAT operation concatenates the string specified in factor 2 to the end of the string specified in factor 1 and places it in the result field. The source and target strings must all be of the same type, either all character, all graphic, or all UCS-2. If no factor 1 is specified, factor 2 is concatenated to the end of the result field string.

Factor 1 can contain a string, which can be one of: a field name, array element, named constant, data structure name, table name, or literal. If factor 1 is not specified, the result field is used. In the following discussion, references to factor 1 apply to the result field if factor 1 is not specified.

Factor 2 must contain a string, and may contain the number of blanks to be inserted between the concatenated strings. Its format is the string, followed by a colon, followed by the number of blanks. The blanks are in the format of the data. For example, for character data a blank is x'40', while for UCS-2 data a blank is x'0020'. The string portion can contain one of: a field name, array element, named constant, data structure name, table name, literal, or data structure subfield name. The number of blanks portion must be numeric with zero decimal positions, and can contain one of: a named constant, array element, literal, table name, or field name.

If a colon is specified, the number of blanks must be specified. If no colon is specified, concatenation occurs with the trailing blanks, if any, in factor 1, or the result field if factor 1 is not specified.

If the number of blanks, N, is specified, factor 1 is copied to the result field left-justified. If factor 1 is not specified the result field string is used. Then N blanks are added following the last non-blank character. Then factor 2 is appended to this result. Leading blanks in factor 2 are not counted when N blanks are added to the result; they are just considered to be part of factor 2. If the number of blanks is not specified, the trailing and leading blanks of factor 1 and factor 2 are included in the result.

The result field must be a string and can contain one of: a field name, array element, data structure name, or table name. Its length should be the length of factor 1 and factor 2 combined plus any intervening blanks; if it is not, truncation occurs from the right. If the result field is variable-length, its length does not change.

A P operation extender indicates that the result field should be padded on the right with blanks after the concatenation occurs if the result field is longer than the result of the operation. If padding is not specified, only the leftmost part of the field is affected.

At run time, if the number of blanks is fewer than zero, the compiler defaults the number of blanks to zero.

Note:
Figurative constants cannot be used in the factor 1, factor 2, or result fields. No overlapping is allowed in a data structure for factor 1 and the result field, or for factor 2 and the result field.

Figure 242. CAT Operation


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* The following example shows leading blanks in factor 2. After
* the CAT, the RESULT contains 'MR. SMITH'.
*
C MOVE 'MR.' NAME 3
C MOVE ' SMITH' FIRST 6
C NAME CAT FIRST RESULT 9

*
* The following example shows the use of CAT without factor 1.
* FLD2 is a 9 character string. Prior to the concatenation, it
* contains 'ABC '; FLD1 contains 'XYZ
* After the concatenation, FLD2 contains 'ABC XYZ '.
*
C MOVEL(P) 'ABC' FLD2 9
C MOVE 'XYZ' FLD1 3
C CAT FLD1:2 FLD2

Figure 243. CAT Operation with leading blanks


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* CAT concatenates LAST to NAME and inserts one blank as specified
* in factor 2. TEMP contains 'Mr. Smith'.
C MOVE 'Mr. ' NAME 6
C MOVE 'Smith ' LAST 6
C NAME CAT LAST:1 TEMP 9

*
* CAT concatenates 'RPG' to STRING and places 'RPG/400' in TEMP.
C MOVE '/400' STRING 4
C 'RPG' CAT STRING TEMP 7

*
* The following example is the same as the previous example except
* that TEMP is defined as a 10 byte field. P operation extender
* specifies that blanks will be used in the rightmost positions
* of the result field that the concatenation result, 'RPG/400',
* does not fill. As a result, TEMP contains 'RPG/400 '
* after concatenation.
C MOVE *ALL'*' TEMP 10
C MOVE '/400' STRING 4
C 'RPG' CAT(P) STRING TEMP

*
* After this CAT operation, the field TEMP contains 'RPG/4'.
* Because the field TEMP was not large enough, truncation occurred.
C MOVE '/400' STRING 4
C 'RPG' CAT STRING TEMP 5

*
* Note that the trailing blanks of NAME are not included because
* NUM=0. The field TEMP contains 'RPGIV '.
C MOVE 'RPG ' NAME 5
C MOVE 'IV ' LAST 5
C Z-ADD 0 NUM 1 0
C NAME CAT(P) LAST:NUM TEMP 10

Figure 244. CAT Operation with Graphic data


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

*
* The following example shows the use of graphic strings
*
DName+++++++++++ETDsFrom+++To/L+++IDc.Functions+++++++++++++++++++++++++
* Value of Graffld is 'AACCBBGG'.
* Value of Graffld2 after CAT 'aa AACCBBGG '
* Value of Graffld3 after CAT 'AABBCCDDEEFFGGHHAACC'
*
D Graffld 4G INZ(G'oAACCBBGGi')
D Graffld2 10G INZ
D Graffld3 10G INZ(G'oAABBCCDDEEFFGGHHi')

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq.
* The value 2 represents 2 graphic blanks as separators
C G'oaai' cat Graffld:2 Graffld2
C cat Graffld Graffld3


CHAIN (Random Retrieval from a File)


Free-Form Syntax CHAIN{(ENHMR)} search-arg name {data-structure}

Code Factor 1 Factor 2 Result Field Indicators
CHAIN (E N) search-arg name (file or record format) data-structure NR ER _

The CHAIN operation retrieves a record from a full procedural file (F in position 18 of the file description specifications), sets a record identifying indicator on (if specified on the input specifications), and places the data from the record into the input fields.

The search argument, search-arg, must be the key or relative record number used to retrieve the record. If access is by key, search-arg can be a a single key in the form of a field name, a named constant, a figurative constant, or a literal.

If the file is an externally-described file, search-arg can also be a composite key in the form of a KLIST name, a list of values, or %KDS. Graphic and UCS-2 key fields must have the same CCSID as the key in the file. For an example of %KDS, see the example at the end of %KDS (Search Arguments in Data Structure). If access is by relative record number, search-arg must be an integer literal or a numeric field with zero decimal positions.

The name operand specifies the file or record format name that is to be read. A record format name is valid with an externally described file. If a file name is specified in name and access is by key, the CHAIN operation retrieves the first record that matches the search argument.

If name is a record format name and access is by key, the CHAIN operation retrieves the first record of the specified record type whose key matches the search argument. If no record is found of the specified record type that matches the search argument, a no-record-found condition exists.

If the data-structure operand is specified, the record is read directly into the data structure. If name refers to a program-described file (identified by an F in position 22 of the file description specification), the data structure can be any data structure of the same length as the file's declared record length. If name refers to an externally-described file or a record format from an externally described file, the data structure must be a data structure defined with EXTNAME(...:*INPUT) or LIKEREC(...:*INPUT). See File Operations for information on how data is transferred between the file and the data structure.

For a WORKSTN file, the CHAIN operation retrieves a subfile record.

For a multiple device file, you must specify a record format in the name operand. Data is read from the program device identified by the field name specified in the DEVID(fieldname) keyword in the file specifications for the device file. If the keyword is not specified, data is read from the device for the last successful input operation to the file.

If the file is specified as an input DISK file, all records are read without locks and so no operation extender can be specified. If the file is specified as update, all records are locked if the N operation extender is not specified.

If you are reading from an update disk file, you can specify an N operation extender to indicate that no lock should be placed on the record when it is read (e.g. CHAIN (N)). See the WebSphere Development Studio: ILE RPG Programmer's Guide for more information.

You can specify an indicator in positions 71-72 that is set on if no record in the file matches the search argument. This information can also be obtained from the %FOUND built-in function, which returns '0' if no record is found, and '1' if a record is found.

To handle CHAIN exceptions (file status codes greater than 1000), either the operation code extender 'E' or an error indicator ER can be specified, but not both. For more information on error handling, see File Exception/Errors.

Positions 75 and 76 must be blank.

When the CHAIN operation is successful, the file specified in name is positioned such that a subsequent read operation retrieves the record logically following or preceding the retrieved record. When the CHAIN operation is not completed successfully (for example, an error occurs or no record is found), the file specified in name must be repositioned (for example, by a CHAIN or SETLL operation) before a subsequent read operation can be done on that file.

If an update (on the calculation or output specifications) is done on the file specified in name immediately after a successful CHAIN operation to that file, the last record retrieved is updated.

See Database Null Value Support for information on handling records with null-capable fields and keys.

Note:
Operation code extenders H, M, and R are allowed only when the search argument is a list or is %KDS().

Figure 245. CHAIN Operation with a File Name


 *..1....+....2....+....3....+....4....+....5....+....6....+....7...+....

*
* The CHAIN operation retrieves the first record from the file,
* FILEX, that has a key field with the same value as the search
* argument KEY (factor 1).

/FREE
CHAIN KEY FILEX;
// If a record with a key value equal to the search argument is
// not found, %FOUND returns '0' and the EXSR operation is
// processed. If a record is found with a key value equal
// to the search argument, the program continues with
// the calculations after the EXSR operation.
IF NOT %FOUND;
EXSR Not_Found;
ENDIF;
/END-FREE

Figure 246. CHAIN Operation Using a List of Key Fields


FFilename++IPEASF.....L.....A.Device+.Keywords+++++++++++++++++++++++++

FCUSTFILE IF E K DISK
/free
// Specify the search keys directly in a list
chain ('abc' : 'AB') custrec;
// Expressions can be used in the list of keys
chain (%xlate(custname : LO : UP) : companyCode + partCode)
custrec;
return;

Figure 247. CHAIN Operation Using a Data Structure with an Externally-Described File


FFilename++IPEASF.....L.....A.Device+.Keywords+++++++++++++++++++++++++

FCUSTFILE IF E K DISK
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++
D custRecDs ds likerec(custRec)

/free
// Read the record directly into the data structure
chain ('abc' : 'AB') custRec custRecDs;
// Use the data structure fields
if (custRecDs.code = *BLANKS);
custRecDs.code = getCompanyCode (custRecDs);
update custRec custRecDs;
endif;


CHECK (Check Characters)


Free-Form Syntax (not allowed - use the %CHECK built-in function)

Code Factor 1 Factor 2 Result Field Indicators
CHECK (E) Comparator string Base string:start Left-
position
_ ER FD

The CHECK operation verifies that each character in the base string (factor 2) is among the characters indicated in the comparator string (factor 1). The base string and comparator string must be of the same type, either both character, both graphic, or both UCS-2. (Graphic and UCS-2 types must have the same CCSID value.) Verifying begins at the leftmost character of factor 2 and continues character by character, from left to right. Each character of the base string is compared with the characters of factor 1. If a match for a character in factor 2 exists in factor 1, the next base string character is verified. If a match is not found, an integer value is placed in the result field to indicate the position of the incorrect character.

You can specify a start position in factor 2, separating it from the base string by a colon. The start position is optional and defaults to 1. If the start position is greater than 1, the value in the result field is relative to the leftmost position in the base string, regardless of the start position.

The operation stops checking when it finds the first incorrect character or when the end of the base string is encountered. If no incorrect characters are found, the result field is set to zero.

If the result field is an array, the operation continues checking after the first incorrect character is found for as many occurrences as there are elements in the array. If there are more array elements than incorrect characters, all of the remaining elements are set to zeros.

Factor 1 must be a string, and can contain one of: a field name, array element, named constant, data structure name, data structure subfield, literal, or table name.

Factor 2 must contain either the base string or the base string, followed by a colon, followed by the start location. The base string portion of factor 2 can contain: a field name, array element, named constant, data-structure name, literal, or table name. The start location portion of factor 2 must be numeric with no decimal positions, and can be a named constant, array element, field name, literal, or table name. If no start location is specified, a value of 1 is used.

The result field can be a numeric variable, numeric array element, numeric table name, or numeric array. Define the field or array specified with no decimal positions. If graphic or UCS-2 data is used, the result field will contain double-byte character positions (that is, position 3, the 3rd double-byte character, will be character position 5).

Note:
Figurative constants cannot be used in the factor 1, factor 2, or result fields. No overlapping is allowed in a data structure for factor 1 and the result field or for factor 2 and the result field.

Any valid indicator can be specified in positions 7 to 11.

To handle CHECK exceptions (program status code 100), either the operation code extender 'E' or an error indicator ER can be specified, but not both. For more information on error handling, see Program Exception/Errors.

You can specify an indicator in positions 75-76 that is set on if any incorrect characters are found. This information can also be obtained from the %FOUND built-in function, which returns '1' if any incorrect characters are found.

Figure 248. CHECK Operation


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++
* In this example, the result will be N=6, because the start
* position is 2 and the first nonnumeric character found is the '.'.
* The %FOUND built-in function is set to return '1', because some
* nonnumeric characters were found.
*
D
D Digits C '0123456789'

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
C
C MOVE '$2000.' Salary
C Digits CHECK Salary:2 N
C IF %FOUND
C EXSR NonNumeric
C ENDIF

*
* Because factor 1 is a blank, CHECK indicates the position
* of the first nonblank character. If STRING contains ' th
* NUM will contain the value 4.
*
C
C ' ' CHECK String Num 2 0

Figure 249. CHECK Operation


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++
* The following example checks that FIELD contains only the letters
* A to J. As a result, ARRAY=(136000) after the CHECK operation.
* Indicator 90 turns on.
*
D
D Letter C 'ABCDEFGHIJ'
D

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
C
C MOVE '1A=BC*' Field 6
C Letter CHECK Field Array 90
C

*
* In the following example, because FIELD contains only the
* letters A to J, ARRAY=(000000). Indicator 90 turns off.
*
C
C MOVE 'FGFGFG' Field 6
C Letter CHECK Field Array 90
C

C

Figure 250. CHECK Operation with graphic data


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++
D
* The following example checks a DBCS field for valid graphic
* characters starting at graphic position 2 in the field.
D
* Value of Graffld is 'DDBBCCDD'.
* The value of num after the CHECK is 4, since this is the
* first character 'DD' which is not contained in the string.
D
D Graffld 4G INZ(G'oDDBBCCDDi')
D Num 5 0

D
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq.
C
C
C G'oAABBCCi' check Graffld:2 Num

CHECKR (Check Reverse)


Free-Form Syntax (not allowed - use the %CHECKR built-in function)

Code Factor 1 Factor 2 Result Field Indicators
CHECKR (E) Comparator string Base string:start Right-
position
_ ER FD

The CHECKR operation verifies that each character in the base string (factor 2) is among the characters indicated in the comparator string (factor 1). The base string and comparator string must be of the same type, either both character, both graphic, or both UCS-2. (Graphic and UCS-2 types must have the same CCSID value.) Verifying begins at the rightmost character of factor 2 and continues character by character, from right to left. Each character of the base string is compared with the characters of factor 1. If a match for a character in factor 2 exists in factor 1, the next source character is verified. If a match is not found, an integer value is placed in the result field to indicate the position of the incorrect character. Although checking is done from the right, the position placed in the result field will be relative to the left.

You can specify a start position in factor 2, separating it from the base string by a colon. The start position is optional and defaults to the length of the string. The value in the result field is relative to the leftmost position in the source string, regardless of the start position.

If the result field is not an array, the operation stops checking when it finds the first incorrect character or when the end of the base string is encountered. If no incorrect characters are found, the result field is set to zero.

If the result field is an array, the operation continues checking after the first incorrect character is found for as many occurrences as there are elements in the array. If there are more array elements than incorrect characters, all of the remaining elements are set to zeros.

Factor 1 must be a string and can contain one of: a field name, array element, named constant, data structure name, data structure subfield, literal, or table name.

Factor 2 must contain either the base string or the base string, followed by a colon, followed by the start location. The base string portion of factor 2 can contain: a field name, array element, named constant, data structure name, data structure subfield name, literal, or table name. The start location portion of factor 2 must be numeric with no decimal positions, and can be a named constant, array element, field name, literal, or table name. If no start location is specified, the length of the string is used.

The result field can be a numeric variable, numeric array element, numeric table name, or numeric array. Define the field or array specified with no decimal positions. If graphic or UCS-2 data is used, the result field will contain double-byte character positions (that is, position 3, the 3rd double-byte character, will be character position 5).

Note:
Figurative constants cannot be used in the factor 1, factor 2, or result fields. No overlapping is allowed in a data structure for factor 1 and the result field, or for factor 2 and the result field.

Any valid indicator can be specified in positions 7 to 11.

To handle CHECKR exceptions (program status code 100), either the operation code extender 'E' or an error indicator ER can be specified, but not both. For more information on error handling, see Program Exception/Errors.

You can specify an indicator in positions 75-76 that is set on if any incorrect characters are found. This information can also be obtained from the %FOUND built-in function, which returns '1' if any incorrect characters are found.

Figure 251. CHECKR Operation


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* Because factor 1 is a blank character, CHECKR indicates the
* position of the first nonblank character. This use of CHECKR
* allows you to determine the length of a string. If STRING
* contains 'ABCDEF ', NUM will contain the value 6.
* If an error occurs, %ERROR is set to return '1' and
* %STATUS is set to return status code 00100.
*
C
C ' ' CHECKR(E) String Num
C
C SELECT
C WHEN %ERROR
C ... an error occurred
C WHEN %FOUND
C ... NUM is less than the full length of the string
C ENDIF

Figure 252. CHECKR Operation


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++
*
* After the following example, N=1 and the found indicator 90
* is on. Because the start position is 5, the operation begins
* with the rightmost 0 and the first nonnumeric found is the '$'.
*
D Digits C '0123456789'
D
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
C
C MOVE '$2000.' Salary 6
C Digits CHECKR Salary:5 N 90
C

Figure 253. CHECKR Operation


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

*
* The following example checks that FIELD contains only the letters
* A to J. As a result, ARRAY=(876310) after the CHECKR operation.
* Indicator 90 turns on. %FOUND would return '1'.
D
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++
D Array S 1 DIM(6)
D Letter C 'ABCDEFGHIJ'
D

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
C
C MOVE '1A=BC***' Field 8
C Letter CHECKR Field Array 90
C


CLEAR (Clear)


Free-Form Syntax CLEAR {*NOKEY} {*ALL} name

Code Factor 1 Factor 2 Result Field Indicators
CLEAR *NOKEY *ALL name (variable or record format)


The CLEAR operation sets elements in a structure (record format, data structure, array, or table) or a variable (field, subfield, array element or indicator), to their default initialization value depending on field type (numeric, character, graphic, UCS-2, indicator, pointer, or date/time/timestamp). For the default initialization value for a data type, see Data Types and Data Formats.

Fully qualified names may be specified as the Result-Field operand for CLEAR when coded in free-form calculation specifications. If the structure or variable being cleared is variable-length, its length changes to 0. The CLEAR operation allows you to clear structures on a global basis, as well as element by element, during run time.

Clearing Variables

You cannot specify *NOKEY.

*ALL is optional. If *ALL is specified and the name operand is a multiple occurrence data structure or a table name, all occurrences or table elements are cleared and the occurrence level or table index is set to 1.

The name operand specifies the variable to be cleared. The particular entry in the name operand determines the clear action as follows:

Single occurrence data structure
All fields are cleared in the order in which they are declared within the structure.
Multiple-occurrence data structure
If *ALL is not specified, all fields in the current occurrence are cleared. If *ALL is specified, all fields in all occurrences are cleared.
Table name
If *ALL is not specified, the current table element is cleared. If *ALL is specified, all table elements are cleared.
Array name
Entire array is cleared
Array element (including indicators)
Only the element specified is cleared.

Clearing Record Formats

*NOKEY is optional. If *NOKEY is specified, then key fields are not cleared to their initial values.

*ALL is optional. If *ALL is specified and *NOKEY is not, all fields in the record format are cleared. If *ALL is not specified, only those fields that are output in that record format are affected. If *NOKEY is specified, then key fields are not cleared, even if *ALL is specified.

The name operand is the record format to be cleared. For WORKSTN file record formats (positions 36-42 on a file-description specification), if *ALL is not specified, only those fields with a usage of output or both are affected. All field-conditioning indicators of the record format are affected by the operation. When the RESET operation is applied to a record format name, and INDARA has been specified in the DDS, the indicators in the record format are not cleared.

Fields in DISK, SEQ, or PRINTER file record formats are affected only if the record format is output in the program. Input-only fields are not affected by the RESET operation, except when *ALL is specified.

A RESET operation of a record format with *ALL specified is not valid when:

  • A field is defined externally as input-only, and the record was not used for input.
  • A field is defined externally as output-only, and the record was not used for output.
  • A field is defined externally as both input and output capable, and the record was not used for either input or output.
Note:
Input-only fields in logical files will appear in the output specifications, although they are not actually written to the file. When a CLEAR or RESET without *NOKEY being specified is done to a record containing these fields, then these fields will be cleared or reset because they appear in the output specifications.

CLEAR Examples

  • Figure 254 shows an example of the CLEAR operation.
  • Figure 255 shows an example of the field initialization for the CLEAR record format.
  • The examples in RESET Examples also apply to CLEAR, except for the actual operation performed on the fields.

Figure 254. CLEAR Operation


 *..1....+....2....+....3....+....4....+....5....+....6....+....7...+....

D*Name++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++
D DS1 DS
D Num 2 5 0
D Char 20 30A
D
D MODS DS OCCURS(2)
D Fld1 1 5
D Fld2 6 10 0

* In the following example, CLEAR sets all subfields in the data
* structure DS1 to their defaults, CHAR to blank, NUM to zero.
/FREE
CLEAR DS1;
// In the following example, CLEAR sets all occurrences for the
// multiple occurrence data structure MODS to their default values
// Fld1 to blank, Fld2 to zero.
CLEAR *ALL MODS;
/END-FREE

Figure 255. Field Initialization for the CLEAR Record Format


 *..1....+....2....+....3....+....4....+....5....+....6....+....7...+....

A* Field2 and Field3 are defined as output capable fields and can be
A* affected by the CLEAR operation. Indicator 10 can also be
A* changed by the CLEAR operation even though it conditions an
A* input only field because field indicators are all treated
A* as output fields. The reason for this is that *ALL was not specifie
A* on the CLEAR operation
A*
A*N01N02N03T.Name++++++RLen++TDpBLinPosFunctions++++++++++++++++++++*
A R FMT01
A 10 Field1 10A I 2 30
A Field2 10A O 3 30
A Field3 10A B 4 30
A*
A* End of DDS source
A*

F*Flename++IPEASFRlen+LKlen+AIDevice+.Keywords+++++++++++++++++++++++++
FWORKSTN CF E WORKSTN INCLUDE(FMT01)
F
D*Name++++++++++ETDsFrom+++To/L+++IDc.Keywords++++++++++++++++++++++++
D IN C 'INPUT DATA'

/FREE
CLEAR FMT01;
WRITE FMT01;
// Loop until PF03 is pressed
DOW NOT *IN03;
READ FMT01;
*INLR = %EOF;
// PF04 will transfer input fields to output fields.
IF *IN04;
Field2 = Field3;
Field3 = Field1;
CLEAR *IN04;
ENDIF;
Field1 = IN;
// When PF11 is pressed, all the fields in the record format
// defined as output or both will be reset to the values they
// held after the initialization step.
IF *IN11;
RESET FMT01;
CLEAR *IN11;
ENDIF;
// When PF12 is pressed, all the fields in the record
// format defined as output or both will be cleared.
IF *IN12;
CLEAR FMT01;
CLEAR *IN12;
ENDIF;
IF NOT *IN03;
WRITE FMT01;
ENDIF;
ENDDO;
*INLR = *ON;
/END-FREE

CLOSE (Close Files)


Free-Form Syntax CLOSE{(E)} file-name|*ALL

Code Factor 1 Factor 2 Result Field Indicators
CLOSE (E)
file-name or *ALL
_ ER _

The explicit CLOSE operation closes one or more files or devices and disconnects them from the module. The file cannot be used again in the module unless you specify an explicit OPEN for that file. A CLOSE operation to an already closed file does not produce an error.

file-name names the file to be closed. You can specify the keyword *ALL to close all the files at once. You cannot specify an array or table file (identified by a T in position 18 of the file description specifications).

To handle CLOSE exceptions (file status codes greater than 1000), either the operation code extender 'E' or an error indicator ER can be specified, but not both. For more information on error handling, see File Exception/Errors.

Positions 71, 72, 75, and 76 must be blank.

If an array or table is to be written to an output file (specified using the TOFILE keyword) the array or table dump does not occur at LR time if the file is closed by a CLOSE operation). If the file is closed, it must be reopened for the dump to occur.

Figure 256. CLOSE Operation


 *..1....+....2....+....3....+....4....+....5....+....6....+....7...+....

* The explicit CLOSE operation closes FILEB.

/FREE
CLOSE FILEB;
// The CLOSE *ALL operation closes all files in the
// module. You must specify an explicit OPEN for any file that
// you wish to use again. If the CLOSE operation is not
// completed successfully, %ERROR returns '1'.
CLOSE(E) *ALL;
/END-FREE

COMMIT (Commit)


Free-Form Syntax COMMIT{(E)} {boundary}

Code Factor 1 Factor 2 Result Field Indicators
COMMIT (E) boundary

_ ER _

The COMMIT operation:

  • Makes all the changes to your files, opened for commitment control, that have been specified in output operations since the previous commit or rollback ROLBK (Roll Back) operation (or since the beginning of operations under commitment control if there has been no previous commit or rollback operation). You specify a file to be opened for commit by specifying the COMMIT keyword on the file specification.
  • Releases all the record locks for files you have under commitment control.

The file changes and the record-lock releases apply to all the files you have under commitment control, whether the changes have been requested by the program issuing the COMMIT operation, or by another program in the same activation group or job, dependent on the commit scope specified on the STRCMTCTL command. The program issuing the COMMIT operation does not need to have any files under commitment control. The COMMIT operation does not change the file position.

Commitment control starts when the CL command STRCMTCTL is executed. See the section on "Commitment Control" in the WebSphere Development Studio: ILE RPG Programmer's Guide for more information.

For the boundary operand, , you can specify a constant or variable (of any type except pointer) to identify the boundary between the changes made by this COMMIT operation and subsequent changes. If boundary is not specified, the identifier is null.

To handle COMMIT exceptions (program status codes 802 to 805), either the operation code extender 'E' or an error indicator ER can be specified, but not both. For example, an error occurs if commitment control is not active. For more information on error handling, see Program Exception/Errors.


COMP (Compare)


Free-Form Syntax (not allowed - use the =, <, >, <=, >=, or <> operator)

Code Factor 1 Factor 2 Result Field Indicators
COMP Comparand Comparand
HI LO EQ

The COMP operation compares factor 1 with factor 2. Factor 1 and factor 2 can contain a literal, a named constant, a field name, a table name, an array element, a data structure, or a figurative constant. Factor 1 and factor 2 must have the same data type. As a result of the comparison, indicators are set on as follows:

  • High: (71-72) Factor 1 is greater than factor 2.
  • Low: (73-74) Factor 1 is less than factor 2.
  • Equal: (75-76) Factor 1 equals factor 2.

You must specify at least one resulting indicator in positions 71 through 76. Do not specify the same indicator for all three conditions. When specified, the resulting indicators are set on or off (for each cycle) to reflect the results of the compare.

For further rules for the COMP operation, see Compare Operations.

Figure 257. COMP Operation


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* Initial field values are:
* FLDA = 100.00
* FLDB = 105.00
* FLDC = 100.00
* FLDD = ABC
* FLDE = ABCDE
*
* Indicator 12 is set on; indicators 11 and 13 are set off.
C FLDA COMP FLDB 111213
*
* Indicator 15 is set on; indicator 14 is set off.
C FLDA COMP FLDB 141515
*
* Indicator 18 is set on; indicator 17 is set off.
C FLDA COMP FLDC 171718
*
* Indicator 21 is set on; indicators 20 and 22 are set off
C FLDD COMP FLDE 202122

DEALLOC (Free Storage)


Free-Form Syntax DEALLOC{(EN)} pointer-name

Code Factor 1 Factor 2 Result Field Indicators
DEALLOC (E/N)

pointer-name _ ER _

The DEALLOC operation frees one previous allocation of heap storage. pointer-name is a pointer that must be the value previously set by a heap-storage allocation operation (either an ALLOC operation in RPG, or some other heap-storage allocation mechanism). It is not sufficient to simply point to heap storage; the pointer must be set to the beginning of an allocation.

The storage pointed to by the pointer is freed for subsequent allocation by this program or any other in the activation group.

If operation code extender N is specified, the pointer is set to *NULL after a successful deallocation.

To handle DEALLOC exceptions (program status code 426), either the operation code extender 'E' or an error indicator ER can be specified, but not both. The result field pointer will not be changed if an error occurs, even if 'N' is specified. For more information on error handling, see Program Exception/Errors.

pointer-name must be a basing pointer scalar variable (a standalone field, data structure subfield, table name or array element).

No error is given at runtime if the pointer is already *NULL.

For more information, see Memory Management Operations.

Figure 258. DEALLOC operation


 *..1....+....2....+....3....+....4....+....5....+....6....+....7...+....

D*Name++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++
*
D Ptr1 S *
D Fld1 S 1A
D BasedFld S 7A BASED(Ptr1)

/FREE
// 7 bytes of storage are allocated from the heap and
// Ptr1 is set to point to it
Ptr1 = %alloc (7);
// The DEALLOC frees the storage. This storage is now available
// for allocation by this program or any other program in the
// activation group. (Note that the next allocation may or
// may not get the same storage back).
dealloc Ptr1;
// Ptr1 still points at the deallocated storage, but this pointer
// should not be used with its current value. Any attempt to
// access BasedFld which is based on Ptr1 is invalid.
Ptr1 = %addr (Fld1);
// The DEALLOC is not valid because the pointer is set to the
// address of program storage. %ERROR is set to return '1',
// the program status is set to 00426 (%STATUS returns 00426),
// and the pointer is not changed.
dealloc(e) Ptr1;
// Allocate and deallocate storage again. Since operational
// extender N is specified, Ptr1 has the value *NULL after the
// DEALLOC.
Ptr1 = %alloc (7);
dealloc(n) Ptr1;
/END-FREE

DEFINE (Field Definition)


Free-Form Syntax (not allowed - use the LIKE or DTAARA keyword on the definition specification)

Code Factor 1 Factor 2 Result Field Indicators
DEFINE *LIKE Referenced field Defined field


DEFINE *DTAARA External data area Internal field


Depending on the factor 1 entry, the declarative DEFINE operation can do either of the following:

  • Define a field based on the attributes (length and decimal positions) of another field .
  • Define a field as a data area .

You can specify the DEFINE operation anywhere within calculations, although you cannot specify a *DTAARA DEFINE in a subprocedure or use it with a UCS-2 result field. The control level entry (positions 7 and 8) can be blank or can contain an L1 through L9 indicator, the LR indicator, or an L0 entry to group the statement within the appropriate section of the program. The control level entry is used for documentation only. Conditioning indicator entries (positions 9 through 11) are not permitted.

*LIKE DEFINE

The DEFINE (Field Definition) operation with *LIKE in factor 1 defines a field based upon the attributes (length and decimal positions) of another field.

Factor 2 must contain the name of the field being referenced, and the result field must contain the name of the field being defined. The field specified in factor 2, which can be defined in the program or externally, provides the attributes for the field being defined. Factor 2 cannot be a literal, a named constant, a float numeric field, or an object. If factor 2 is an array, an array element, or a table name, the attributes of an element of the array or table are used to define the field. The result field cannot be an array, an array element, a data structure, or a table name. Attributes such as ALTSEQ(*NO), NOOPT, ASCEND, CONST or null capability are not inherited from factor 2 by the result field. Only the data type, length, and decimal positions are inherited.

You can use positions 64 through 68 (field length) to make the result field entry longer or shorter than the factor 2 entry. A plus sign (+) preceding the number indicates a length increase; a minus sign (-) indicates a length decrease. Positions 65-68 can contain the increase or decrease in length (right-adjusted) or can be blank. If positions 64 through 68 are blank, the result field entry is defined with the same length as the factor 2 entry. You cannot change the number of decimal positions for the field being defined. The field length entry is allowed only for graphic, UCS-2, numeric, and character fields.

For graphic or UCS-2 fields the field length difference is calculated in double-byte characters.

If factor 2 is a graphic or UCS-2 field, the result field will be defined as the same type, that is, as graphic or UCS-2. The new field will have the default graphic or UCS-2 CCSID of the module. If you want the new field to have the same CCSID as the field in factor 2, use the LIKE keyword on a definition specification. The length adjustment is expressed in double bytes.

Figure 259. DEFINE Operation with *LIKE


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* FLDA is a 7-position character field.
* FLDB is a 5-digit field with 2 decimal positions.
*
*
* FLDP is a 7-position character field.
C *LIKE DEFINE FLDA FLDP
*
* FLDQ is a 9-position character field.
C *LIKE DEFINE FLDA FLDQ +2
*
* FLDR is a 6-position character field.
C *LIKE DEFINE FLDA FLDR - 1
*
* FLDS is a 5-position numeric field with 2 decimal positions.
C *LIKE DEFINE FLDB FLDS
*
* FLDT is a 6-position numeric field with 2 decimal positions.
C *LIKE DEFINE FLDB FLDT + 1
*
* FLDU is a 3-position numeric field with 2 decimal positions.
C *LIKE DEFINE FLDB FLDU - 2
*
* FLDX is a 3-position numeric field with 2 decimal positions.
C *LIKE DEFINE FLDU FLDX

Note the following for *LIKE DEFINE of numeric fields:

  • If the field is fully defined on Definition Specifications, the format is not changed by the *LIKE DEFINE.
  • Otherwise, if the field is a subfield of a data structure, it is defined in zoned format.
  • Otherwise, the field is defined in packed format.

Figure 260. Using *LIKE DEFINE


D            DS

D Fld1
D Fld2 S 7P 2

*
* Fld1 will be defined as zoned because it is a subfield of a
* data structure and numeric subfields default to zoned format.
*
C *LIKE DEFINE Fld2 Fld1
*
* Fld3 will be defined as packed because it is a standalone field
* and all numeric items except subfields default to packed format.
C *LIKE DEFINE Fld1 Fld3

*DTAARA DEFINE

The DEFINE (Field Definition) operation with *DTAARA in factor 1 associates a field, a data structure, a data-structure subfield, or a data-area data structure (within your ILE RPG program) with an AS/400 data area (outside your ILE RPG program).

Note:
You cannot use *DTAARA DEFINE within a subprocedure or with a UCS-2 result field.

In factor 2, specify the external name of a data area. Use *LDA for the name of the local data area or use *PDA for the Program Initialization Parameters (PIP) data area. If you leave factor 2 blank, the result field entry is both the RPG IV name and the external name of the data area.

In the result field, specify the name of one of the following that you have defined in your program: a field, a data structure, a data structure subfield, or a data-area data structure. You use this name with the IN and OUT operations to retrieve data from and write data to the data area specified in factor 2. When you specify a data-area data structure in the result field, the ILE RPG program implicitly retrieves data from the data area at program start and writes data to the data area when the program ends.

The result field entry must not be the name of a program-status data structure, a file-information data structure (INFDS), a multiple-occurrence data structure, an input record field, an array, an array element, or a table. It cannot be the name of a subfield of a multiple-occurrence data structure, of a data area data structure, of a program-status data structure, of a file-information data structure (INFDS), or of a data structure that already appears on a *DTAARA DEFINE statement, or has already been defined as a data area using the DTAARA keyword on a definition specification.

You can create three kinds of data areas:

  • *CHAR Character
  • *DEC Numeric
  • *LGL Logical

You can also create a DDM data area (type *DDM) that points to a data area on a remote system of one of the three types above.

Only character and numeric types (excluding float numeric) are allowed to be associated with data areas. The actual data area on the system must be of the same type as the field in the program, with the same length and decimal positions. Indicator fields can be associated with either a logical or character data area.

For numeric data areas, the maximum length is 24 digits with 9 decimal places. Note that there is a maximum of 15 digits to the left of the decimal place, even if the number of decimals is less than 9.

In positions 64 through 70, you can define the length and number of decimal positions for the entry in the result field. These specifications must match those for the external description of the data area specified in factor 2. The local data area is character data of length 1024, but within your program you can access the local data area as if it has a length of 1024 or less.

Figure 261. DEFINE Operation with *DTAARA


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* The attributes (length and decimal positions) of
* the data area (TOTGRS) must be the same as those for the
* external data area.
C
C *DTAARA DEFINE TOTGRS 10 2
C

*
* The result field entry (TOTNET) is the name of the data area to
* be used within the ILE RPG program. The factor 2 entry (TOTAL)
* is the name of the data area as defined to the system.
C
C *DTAARA DEFINE TOTAL TOTNET
C

*
* The result field entry (SAVTOT) is the name of the data area to
* be used within the ILE RPG program. The factor 2 entry (*LDA)
* indicates the use of the local data area.
C
C *DTAARA DEFINE *LDA SAVTOT


DELETE (Delete Record)


Free-Form Syntax DELETE{(EHMR)} {search-arg} name

Code Factor 1 Factor 2 Result Field Indicators
DELETE (E) search-arg name (file or record format)
NR ER _

The DELETE operation deletes a record from a database file. The file must be an update file (identified by a U in position 17 of the file description specifications) The deleted record can never be retrieved.

If a search argument (search-arg) is specified, the DELETE operation deletes the current record (the last record retrieved). The record must have been locked by a previous input operation (for example, CHAIN or READ).

The search argument, search-arg, must be the key or relative record number used to retrieve the record to be deleted. If access is by key, search-arg can be a single key in the form of a field name, a named constant, a figurative constant, or a literal.

If the file is an externally-described file, search-arg can also be a composite key in the form of a KLIST name, a list of values, or %KDS. Graphic and UCS-2 key fields must have the same CCSID as the key in the file. For an example of %KDS, see the example at the end of %KDS (Search Arguments in Data Structure). If access is by relative record number, search-arg must be an integer literal or a numeric field with zero decimal positions. For an example of using a list of values to search for the record to be deleted, see Figure 246.

The name operand must be the name of the update file or a record format in the file from which a record is to be deleted. A record format name is valid only with an externally described file. If search-arg is not specified, the record format name must be the name of the last record read from the file; otherwise, an error occurs.

If search-arg is specified, positions 71 and 72 can contain an indicator that is set on if the record to be deleted is not found in the file. If search-arg is not specified, leave these positions blank. This information can also be obtained from the %FOUND built-in function, which returns '0' if no record is found, and '1' if a record is found.

To handle DELETE exceptions (file status codes greater than 1000), either the operation code extender 'E' or an error indicator ER can be specified, but not both. For more information on error handling, see File Exception/Errors.

Under the OS/400 operating system, if a read operation is done on the file specified in file-name after a successful DELETE operation to that file, the next record after the deleted record is obtained.

See Database Null Value Support for information on handling records with null-capable fields and keys.

Notes:

  1. Operation code extenders H, M, and R are allowed only when the search argument is a list or is %KDS().
  2. Leave positions 75 and 76 blank.

DIV (Divide)


Free-Form Syntax (not allowed - use the / or /= operators, or the %DIV built-in function)

Code Factor 1 Factor 2 Result Field Indicators
DIV (H) Dividend Divisor Quotient + - Z

If factor 1 is specified, the DIV operation divides factor 1 by factor 2; otherwise, it divides the result field by factor 2. The quotient (result) is placed in the result field. If factor 1 is 0, the result of the divide operation is 0. Factor 2 cannot be 0. If it is, an error occurs and the RPG IVexception/error handling routine receives control. When factor 1 is not specified, the result field (dividend) is divided by factor 2 (divisor), and the result (quotient) is placed in the result field. Factor 1 and factor 2 must be numeric; each can contain one of: an array, array element, field, figurative constant, literal, named constant, subfield, or table name.

Any remainder resulting from the divide operation is lost unless the move remainder (MVR) operation is specified as the next operation. If you use conditioning indicators, you must ensure that the DIV operation is processed immediately before the MVR operation. If the MVR operation is processed before the DIV operation, undesirable results occur. If move remainder is the next operation, the result of the divide operation cannot be half-adjusted (rounded).

For further rules for the DIV operation, see Arithmetic Operations.

Figure 146 shows examples of the DIV operation.

Note:
The MVR operation cannot follow a DIV operation if any operand of the DIV operation is of float format. A float variable can, however, be specified as the result of operation code MVR.

DO (Do)


Free-Form Syntax (not allowed - use the FOR operation code)

Code Factor 1 Factor 2 Result Field Indicators
DO Starting value Limit value Index value


The DO operation begins a group of operations and indicates the number of times the group will be processed. To indicate the number of times the group of operations is to be processed, specify an index field, a starting value, and a limit value. An associated ENDDO statement marks the end of the group. For further information on DO groups, see Structured Programming Operations.

In factor 1, specify a starting value with zero decimal positions, using a numeric literal, named constant, or field name. If you do not specify factor 1, the starting value is 1.

In factor 2, specify the limit value with zero decimal positions, using a numeric field name, literal, or named constant. If you do not specify factor 2, the limit value is 1.

In the result field, specify a numeric field name that will contain the current index value. The result field must be large enough to contain the limit value plus the increment. If you do not specify an index field, one is generated for internal use. Any value in the index field is replaced by factor 1 when the DO operation begins.

Factor 2 of the associated ENDDO operation specifies the value to be added to the index field. It can be a numeric literal or a numeric field with no decimal positions. If it is blank, the value to be added to the index field is 1.

In addition to the DO operation itself, the conditioning indicators on the DO and ENDDO statements control the DO group. The conditioning indicators on the DO statement control whether or not the DO operation begins. These indicators are checked only once, at the beginning of the DO loop. The conditioning indicators on the associated ENDDO statement control whether or not the DO group is repeated another time. These indicators are checked at the end of each loop.

The DO operation follows these 7 steps:

  1. If the conditioning indicators on the DO statement line are satisfied, the DO operation is processed (step 2). If the indicators are not satisfied, control passes to the next operation to be processed following the associated ENDDO statement (step 7).
  2. The starting value (factor 1) is moved to the index field (result field) when the DO operation begins.
  3. If the index value is greater than the limit value, control passes to the calculation operation following the associated ENDDO statement (step 7). Otherwise, control passes to the first operation after the DO statement (step 4).
  4. Each of the operations in the DO group is processed.
  5. If the conditioning indicators on the ENDDO statement are not satisfied, control passes to the calculation operation following the associated ENDDO statement (step 7). Otherwise, the ENDDO operation is processed (step 6).
  6. The ENDDO operation is processed by adding the increment to the index field. Control passes to step 3. (Note that the conditioning indicators on the DO statement are not tested again (step 1) when control passes to step 3.)
  7. The statement after the ENDDO statement is processed when the conditioning indicators on the DO or ENDDO statements are not satisfied (step 1 or 5), or when the index value is greater than the limit value (step 3).

Remember the following when specifying the DO operation:

  • The index, increment, limit value, and indicators can be modified within the loop to affect the ending of the DO group.
  • A DO group cannot span both detail and total calculations.

See LEAVE (Leave a Do/For Group) and ITER (Iterate) for information on how those operations affect a DO operation.

See FOR (For) for information on performing iterative loops with free-form expressions for the initial, increment, and limit values.

Figure 262. DO Operation


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* The DO group is processed 10 times when indicator 17 is on;
* it stops running when the index value in field X, the result
* field, is greater than the limit value (10) in factor 2. When
* the DO group stops running, control passes to the operation
* immediately following the ENDDO operation. Because factor 1
* in the DO operation is not specified, the starting value is 1.
* Because factor 2 of the ENDDO operation is not specified, the
* incrementing value is 1.
C
C 17 DO 10 X 3 0
C :
C ENDDO

*
* The DO group can be processed 10 times. The DO group stops
* running when the index value in field X is greater than
* the limit value (20) in factor 2, or if indicator 50 is not on
* when the ENDDO operation is encountered. When indicator 50
* is not on, the ENDDO operation is not processed; therefore,
* control passes to the operation following the ENDDO operation.
* The starting value of 2 is specified in factor 1 of the DO
* operation, and the incrementing value of 2 is specified in
* factor 2 of the ENDDO operation.
*
C 2 DO 20 X 3 0
C :
C :
C :
C 50 ENDDO 2


DOU (Do Until)


Free-Form Syntax DOU{(MR)} indicator-expression

Code Factor 1 Extended Factor 2
DOU (M/R)
indicator-expression

The DOU operation code precedes a group of operations which you want to execute at least once and possibly more than once. Its function is similar to that of the DOUxx operation code. An associated ENDDO statement marks the end of the group. It differs in that the logical condition is expressed by an indicator valued expression (indicator-expression). The operations controlled by the DOU operation are performed until the expression in indicator-expression is true. For information on how operation extenders M and R are used, see Precision Rules for Numeric Operations.

For fixed-format syntax, level and conditioning indicators are valid. Factor 1 must be blank. Extended factor 2 contains the expression to be evaluated.

Figure 263. DOU Operation


 *..1....+....2....+....3....+....4....+....5....+....6....+....7...+....

/FREE
// In this example, the do loop will be repeated until the F3
// is pressed.
dou *inkc;
do_something();
enddo;
// The following do loop will be repeated until *In01 is on
// or until FIELD2 is greater than FIELD3
dou *in01 or (Field2 > Field3);
do_something_else ();
enddo;
// The following loop will be repeated until X is greater than
// the number of elements in Array
dou X > %elem (Array);
Total = Total + Array(x);
X = X + 1;
enddo;
/END-FREE

DOUxx (Do Until)


Free-Form Syntax (not allowed - use the DOU operation code)

Code Factor 1 Factor 2 Result Field Indicators
DOUxx Comparand Comparand



The DOUxx operation code precedes a group of operations which you want to execute at least once and possibly more than once. An associated ENDDO statement marks the end of the group. For further information on DO groups and the meaning of xx, see Structured Programming Operations.

Factor 1 and factor 2 must contain a literal, a named constant, a field name, a table name, an array element, a figurative constant, or a data structure name. Factor 1 and factor 2 must be the same data type.

On the DOUxx statement, you indicate a relationship xx. To specify a more complex condition, immediately follow the DOUxx statement with ANDxx or ORxx statements. The operations in the DOUxx group are processed once, and then the group is repeated until either:

  • the relationship exists between factor 1 and factor 2
  • the condition specified by a combined DOUxx, ANDxx, or ORxx operation exists

The group is always processed at least once even if the condition is true at the start of the group.

In addition to the DOUxx operation itself, the conditioning indicators on the DOUxx and ENDDO statements control the DOUxx group. The conditioning indicators on the DOUxx statement control whether or not the DOUxx operation begins. The conditioning indicators on the associated ENDDO statement can cause a DO loop to end prematurely.

The DOUxx operation follows these steps:

  1. If the conditioning indicators on the DOUxx statement line are satisfied, the DOUxx operation is processed (step 2). If the indicators are not satisfied, control passes to the next operation that can be processed following the associated ENDDO statement (step 6).
  2. The DOUxx operation is processed by passing control to the next operation that can be processed (step 3). The DOUxx operation does not compare factor 1 and factor 2 or test the specified condition at this point.
  3. Each of the operations in the DO group is processed.
  4. If the conditioning indicators on the ENDDO statement are not satisfied, control passes to the next calculation operation following the associated ENDDO statement (step 6). Otherwise, the ENDDO operation is processed (step 5).
  5. The ENDDO operation is processed by comparing factor 1 and factor 2 of the DOUxx operation or testing the condition specified by a combined operation. If the relationship xx exists between factor 1 and factor 2 or the specified condition exists, the DO group is finished and control passes to the next calculation operation after the ENDDO statement (step 6). If the relationship xx does not exist between factor 1 and factor 2 or the specified condition does not exist, the operations in the DO group are repeated (step 3).
  6. The statement after the ENDDO statement is processed when the conditioning indicators on the DOUxx or ENDDO statements are not satisfied (steps 1 or 4), or when the relationship xx between factor 1 and factor 2 or the specified condition exists at step 5.

See LEAVE (Leave a Do/For Group) and ITER (Iterate) for information on how those operations affect a DOUxx operation.

Figure 264. DOUxx Operations


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* The DOUEQ operation runs the operation within the DO group at
* least once.
C
C FLDA DOUEQ FLDB
C

*
* At the ENDDO operation, a test is processed to determine whether
* FLDA is equal to FLDB. If FLDA does not equal FLDB, the
* preceding operations are processed again. This loop continues
* processing until FLDA is equal to FLDB. When FLDA is equal to
* FLDB, the program branches to the operation immediately
* following the ENDDO operation.
C
C SUB 1 FLDA
C ENDDO
C

*
* The combined DOUEQ ANDEQ OREQ operation processes the operation
* within the DO group at least once.
C
C FLDA DOUEQ FLDB
C FLDC ANDEQ FLDD
C FLDE OREQ 100
C

*
* At the ENDDO operation, a test is processed to determine whether
* the specified condition, FLDA equal to FLDB and FLDC equal to
* FLDD, exists. If the condition exists, the program branches to
* the operation immediately following the ENDDO operation. There
* is no need to test the OREQ condition, FLDE equal to 100, if the
* DOUEQ and ANDEQ conditions are met. If the specified condition
* does not exist, the OREQ condition is tested. If the OREQ
* condition is met, the program branches to the operation
* immediately following the ENDDO. Otherwise, the operations
* following the OREQ operation are processed and then the program
* processes the conditional tests starting at the second DOUEQ
* operation. If neither the DOUEQ and ANDEQ condition nor the
* OREQ condition is met, the operations following the OREQ
* operation are processed again.
C
C SUB 1 FLDA
C ADD 1 FLDC
C ADD 5 FLDE
C ENDDO


DOW (Do While)


Free-Form Syntax DOW{(MR)} indicator-expression

Code Factor 1 Extended Factor 2
DOW (M/R)
indicator-expression

The DOW operation code precedes a group of operations which you want to process when a given condition exists. Its function is similar to that of the DOWxx operation code. An associated ENDDO statement marks the end of the group. It differs in that the logical condition is expressed by an indicator valued expression (indicator-expression). The operations controlled by the DOW operation are performed while the expression in indicator-expression is true. See Expressions for details on expressions. For information on how operation extenders M and R are used, see Precision Rules for Numeric Operations.

For fixed-format syntax, level and conditioning indicators are valid. Factor 1 must be blank. Factor 2 contains the expression to be evaluated.

Figure 265. DOW Operation


 *..1....+....2....+....3....+....4....+....5....+....6....+....7...+....

* In this example, the do loop will be repeated until the condition
* is false. That is when A > 5 or B+C are not equal to zero.

/FREE
dow (a <= 5) and (b + c = 0);
do_something (a:b:c);
enddo;
/END-FREE

DOWxx (Do While)


Free-Form Syntax (not allowed - use the DOW operation code)

Code Factor 1 Factor 2 Result Field Indicators
DOWxx Comparand Comparand



The DOWxx operation code precedes a group of operations which you want to process when a given condition exists. To specify a more complex condition, immediately follow the DOWxx statement with ANDxx or ORxx statements. An associated ENDDO statement marks the end of the group. For further information on DO groups and the meaning of xx, see Structured Programming Operations.

Factor 1 and factor 2 must contain a literal, a named constant, a figurative constant, a field name, a table name, an array element, or a data structure name. Factor 1 and factor 2 must be of the same data type. The comparison of factor 1 and factor 2 follows the same rules as those given for the compare operations. See Compare Operations.

In addition to the DOWxx operation itself, the conditioning indicators on the DOWxx and ENDDO statements control the DO group. The conditioning indicators on the DOWxx statement control whether or not the DOWxx operation is begun. The conditioning indicators on the associated ENDDO statement control whether the DOW group is repeated another time.

The DOWxx operation follows these steps:

  1. If the conditioning indicators on the DOWxx statement line are satisfied, the DOWxx operation is processed (step 2). If the indicators are not satisfied, control passes to the next operation to be processed following the associated ENDDO statement (step 6).
  2. The DOWxx operation is processed by comparing factor 1 and factor 2 or testing the condition specified by a combined DOWxx, ANDxx, or ORxx operation. If the relationship xx between factor 1 and factor 2 or the condition specified by a combined operation does not exist, the DO group is finished and control passes to the next calculation operation after the ENDDO statement (step 6). If the relationship xx between factor 1 and factor 2 or the condition specified by a combined operation exists, the operations in the DO group are repeated (step 3).
  3. Each of the operations in the DO group is processed.
  4. If the conditioning indicators on the ENDDO statement are not satisfied, control passes to the next operation to run following the associated ENDDO statement (step 6). Otherwise, the ENDDO operation is processed (step 5).
  5. The ENDDO operation is processed by passing control to the DOWxx operation (step 2). (Note that the conditioning indicators on the DOWxx statement are not tested again at step 1.)
  6. The statement after the ENDDO statement is processed when the conditioning indicators on the DOWxx or ENDDO statements are not satisfied (steps 1 or 4), or when the relationship xx between factor 1 and factor 2 of the specified condition does not exist at step 2.

See LEAVE (Leave a Do/For Group) and ITER (Iterate) for information on how those operations affect a DOWxx operation.

Figure 266. DOWxx Operations


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* The DOWLT operation allows the operation within the DO group
* to be processed only if FLDA is less than FLDB. If FLDA is
* not less than FLDB, the program branches to the operation
* immediately following the ENDDO operation. If FLDA is less
* than FLDB, the operation within the DO group is processed.
C
C FLDA DOWLT FLDB
C

*
* The ENDDO operation causes the program to branch to the first
* DOWLT operation where a test is made to determine whether FLDA
* is less than FLDB. This loop continues processing until FLDA
* is equal to or greater than FLDB; then the program branches
* to the operation immediately following the ENDDO operation.
C
C MULT 2.08 FLDA
C ENDDO
C

* In this example, multiple conditions are tested. The combined
* DOWLT ORLT operation allows the operation within the DO group
* to be processed only while FLDA is less than FLDB or FLDC. If
* neither specified condition exists, the program branches to
* the operation immediately following the ENDDO operation. If
* either of the specified conditions exists, the operation after
* the ORLT operation is processed.
C
C FLDA DOWLT FLDB
C FLDA ORLT FLDC
C

* The ENDDO operation causes the program to branch to the second
* DOWLT operation where a test determines whether specified
* conditions exist. This loop continues until FLDA is equal to
* or greater than FLDB and FLDC; then the program branches to the
* operation immediately following the ENDDO operation.
C
C MULT 2.08 FLDA
C ENDDO


DSPLY (Display Function)


Free-Form Syntax DSPLY{(E)} {message {output-queue {response}}}

Code Factor 1 Factor 2 Result Field Indicators
DSPLY (E) message output-queue response _ ER _

The DSPLY operation allows the program to communicate with the display work station that requested the program. Either message, response, or both operands must be specified. The operation can display a message and accept a response.

The value in the message operand and possibly the response operand are used to create the message to be displayed. message can be a field name, a literal, a named constant, a table name, or an array element whose value is used to create the message to be displayed. Within free-form calculations, the message operand can be an expression, provided the expression is enclosed by parentheses. The message operand can also be *M, followed by a message identifier that identifies the message to be retrieved from the message file, QUSERMSG. Use the OVRMSGF CL command to use a different message file. QUSERMSG must be in a library in the library list of the job receiving the message.

The message identifier must be 7 characters in length consisting 3 alphabetic characters and four numeric characters (for example, *MUSR0001, this means message USR0001 is used).

If specified, the output-queue operand can be a character field, a literal, a named constant, a table name, or an array element whose value is the symbolic name of the object meant to receive the message and from which the optional response can be sent. Any queue name, except a program message queue name, can be the value contained in the output-queue operand. The queue must be declared to the OS/400 system before it can be used during program execution. (For information on how to create a queue, see the CL Programming. There are two predefined queues:

Queue
Value
QSYSOPR
The message is sent to the system operator. Note that the QSYSOPR message queue severity level must be zero (00) to enable the DSPLY operation to immediately display a message to the system operator.
*EXT
The message is sent to the external message queue.
Note:
For a batch job, if no output-queue value is specified, the default is QSYSOPR. For an interactive job, the default value is *EXT.

The response operand is optional. If it is specified, the response is placed in it. response can be a field name, a table name, or an array element in which the response is placed. If no data is entered, response is unchanged. To specify a response but no output queue in a free-form specification, specify ' ' for output-queue.

Fully qualified names may be specified as the Result-Field operand, and expressions are allowed as Factor 1 and Factor 2 operands, when coded in free-form calculation specifications. However, if the operand is more complex than a fully qualified name, the expression must be enclosed in parentheses.

To handle DSPLY exceptions (program status code 333), either the operation code extender 'E' or an error indicator ER can be specified, but not both. The exception is handled by the specified method if an error occurs on the operation. For more information on error handling, see Program Exception/Errors.

When you specify the DSPLY operation with no message identifier in the message operand, the operation functions as follows:

  • If the message operand is specified but the response operand is not, the contents of the message operand are displayed. The program does not wait for a response unless a display file with the parameter RSTDSP (*NO) specified was used to display a format at the workstation. Then the program waits for the user to press Enter.
  • If the message operand is not specified but the response operand is, the contents of the response operand are displayed and the program waits for the user to enter data for the response. The reply is placed in the response operand.
  • When both message and response operands are specified,, their contents are combined and displayed. The program waits for the user to enter data for the response. The response is placed in the result field.
  • If you request help on the message, you can find the type and attributes of the data that is expected and the number of unsuccessful attempts that have been made.

    The maximum length of information that can be displayed is 52 bytes.

The format of the record written by the DSPLY operation with no message identifier specified by the message operand follows:

Figure 267. DSPLY Operation Record Format. 1The maximum length of information that can be displayed is 52 bytes.


When you specify the DSPLY operation with a message identifier in the message operand, the operation functions as follows: the message identified in the message operand is retrieved from QUSERMSG, the message is displayed, and the program waits for the user to respond by entering data if the response operand is specified. The response is placed in the result field.

When replying to a message, remember the following:

  • Non-float numeric fields sent to the display are right-adjusted and zero-suppressed.
  • If a non-float numeric field is entered with a length greater than the number of digits in the result field and the rightmost character is not a minus sign (-), an error is detected and a second wait occurs. The user must key in the field again.
  • A float value is entered in the external display representation. It can be no longer than 14 characters for 4-byte float fields, and no longer than 23 characters for 8-byte float fields.
  • If graphic, UCS-2, or character data is entered, the length must be equal or less than the receiving field length.
  • If the result field is variable-length, its length will be set to the length of the value that you enter.
  • If a date, time, or timestamp field is entered, the format and separator must match the format and separator of the result field. If the format or separator do not match, or the value is not valid (for example a date of 1999/99/99), an error is detected and a second wait occurs. The user must key in the field again.
  • The DSPLY operation allows the workstation user up to 5 attempts to respond to the message. After the fifth unsuccessful attemp, the DSPLY operation fails. If the DSPLY operation does not have a message identifier specified in the message operand, the user can request help on the message to find the type and attributes of the expected response.
  • To enter a null response to the system operator queue (QSYSOPR), the user must enter the characters *N and then press Enter.
  • Graphic, UCS-2, or character fields are padded on the right with blanks after all characters are entered.
  • UCS-2 fields are displayed and entered as single-byte characters.
  • Numeric fields are right-adjusted and padded on the left with zeros after all characters are entered.
  • Lowercase characters are not converted to uppercase.
  • If factor 1 or the result field is of graphic data type, they will be bracketed by SO/SI when displayed. The SO/SI will be stripped from the value to be assigned to the graphic result field on input.
  • Float fields are displayed in the external display representation. Float values can be entered as numeric literals or float literals. When entering a response, the float value does not have to be normalized.

Figure 268. DSPLY Operation Code Examples


   /free

// Display prompt and wait for response:
dsply prompt '' result;
// Display string constructed in an expression:
dsply ('Length of name is ' + %char(%len(str)) + ' bytes.');
/end-free


DUMP (Program Dump)


Free-Form Syntax DUMP{(A)} {identifier}

Code Factor 1 Factor 2 Result Field Indicators
DUMP (A) identifier




The DUMP operation provides a dump (all fields, all files, indicators, data structures, arrays, and tables defined) of the program. It can be used independently or in combination with the OS/400 testing and debugging functions. When the OPTIMIZE(*FULL) compiler option is selected on either the CRTBNDRPG or CRTRPGMOD command or as a keyword on a control specification, the field values shown in the dump may not reflect the actual content due to the effects of optimization.

If the DBGVIEW(*NONE) compiler option is specified, the dump will only show the program status data structure, the file information data structures, and the *IN indicators. Other variables will not have their contents shown because the object does not contain the necessary observability information.

If the DEBUG(*NO) control-specification keyword is specified, no dump is performed. You can override this keyword by specifying operation extender A. This operation extender means that a dump is always performed, regardless of the value of the DEBUG keyword.

The contents of the optional identifier operand identify the DUMP operation. It will replace the default heading on the dump listing if specified. It must contain a character or graphic entry that can be one of: a field name, literal, named constant, table name, or array element whose contents identify the dump. If the identifier operand is a graphic entry, it is limited to 64 double byte characters. identifier cannot be a figurative constant.

The program continues processing the next calculation statement following the DUMP operation.

The DUMP operation is performed if the DEBUG keyword is specified on the control specification, or the A operation extender is coded for the DUMP operation. Otherwise, the DUMP operation is checked for errors and the statement is printed on the listing, but the DUMP operation is not processed.

When dumping files, the DUMP will dump the File Feedback Information section of the INFDS, but not the Open Feedback Information or the Input/Output Feedback Information sections of the INFDS. DUMP will instead dump the actual Open Feedback, and Device Feedback Information for the file.

Note that if the INFDS you have declared is not large enough to contain the Open Feedback, or Input/Output Feedback Information, then you do not have to worry about doing a POST before DUMP since the File Feedback Information in the INFDS is always up to date.

The values of variables in subprocedures may not be valid if the subprocedure is not active. If a subprocedure has been called recursively, the values from the most recent invocation are shown.

Java object variables may not show the expected value. The RPG module may retain the reference to an object after the object no longer exists; it is possible for an object reference to be reused, and refer to a different object that is unrelated to the RPG module being dumped. That different object is the one that will appear in the formatted dump.

For an sample dump listing, see the chapter on obtaining dumps in the WebSphere Development Studio: ILE RPG Programmer's Guide.


ELSE (Else)


Free-Form Syntax ELSE

Code Factor 1 Factor 2 Result Field Indicators
ELSE





The ELSE operation is an optional part of the IFxx and IF operations. If the IFxx comparison is met, the calculations before ELSE are processed; otherwise, the calculations after ELSE are processed.

Within total calculations, the control level entry (positions 7 and 8) can be blank or can contain an L1 through L9 indicator, an LR indicator, or an L0 entry to group the statement within the appropriate section of the program. The control level entry is for documentation purposes only. Conditioning indicator entries (positions 9 through 11) are not permitted. To close the IFxx/ELSE group use an ENDIF operation.

Figure 278 shows an example of an ELSE operation with an IFxx operation.


ELSEIF (Else If)


Free-Form Syntax ELSEIF{(MR)} indicator-expression

Code Factor 1 Extended Factor 2
ELSEIF (M/R) Blank indicator-expression

The ELSE operation is the combination of an ELSE operation and an IF operation. It avoids the need for an additional level of nesting.

The IF operation code allows a series of operation codes to be processed if a condition is met. Its function is similar to that of the IFxx operation code. It differs in that the logical condition is expressed by an indicator valued expression (indicator-expression). The operations controlled by the ELSEIF operation are performed when the expression in the indicator-expression operand is true (and the expression for the previous IF or ELSEIF statement was false).

For information on how operation extenders M and R are used, see Precision Rules for Numeric Operations.

Figure 269. ELSEIF Operation


 *..1....+....2....+....3....+....4....+....5....+....6....+....7...+....

/free

IF keyPressed = HELPKEY;
displayHelp();
ELSEIF keyPressed = EXITKEY;
return;
ELSEIF keyPressed = ROLLUP OR keyPressed = ROLLDOWN;
scroll (keyPressed);
ELSE;
signalError ('Key not defined');
ENDIF;

/end-free

ENDyy (End a Structured Group)


Free-Form Syntax ENDDO
ENDFOR
ENDIF
ENDMON
ENDSL
(END and ENDCS not allowed)

Code Factor 1 Factor 2 Result Field Indicators
END
increment-value



ENDCS





ENDDO
increment- value



ENDFOR





ENDIF





ENDMON





ENDSL





The ENDyy operation ends a CASxx, DO, DOU, DOW, DOUxx, DOWxx, FOR, IF, IFxx, MONITOR, or SELECT group of operations.

The ENDyy operations are listed below:

END
End a CASxx, DO, DOU, DOUxx, DOW, DOWxx, FOR, IF, IFxx, or SELECT group
ENDCS
End a CASxx group
ENDDO
End a DO, DOU, DOUxx, DOW, or DOWxx group
ENDFOR
End a FOR group
ENDIF
End an IF or IFxx group
ENDMON
End a MONITOR group
ENDSL
End a SELECT group

The increment- value operand is allowed only on an ENDyy operation that delimits a DO group. It contains the incrementing value of the DO group. It can be positive or negative, must have zero decimal positions, and can be one of: an array element, table name, data structure, field, named constant, or numeric literal. If increment- value is not specified on the ENDDO, the increment defaults to 1. If increment- value is negative, the DO group will never end.

Conditioning indicators are optional for ENDDO or ENDFOR and not allowed for ENDCS, ENDIF, ENDMON, and ENDSL.

Resulting indicators are not allowed. No operands are allowed for ENDCS, ENDIF, ENDMON, and ENDSL.

If one ENDyy form is used with a different operation group (for example, ENDIF with a structured group), an error results at compilation time.

See the CASxx, DO, DOUxx, DOWxx, FOR, IFxx, and DOU, DOW, IF, MONITOR, and SELECT operations for examples that use the ENDyy operation.


ENDSR (End of Subroutine)


Free-Form Syntax ENDSR {return-point}

Code Factor 1 Factor 2 Result Field Indicators
ENDSR label return-point



The ENDSR operation defines the end of an RPG IV subroutine and the return point (return-point) to the main program. ENDSR must be the last statement in the subroutine. In traditional syntax, the label operand can be specified as a point to which a GOTO operation within the subroutine can branch. (You cannot specify a label in free-form syntax.) The control level entry (positions 7 and 8) can be SR or blank. Conditioning indicator entries are not allowed.

The ENDSR operation ends a subroutine and causes a branch back to the statement immediately following the EXSR or CASxx operation unless the subroutine is a program exception/error subroutine (*PSSR) or a file exception/error subroutine (INFSR). For these subroutines, the return-point operand of the ENDSR operation can contain an entry that specifies where control is to be returned following processing of the subroutine. This entry can be a field name that contains a reserved keyword or a literal or named constant that is a reserved keyword. If a return point that is not valid is specified, the RPG IV error handler receives control.

Note:
The return-point operand cannot be specified for an ENDSR operation that occurs within a subprocedure.

See File Exception/Error Subroutine (INFSR) for more detail on return points.

See Figure 156 for an example of coding an RPG IV subroutine.


EVAL (Evaluate expression)


Free-Form Syntax {EVAL{(HMR)}} result = expression
{EVAL{(HMR)}} result += expression
{EVAL{(HMR)}} result -= expression
{EVAL{(HMR)}} result *= expression
{EVAL{(HMR)}} result /= expression
{EVAL{(HMR)}} result **= expression

Code Factor 1 Extended Factor 2
EVAL (H M/R)
Assignment Statement

The EVAL operation code evaluates an assignment statement of the form "result = expression" or "result op = expression". The expression is evaluated and the result placed in result. Therefore, result cannot be a literal or constant but must be a field name, array name, array element, data structure, data structure subfield, or a string using the %SUBST built-in function.

The expression may yield any of the RPG data types. The type of the expression must be the same as the type of the result. A character, graphic, or UCS-2 result will be left justified and padded with blanks on the right or truncated as required. If result is a variable-length field, its length will be set to the length of the result of the expression.

If the result represents an unindexed array or an array specified as array(*), the value of the expression is assigned to each element of the result, according to the rules described in Specifying an Array in Calculations. Otherwise, the expression is evaluated once and the value is placed into each element of the array or sub-array. For numeric expressions, the half-adjust operation code extender is allowed. The rules for half adjusting are equivalent to those for the arithmetic operations.

On a free-form calculation specification, the operation code name may be omitted if no extenders are needed.

For the assignment operators +=, -=, *=, /=, and **=, the appropriate operation is applied to the result and the expression, and the result is assigned to the result. For example, statement X+=Y is roughly equivalent to X=X+Y. The difference between the two statements is that for these assignment operators, the result operand is evaluated only once. This difference is significant when the evaluation of the result operation involves a call to a subprocedure which has side-effects, for example:

     warnings(getNextCustId(OVERDRAWN)) += 1;

See Expressions for general information on expressions. See Precision Rules for Numeric Operations for information on precision rules for numeric expressions. This is especially important if the expression contains any divide operations, or if the EVAL uses any of the operation extenders.

Figure 270. EVAL Operations


 *..1....+....2....+....3....+....4....+....5....+....6....+....7...+....

* Assume FIELD1 = 10
* FIELD2 = 9
* FIELD3 = 8
* FIELD4 = 7
* ARR is defined with DIM(10)
* *IN01 = *ON
* A = 'abcdefghijklmno' (define as 15 long)
* CHARFIELD1 = 'There' (define as 5 long)

/FREE
// The content of RESULT after the operation is 20
eval RESULT=FIELD1 + FIELD2+(FIELD3-FIELD4);
// The indicator *IN03 will be set to *ON
*IN03 = *IN01 OR (FIELD2 > FIELD3);
// Each element of array ARR will be assigned the value 72
ARR(*) = FIELD2 * FIELD3;
// After the operation, the content of A = 'Hello There '
A = 'Hello ' + CHARFIELD1;
// After the operation the content of A = 'HelloThere '
A = %TRIMR('Hello ') + %TRIML(CHARFIELD1);
// Date in assignment
ISODATE = DMYDATE;
// Relational expression
// After the operation the value of *IN03 = *ON
*IN03 = FIELD3 <>
// Date in Relational expression
// After the operation, *IN05 will be set to *ON if Date1 represents
// a date that is later that the date in Date2
*IN05 = Date1 > Date2;
// After the EVAL the original value of A contains 'ab****ghijklmno'
%SUBST(A(3:4))= '****';
// After the EVAL PTR has the address of variable CHARFIELD1
PTR = %ADDR(CHARFIELD1);
// An example to show that the result of a logical expression is
// compatible with the character data type.
// The following EVAL statement consisting of 3 logical expressions
// whose results are concatenated using the '+' operator
// The resulting value of the character field RES is '010'
RES = (FIELD1<10)>= 17);
// An example of calling a user-defined function using EVAL.
// The procedure FormatDate converts a date field into a character
// string, and returns that string. In this EVAL statement, the
// field DateStrng1 is assigned the output of formatdate.
DateStrng1 = FormatDate(Date1);
// Subtract value in complex data structure.
cust(custno).account(accnum).balance -= purchase_amount;
// Add days and months to a date
DATE += %DAYS(12) + %MONTHS(3);
// Append characters to varying length character variable
line += '
';

/END-FREE

EVALR (Evaluate expression, right adjust)


Free-Form Syntax EVALR{(MR)} result = expression

Code Factor 1 Extended Factor 2
EVALR (M/R)
Assignment Statement

The EVALR operation code evaluates an assignment statement of the form result=expression. The expression is evaluated and the result is placed right-adjusted in the result. Therefore, the result cannot be a literal or constant, but must be a fixed-length character, graphic, or UCS-2 field name, array name, array element, data structure, data structure subfield, or a string using the %SUBST built-in function. The type of the expression must be the same as the type of the result. The result will be right justified and padded with blanks on the left, or truncated on the left as required.

Note:
Unlike the EVAL operation, the result of EVALR can only be of type character, graphic, or UCS-2. In addition, only fixed length result fields are allowed, although %SUBST can contain a variable length field if this built-in function forms the lefthand part of the expression.

If the result represents an unindexed array or an array specified as array(*), the value of the expression is assigned to each element of the result, according to the rules described in Specifying an Array in Calculations. Otherwise, the expression is evaluated once and the value is placed into each element of the array or sub-array.

See Expressions for general information on expressions. See Precision Rules for Numeric Operations for information on precision rules for numeric expressions. This is especially important if the expression contains any divide operations, or if the EVALR uses any of the operation extenders.

Figure 271. EVALR Operations


 *..1....+....2....+....3....+....4....+....5....+....6....+....7...+....

D*Name++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++
D Name S 20A

/FREE
eval Name = 'Kurt Weill';
// Name is now 'Kurt Weill '
evalr Name = 'Johann Strauss';
// Name is now ' Johann Strauss'
evalr %SUBST(Name:1:12) = 'Richard';
// Name is now ' Richard Strauss'
eval Name = 'Wolfgang Amadeus Mozart';
// Name is now 'Wolfgang Amadeus Moz'
evalr Name = 'Wolfgang Amadeus Mozart';
// Name is now 'fgang Amadeus Mozart'
/END-FREE

EXCEPT (Calculation Time Output)


Free-Form Syntax EXCEPT {except-name}

Code Factor 1 Factor 2 Result Field Indicators
EXCEPT
except-name



The EXCEPT operation allows one or more records to be written during either detail calculations or total calculations. See Figure 272 for examples of the EXCEPT operation.

When specifying the EXCEPT operation remember:

  • The exception records that are to be written during calculation time are indicated by an E in position 17 of the output specifications. An EXCEPT name, which is the same name as specified by the except-name operand of an EXCEPT operation, can be specified in positions 30 through 39 of the output specifications of the exception records.
  • Only exception records, not heading, detail, or total records, can contain an EXCEPT name.
  • When the EXCEPT operation with a name specified in the except-name operand is processed, only those exception records with the same EXCEPT name are checked and written if the conditioning indicators are satisfied.
  • When no except-name is specified, only those exception records with no name in positions 30 through 39 of the output specifications are checked and written if the conditioning indicators are satisfied.
  • If an exception record is conditioned by an overflow indicator on the output specification, the record is written only during the overflow portion of the RPG IV cycle or during fetch overflow. The record is not written at the time the EXCEPT operation is processed.
  • If an exception output is specified to a format that contains no fields, the following occurs:
    • If an output file is specified, a record is written with default values.
    • If a record is locked, the system treats the operation as a request to unlock the record. This is the alternative form of requesting an unlock. The preferred method is with the UNLOCK operation.

Figure 272. EXCEPT Operation with/without Factor 2 Specified


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* When the EXCEPT operation with HDG specified in factor 2 is
* processed, all exception records with the EXCEPT name HDG are
* written. In this example, UDATE and PAGE would be printed
* and then the printer would space 2 lines.
* The second HDG record would print a line of dots and then the
* printer would space 3 lines.
*
C EXCEPT HDG
*
* When the EXCEPT operation with no entry in factor 2 is
* processed, all exception records that do not have an EXCEPT
* name specified in positions 30 through 39 are written if the
* conditioning indicators are satisfied. Any exception records
* without conditioning indicators and without an EXCEPT name
* are always written by an EXCEPT operation with no entry in
* factor 2. In this example, if indicator 10 is on, TITLE and
* AUTH would be printed and then the printer would space 1 line.
*
C EXCEPT
O*
OFilename++DF..N01N02N03Excnam++++B++A++Sb+Sa+.............................
O..............N01N02N03Field+++++++++YB.End++PConstant/editword/DTformat++
O
O E 10 1
O TITLE
O AUTH
O E HDG 2
O UDATE
O PAGE
O E HDG 3
O '...............'
O '...............'
O E DETAIL 1
O AUTH
O VERSNO


EXFMT (Write/Then Read Format)


Free-Form Syntax EXFMT{(E)} format-name

Code Factor 1 Factor 2 Result Field Indicators
EXFMT (E)
format-name
_ ER _

The EXFMT operation is a combination of a WRITE followed by a READ to the same record format. EXFMT is valid only for a WORKSTN file defined as a full procedural (F in position 18 of the file description specifications) combined file (C in position 17 of the file description specifications) that is externally described (E in position 22 of the file description specifications)

The format-name operand must be the name of the record format to be written and then read.

To handle EXFMT exceptions (file status codes greater than 1000), either the operation code extender 'E' or an error indicator ER can be specified, but not both. When an error occurs, the read portion of the operation is not processed (record-identifying indicators and fields are not modified). For more information on error handling, see File Exception/Errors.

Positions 71, 72, 75, and 76 must be blank.

For the use of EXFMT with multiple device files, see the descriptions of the READ (by format name) and WRITE operations.

Figure 273. EXFMT Operation


 *..1....+....2....+....3....+....4....+....5....+....6....+....7...+....

F*Flename++IPEASFRLen+LKlen+AIDevice+.Keywords+++++++++++++++++++++++++
*
* PROMTD is a WORKSTN file which prompts the user for an option.
* Based on what user enters, this program executes different
* subroutines to add, delete, or change a record.
*
FPROMTD CF E WORKSTN

/free
// If user enters F3 function key, indicator *IN03 is set
// on and the do while loop is exited.
dow not *in03;
// EXFMT writes out the prompt to the screen and expects user to
// enter an option. SCR1 is a record format name defined in the
// WORKSTN file and OPT is a field defined in the record.
exfmt SCR1;
select;
when opt = 'A';
exsr AddRec;
when opt = 'D';
exsr DelRec;
when opt = 'C';
exsr ChgRec;
endsl;
enddo;
do_something ();
do_more_stuff ();
/end-free

EXSR (Invoke Subroutine)


Free-Form Syntax EXSR subroutine-name

Code Factor 1 Factor 2 Result Field Indicators
EXSR
subroutine-name



The EXSR operation causes the RPG IV subroutine named in the subroutine-name operand to be processed. The subroutine name must be a unique symbolic name and must appear as the subroutine-name operand of a BEGSR operation. The EXSR operation can appear anywhere in the calculation specifications. Whenever it appears, the subroutine that is named is processed. After operations in the subroutine are processed, the statement following the EXSR operation is processed, except when a GOTO within the subroutine is given to a label outside the subroutine or when the subroutine is an exception/error subroutine specified by the return-point operand of the ENDSR operation.

*PSSR used in the subroutine-name operand specifies that the program exception/error subroutine is to be processed. *INZSR used in the subroutine-name operand specifies that the program initialization subroutine is to be processed.

See Coding Subroutines for more information.


EXTRCT (Extract Date/Time/Timestamp)


Free-Form Syntax (not allowed - use the %SUBDT built-in function)

Code Factor 1 Factor 2 Result Field Indicators
EXTRCT (E)
Date/Time: Duration Code Target _ ER _

The EXTRCT operation code will return one of:

  • The year, month or day part of a date or timestamp field
  • The hours, minutes or seconds part of a time or timestamp field
  • The microseconds part of the timestamp field

to the field specified in the result field.

The Date, Time or Timestamp from which the information is required, is specified in factor 2, followed by the duration code. The entry specified in factor 2 can be a field, subfield, table element, or array element. The duration code must be consistent with the Data type of factor 2. See Date Operations for valid duration codes.

Factor 1 must be blank.

The result field can be any numeric or character field, subfield, array/table element. The result field is cleared before the extracted data is assigned. For a character result field, the data is put left adjusted into the result field.

Note:
When using the EXTRCT operation with a Julian Date (format *JUL), specifying a duration code of *D will return the day of the month, specifying *M will return the month of the year. If you require the day and month to be in the 3-digit format, you can use a basing pointer to obtain it. See Figure 94 for an example of obtaining the Julian format.

To handle EXTRCT exceptions (program status code 112), either the operation code extender 'E' or an error indicator ER can be specified, but not both. For more information on error handling, see Program Exception/Errors.

Figure 274. EXTRCT Operation


     D LOGONDATE       S               D

D DATE_STR S 15
D MONTHS S 8 DIM(12) CTDATA

C*0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
* Move the job date to LOGONDATE. By default, LOGONDATE has an *ISO
* date format, which contains a 4-digit year. *DATE also contains a
* 4-digit year, but in a different format, *USA.
C *USA MOVE *DATE LOGONDATE
*
* Extract the month from a date field to a 2-digit field
* that is used as an index into a character array containing
* the names of the months. Then extract the day from the
* timestamp to a 2-byte character field which can be used in
* an EVAL concatenation expression to form a string.
* For example, if LOGONDATE is March 17, 1996, LOGMONTH will
* contain 03, LOGDAY will contain 17, and DATE_STR will contain
* 'March 17'.
C EXTRCT LOGONDATE:*M LOGMONTH 2 0
C EXTRCT LOGONDATE:*D LOGDAY 2
C EVAL DATE_STR = %TRIMR(MONTHS(LOGMONTH))
C + ' ' + LOGDAY
C SETON LR
** CTDATA MONTHS
January
February
March
April
May
June
July
August
September
October
November
December


FEOD (Force End of Data)


Free-Form Syntax FEOD{(EN)} file-name

Code Factor 1 Factor 2 Result Field Indicators
FEOD (EN)
file-name
_ ER _

The FEOD operation signals the logical end of data for a primary, secondary, or full procedural file. The FEOD function differs, depending on the file type and device. (For an explanation of how FEOD differs per file type and device, see the iSeries Information Center database and file systems category).

FEOD differs from the CLOSE operation: the program is not disconnected from the device or file; the file can be used again for subsequent file operations without an explicit OPEN operation being specified to the file.

You can specify conditioning indicators. The file-name operand names the file to which FEOD is specified.

Operation extender N may be specified for an FEOD to an output-capable DISK or SEQ file that uses blocking (see Blocking Considerations). If operation extender N is specified, any unwritten records in the block will be written out to the database, but they will not necessarily be written to non-volatile storage. Using the N extender can improve performance.

To handle FEOD exceptions (file status codes greater than 1000), either the operation code extender 'E' or an error indicator ER can be specified, but not both. For more information on error handling, see File Exception/Errors.

To process any further sequential operations to the file after the FEOD operation (for example, READ or READP), you must reposition the file.


FOR (For)


Free-Form Syntax FOR{(MR)} index-name {= start-value} {BY increment} {TO|DOWNTO limit}

Code Factor 1 Extended Factor 2
FOR
index-name = start-value BY increment TO | DOWNTO limit

The FOR operation begins a group of operations and controls the number of times the group will be processed. To indicate the number of times the group of operations is to be processed, specify an index name, a starting value, an increment value, and a limit value. The optional starting, increment, and limit values can be a free-form expressions. An associated END or ENDFOR statement marks the end of the group. For further information on FOR groups, see Structured Programming Operations.

The syntax of the FOR operation is as follows:

      FOR         index-name { = starting-value }

{ BY increment-value }
{ TO | DOWNTO limit-value }
{ loop body }
ENDFOR | END

The starting-value, increment-value, and limit-value can be numeric values or expressions with zero decimal positions. The increment value, if specified, cannot be zero.

The BY and TO (or DOWNTO) clauses can be specified in either order. Both "BY 2 TO 10" and "TO 10 BY 2" are allowed.

In addition to the FOR operation itself, the conditioning indicators on the FOR and ENDFOR (or END) statements control the FOR group. The conditioning indicators on the FOR statement control whether or not the FOR operation begins. These indicators are checked only once, at the beginning of the for loop. The conditioning indicators on the associated END or ENDFOR statement control whether or not the FOR group is repeated another time. These indicators are checked at the end of each loop.

The FOR operation is performed as follows:

  1. If the conditioning indicators on the FOR statement line are satisfied, the FOR operation is processed (step 2). If the indicators are not satisfied, control passes to the next operation to be processed following the associated END or ENDFOR statement (step 8).
  2. If specified, the initial value is assigned to the index name. Otherwise, the index name retains the same value it had before the start of the loop.
  3. If specified, the limit value is evaluated and compared to the index name. If no limit value is specified, the loop repeats indefinitely until it encounters a statement that exits the loop (such as a LEAVE or GOTO) or that ends the program or procedure (such as a RETURN).

    If the TO clause is specified and the index name value is greater than the limit value, control passes to the first statement following the ENDFOR statement. If DOWNTO is specified and the index name is less than the limit value, control passes to the first statement after the ENDFOR.

  4. The operations in the FOR group are processed.
  5. If the conditioning indicators on the END or ENDFOR statement are not satisfied, control passes to the statement after the associated END or ENDFOR and the loop ends.
  6. If the increment value is specified, it is evaluated. Otherwise, it defaults to 1.
  7. The increment value is either added to (for TO) or subtracted from (for DOWNTO) the index name. Control passes to step 3. (Note that the conditioning indicators on the FOR statement are not tested again (step 1) when control passes to step 3.)
  8. The statement after the END or ENDFOR statement is processed when the conditioning indicators on the FOR, END, or ENDFOR statements are not satisfied (step 1 or 5), or when the index value is greater than (for TO) or less than (for DOWNTO) the limit value (step 3), or when the index value overflows.
Note:
If the FOR loop is performed n times, the limit value is evaluated n+1 times and the increment value is evaluated n times. This can be important if the limit value or increment value is complex and time-consuming to evaluate, or if the limit value or increment value contains calls to subprocedures with side-effects. If multiple evaluation of the limit or increment is not desired, calculate the values in temporaries before the FOR loop and use the temporaries in the FOR loop.

Remember the following when specifying the FOR operation:

  • The index name cannot be declared on the FOR operation. Variables should be declared in the Definition specifications.
  • The index-name can be any fully-qualified name, including an indexed array element.

See LEAVE (Leave a Do/For Group) and ITER (Iterate) for information on how those operations affect a FOR operation.

Figure 275. Examples of the FOR Operation


 *..1....+....2....+....3....+....4....+....5....+....6....+....7...+....

/free
// Example 1
// Compute n!
factorial = 1;
for i = 1 to n;
factorial = factorial * i;
endfor;
// Example 2
// Search for the last nonblank character in a field.
// If the field is all blanks, "i" will be zero.
// Otherwise, "i" will be the position of nonblank.
for i = %len (field) downto 1;
if %subst(field: i: 1) <> ' ';
leave;
endif;
endfor;
// Example 3
// Extract all blank-delimited words from a sentence.
WordCnt = 0;
for i = 1 by WordIncr to %len (Sentence);
// Is there a blank?
if %subst(Sentence: i: 1) = ' ';
WordIncr = 1;
iter;
endif;
// We've found a word - determine its length:
for j = i+1 to %len(Sentence);
if %subst (Sentence: j: 1) = ' ';
leave;
endif;
endfor;
// Store the word:
WordIncr = j - i;
WordCnt = WordCnt + 1;
Word (WordCnt) = %subst (Sentence: i: WordIncr);
endfor;
/end-free

FORCE (Force a Certain File to Be Read Next Cycle)


Free-Form Syntax FORCE file-name

Code Factor 1 Factor 2 Result Field Indicators
FORCE
file-name



The FORCE operation allows selection of the file from which the next record is to be read. It can be used only for primary or secondary files.

The file-name operand must be the name of a file from which the next record is to be selected.

If the FORCE operation is processed, the record is read at the start of the next program cycle. If more than one FORCE operation is processed during the same program cycle, all but the last is ignored. FORCE must be issued at detail time, not total time.

FORCE operations override the multi-file processing method by which the program normally selects records. However, the first record to be processed is always selected by the normal method. The remaining records can be selected by FORCE operations. For information on how the FORCE operation affects match-field processing, see Figure 6.

If FORCE is specified for a file that is at end of file, no record is retrieved from the file. The program cycle determines the next record to be read.


GOTO (Go To)


Free-Form Syntax (not allowed - use other operation codes, such as LEAVE, ITER, and RETURN)

Code Factor 1 Factor 2 Result Field Indicators
GOTO
Label



The GOTO operation allows calculation operations to be skipped by instructing the program to go to (or branch to) another calculation operation in the program. A TAG (Tag) operation names the destination of a GOTO operation. The TAG can either precede or follow the GOTO. Use a GOTO operation to specify a branch:

  • From a detail calculation line to another detail calculation line
  • From a total calculation line to another total calculation line
  • From a detail calculation line to a total calculation line
  • From a subroutine to a TAG or ENDSR within the same subroutine
  • From a subroutine to a detail calculation line or to a total calculation line.

A GOTO within a subroutine in the main procedure can be issued to a TAG within the same subroutine, detail calculations or total calculations. A GOTO within a subroutine in a subprocedure can be issued to a TAG within the same subroutine, or within the body of the subprocedure.

Branching from one part of the RPG IV logic cycle to another may result in an endless loop. You are responsible for ensuring that the logic of your program does not produce undesirable results.

Factor 2 must contain the label to which the program is to branch. This label is entered in factor 1 of a TAG or ENDSR operation. The label must be a unique symbolic name.

Figure 276. GOTO and TAG Operations


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* If indicator 10, 15, or 20 is on, the program branches to
* the TAG label specified in the GOTO operations.
* A branch within detail calculations.
C 10 GOTO RTN1
*
* A branch from detail to total calculations.
C 15 GOTO RTN2
*
C RTN1 TAG
*
C :
C :
C:
C 20 GOTO END

*
C :
C :
C :
C END TAG

* A branch within total calculations.
CL1 GOTO RTN2
CL1 :
CL1 RTN2 TAG


IF (If)


Free-Form Syntax IF{(MR)} indicator-expression

Code Factor 1 Extended Factor 2
IF (M/R) Blank indicator-expression

The IF operation code allows a series of operation codes to be processed if a condition is met. Its function is similar to that of the IFxx operation code. It differs in that the logical condition is expressed by an indicator valued expression (indicator-expression). The operations controlled by the IF operation are performed when the expression in the indicator-expression operand is true. For information on how operation extenders M and R are used, see Precision Rules for Numeric Operations.

Figure 277. IF Operation


CL0N01Factor1+++++++Opcode(E)+Extended-factor2+++++++++++++++++++++++++++..

C Extended-factor2-continuation+++++++++++++++
* The operations controlled by the IF operation are performed
* when the expression is true. That is A is greater than 10 and
* indicator 20 is on.
C
C IF A>10 AND *IN(20)
C :
C ENDIF

*
* The operations controlled by the IF operation are performed
* when Date1 represents a later date then Date2
C
C IF Date1 > Date2
C :
C ENDIF

*

IFxx (If)


Free-Form Syntax (not allowed - use the IF operation code)

Code Factor 1 Factor 2 Result Field Indicators
IFxx Comparand Comparand



The IFxx operation allows a group of calculations to be processed if a certain relationship, specified by xx, exists between factor 1 and factor 2. When ANDxx (And) and ORxx (Or) operations are used with IFxx, the group of calculations is performed if the condition specified by the combined operations exists. (For the meaning of xx, see Structured Programming Operations.)

You can use conditioning indicators. Factor 1 and factor 2 must contain a literal, a named constant, a figurative constant, a table name, an array element, a data structure name, or a field name. Both the factor 1 and factor 2 entries must be of the same data type.

If the relationship specified by the IFxx and any associated ANDxx or ORxx operations does not exist, control passes to the calculation operation immediately following the associated ENDIF operation. If an ELSE (Else) operation is specified as well, control passes to the first calculation operation that can be processed following the ELSE operation.

Conditioning indicator entries on the ENDIF operation associated with IFxx must be blank.

An ENDIF statement must be used to close an IFxx group. If an IFxx statement is followed by an ELSE statement, an ENDIF statement is required after the ELSE statement but not after the IFxx statement.

You have the option of indenting DO statements, IF-ELSE clauses, and SELECT-WHENxx-OTHER clauses in the compiler listing for readability. See the section on compiler listings in the WebSphere Development Studio: ILE RPG Programmer's Guide for an explanation of how to indent statements in the source listing.

Figure 278. IFxx/ENDIF and IFxx/ELSE/ENDIF Operations


*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* If FLDA equals FLDB, the calculation after the IFEQ operation
* is processed. If FLDA does not equal FLDB, the program
* branches to the operation immediately following the ENDIF.
C
C FLDA IFEQ FLDB
C :
C :
C :
C ENDIF
C

* If FLDA equals FLDB, the calculation after the IFEQ operation
* is processed and control passes to the operation immediately
* following the ENDIF statement. If FLDA does not equal FLDB,
* control passes to the ELSE statement and the calculation
* immediately following is processed.
C
C FLDA IFEQ FLDB
C :
C :
C :
C ELSE
C :
C :
C :
C ENDIF

*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* If FLDA is equal to FLDB and greater than FLDC, or if FLDD
* is equal to FLDE and greater than FLDF, the calculation
* after the ANDGT operation is processed. If neither of the
* specified conditions exists, the program branches to the
* operation immediately following the ENDIF statement.
C
C FLDA IFEQ FLDB
C FLDA ANDGT FLDC
C FLDD OREQ FLDE
C FLDD ANDGT FLDF
C :
C :
C :
C ENDIF


IN (Retrieve a Data Area)


Free-Form Syntax IN{(E)} {*LOCK} data-area-name

Code Factor 1 Factor 2 Result Field Indicators
IN (E) *LOCK data-area-name
_ ER _

The IN operation retrieves a data area and optionally allows you to specify whether the data area is to be locked from update by another program. For a data area to be retrieved by the IN operation, it must be specified in the result field of an *DTAARA DEFINE statement or using the DTAARA keyword on the Definition specification. (See DEFINE (Field Definition) for information on *DTAARA DEFINE operation and the Definition Specification for information on the DTAARA keyword).

If name of the data area is determined at runtime because DTAARA(*VAR) was specified on the definition of the field, then the variable containing the name of the data area must be set before the IN operation. However, if the data area is already locked due to a prior *LOCK IN operation, the variable containing the name will not be consulted; instead, the previously locked data area will be used.

The data-area-name operand can contain the reserved word *LOCK or can be blank. *LOCK indicates that the data area cannot be updated or locked by another program until (1) an UNLOCK (Unlock a Data Area or Release a Record) operation is processed, (2) an OUT (Write a Data Area) operation with no data-area-name operand specified, or (3) the RPG IV program implicitly unlocks the data area when the program ends.

*LOCK cannot be specified when the data-area-name operand is the name of the local data area or the Program Initialization Parameters (PIP) data area.

You can specify a *LOCK IN statement for a data area that the program has locked. When data-area-name is not specified, the lock status is the same as it was before the data area was retrieved: If it was locked, it remains locked; if unlocked, it remains unlocked.

data-area-name must be the name of a definition defined with the DTAARA keyword, the result field of a *DTAARA DEFINE operation, or the reserved word *DTAARA.. When *DTAARA is specified, all data areas defined in the program are retrieved. If an error occurs on the retrieval of a data area (for example, a data area can be retrieved but cannot be locked), an error occurs on the IN operation and the RPG IV exception/error handling routine receives control. If a message is issued to the requester, the message identifies the data area in error.

To handle IN exceptions (program status codes 401-421, 431, or 432), either the operation code extender 'E' or an error indicator ER can be specified, but not both. For more information on error handling, see Program Exception/Errors.

On a fixed-form calculation, positions 71-72 and 75-76 must be blank.

For further rules for the IN operation, see Data-Area Operations.

Figure 279. IN and OUT Operations


 *..1....+....2....+....3....+....4....+....5....+....6....+....7...+....

* Define Data areas
D TotAmt s 8p 2 dtaara
D TotGrs s 10p 2 dtaara
D TotNet s 10p 2 dtaara

* TOTAMT, TOTGRS, and TOTNET are defined as data areas. The IN
* operation retrieves all the data areas defined in the program
* and locks them. The program processes calculations, and at
* LR time it writes and unlocks all the data areas.
* The data areas can then be used by other programs.

/free
in *lock *dtaara;
TotAmt = TotAmt + Amount;
TotGrs = TotGrs + Gross;
TotNet = TotNet + Net;
/end-free
* To start total calcs, code a fixed format calc statement with a
* level entry specified.
CL0 total_calcs tag
/free
if *inlr
out *dtaara
endif
/end-free


ITER (Iterate)


Free-Form Syntax ITER

Code Factor 1 Factor 2 Result Field Indicators
ITER





The ITER operation transfers control from within a DO or FOR group to the ENDDO or ENDFOR statement of the group. It can be used in DO, DOU, DOUxx, DOW, DOWxx, and FOR loops to transfer control immediately to a loop's ENDDO or ENDFOR statement. It causes the next iteration of the loop to be executed immediately. ITER affects the innermost loop.

If conditioning indicators are present on the ENDDO or ENDFOR statement to which control is passed, and the condition is not satisfied, processing continues with the statement following the ENDDO or ENDFOR operation.

The LEAVE (Leave a Do/For Group) operation is similar to the ITER operation; however, LEAVE transfers control to the statement following the ENDDO or ENDFOR operation.

Figure 280. ITER Operation


*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* The following example uses a DOU loop containing a DOW loop.
* The IF statement checks indicator 01. If indicator 01 is ON,
* the LEAVE operation is executed, transferring control out of
* the innermost DOW loop to the Z-ADD instruction. If indicator
* 01 is not ON, subroutine PROC1 is processed. Then indicator
* 12 is checked. If it is OFF, ITER transfers control to the
* innermost ENDDO and the condition on the DOW is evaluated
* again. If indicator 12 is ON, subroutine PROC2 is processed.
C
C DOU FLDA = FLDB
C :
C NUM DOWLT 10
C IF *IN01
C LEAVE
C ENDIF
C EXSR PROC1
C *IN12 IFEQ *OFF
C ITER
C ENDIF
C EXSR PROC2
C ENDDO
C Z-ADD 20 RSLT 2 0
C :
C ENDDO
C :

*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* The following example uses a DOU loop containing a DOW loop.
* The IF statement checks indicator 1. If indicator 1 is ON, the
* MOVE operation is executed, followed by the LEAVE operation,
* transferring control from the innermost DOW loop to the Z-ADD
* instruction. If indicator 1 is not ON, ITER transfers control
* to the innermost ENDDO and the condition on the DOW is
* evaluated again.
C :
C FLDA DOUEQ FLDB
C :
C NUM DOWLT 10
C *IN01 IFEQ *ON
C MOVE 'UPDATE' FIELD 20
C LEAVE
C ELSE
C ITER
C ENDIF
C ENDDO
C Z-ADD 20 RSLT 2 0
C :
C ENDDO
C :


KFLD (Define Parts of a Key)


Free-Form Syntax (not allowed - use%KDS (Search Arguments in Data Structure))

Code Factor 1 Factor 2 Result Field Indicators
KFLD
Indicator Key field


The KFLD operation is a declarative operation that indicates that a field is part of a search argument identified by a KLIST name.

The KFLD operation can be specified anywhere within calculations, including total calculations. The control level entry (positions 7 and 8) can be blank or can contain an L1 through L9 indicator, an LR indicator, or an L0 entry to group the statement within the appropriate section of the program. Conditioning indicator entries (positions 9 through 11) are not permitted.

KFLDs can be global or local. A KLIST in a main procedure can have only global KFLDs associated with it. A KLIST in a subprocedure can have local and global KFLDs. For more information, see Scope of Definitions.

Factor 2 can contain an indicator for a null-capable key field if ALWNULL(*USRCTL) is specified as a keyword on a control specification or as a command parameter.

If the indicator is on, the key fields with null values are selected. If the indicator is off or not specified, the key fields with null values are not selected. See Keyed Operations for information on how to access null-capable keys.

The result field must contain the name of a field that is to be part of the search argument. The result field cannot contain an array name. Each KFLD field must agree in length, data type, and decimal position with the corresponding field in the composite key of the record or file. However, if the record has a variable-length KFLD field, the corresponding field in the composite key must be varying but does not need to be the same length. Each KFLD field need not have the same name as the corresponding field in the composite key. The order the KFLD fields are specified in the KLIST determines which KFLD is associated with a particular field in the composite key. For example, the first KFLD field following a KLIST operation is associated with the leftmost (high-order) field of the composite key.

Graphic and UCS-2 key fields must have the same CCSID as the key in the file.

Figure 281 shows an example of the KLIST operation with KFLD operations.

Figure 99 illustrates how keyed operations are used to position and retrieve records with null keys.


KLIST (Define a Composite Key)


Free-Form Syntax (not allowed - use %KDS)

Code Factor 1 Factor 2 Result Field Indicators
KLIST KLIST name




The KLIST operation is a declarative operation that gives a name to a list of KFLDs. This list can be used as a search argument to retrieve records from files that have a composite key.

You can specify a KLIST anywhere within calculations. The control level entry (positions 7 and 8) can be blank or can contain an L1 through L9 indicator, an LR indicator, or an L0 entry to group the statement within the appropriate section of the program. Conditioning indicator entries (positions 9 through 11) are not permitted. Factor 1 must contain a unique name.

Remember the following when specifying a KLIST operation:

  • If a search argument is composed of more than one field (a composite key), you must specify a KLIST with multiple KFLDs.
  • A KLIST name can be specified as a search argument only for externally described files.
  • A KLIST and its associated KFLD fields can appear anywhere in calculations.
  • A KLIST must be followed immediately by at least one KFLD.
  • A KLIST is ended when a non-KFLD operation is encountered.
  • A KLIST name can appear in factor 1 of a CHAIN, DELETE, READE, READPE, SETGT, or SETLL operation.
  • The same KLIST name can be used as the search argument for multiple files, or it can be used multiple times as the search argument for the same file.
  • A KLIST in a main procedure can have only global KFLDs associated with it. A KLIST in a subprocedure can have local and global KFLDs. For more information, see Scope of Definitions.

Figure 281. KLIST and KFLD Operations


*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

A* DDS source
A R RECORD
A FLDA 4
A SHIFT 1 0
A FLDB 10
A CLOCK# 5 0
A FLDC 10
A DEPT 4
A FLDD 8
A K DEPT
A K SHIFT
A K CLOCK#

A*
A* End of DDS source
A*
A***********************************************************************
*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* The KLIST operation indicates the name, FILEKY, by which the
* search argument can be specified.
*
C FILEKY KLIST
C KFLD DEPT
C KFLD SHIFT
C KFLD CLOCK#

The following diagram shows what the search argument looks like. The
fields DEPT, SHIFT, and CLOCK# are key fields in this record.


LEAVE (Leave a Do/For Group)


Free-Form Syntax LEAVE

Code Factor 1 Factor 2 Result Field Indicators
LEAVE





The LEAVE operation transfers control from within a DO or FOR group to the statement following the ENDDO or ENDFOR operation.

You can use LEAVE within a DO, DOU, DOUxx, DOW, DOWxx, or FOR loop to transfer control immediately from the innermost loop to the statement following the innermost loop's ENDDO or ENDFOR operation. Using LEAVE to leave a DO or FOR group does not increment the index.

In nested loops, LEAVE causes control to transfer "outwards" by one level only. LEAVE is not allowed outside a DO or FOR group.

The ITER (Iterate) operation is similar to the LEAVE operation; however, ITER transfers control to the ENDDO or ENDFOR statement.

Figure 282. LEAVE Operation


*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* The following example uses an infinite loop. When the user
* types 'q', control transfers to the LEAVE operation, which in
* turn transfers control out of the loop to the Z-ADD operation.
*
C 2 DOWNE 1
C :
C IF ANSWER = 'q'
C LEAVE
C ENDIF
C :
C ENDDO
C Z-ADD A B

*
* The following example uses a DOUxx loop containing a DOWxx.
* The IF statement checks indicator 1. If it is ON, indicator
* 99 is turned ON, control passes to the LEAVE operation and
* out of the inner DOWxx loop.
*
* A second LEAVE instruction is then executed because indicator 99
* is ON, which in turn transfers control out of the DOUxx loop.
*
C :
C FLDA DOUEQ FLDB
C NUM DOWLT 10
C *IN01 IFEQ *ON
C SETON 99
C LEAVE
C :
C ENDIF
C ENDDO
C 99 LEAVE
C :
C ENDDO
C :


LEAVESR (Leave a Subroutine)


Free-Form Syntax LEAVESR

Code Factor 1 Factor 2 Result Field Indicators
LEAVESR





The LEAVESR operation exits a subroutine from any point within the subroutine. Control passes to the ENDSR operation for the subroutine. LEAVESR is allowed only from within a subroutine.

The control level entry (positions 7 and 8) can be SR or blank. Conditioning indicator entries (positions 9 to 11) can be specified.

Figure 283. LEAVESR Operations


CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq...

*
C CheckCustName BEGSR
C Name CHAIN CustFile

*
* Check if the name identifies a valid customer
*
C IF not %found(CustFile)
C EVAL Result = CustNotFound
C LEAVESR
C ENDIF

*
* Check if the customer qualifies for discount program
C IF Qualified = *OFF
C EVAL Result = CustNotQualified
C LEAVESR
C ENDIF

*
* If we get here, customer can use the discount program
C EVAL Result = CustOK
C ENDSR


LOOKUP (Look Up a Table or Array Element)


Free-Form Syntax (not allowed - use the %LOOKUPxx or %TLOOKUPxx built-in function)

Code Factor 1 Factor 2 Result Field Indicators
LOOKUP





(array) Search argument Array name
HI LO EQ
(table) Search argument Table name Table name HI LO EQ

The LOOKUP operation causes a search to be made for a particular element in an array or table. Factor 1 is the search argument (data for which you want to find a match in the array or table named). It can be: a literal, a field name, an array element, a table name, a named constant, or a figurative constant. The nature of the comparison depends on the data type:

Character data
If ALTSEQ(*EXT) is specified on the control specification, the alternate collating sequence is used for character LOOKUP, unless either factor 1 or factor 2 was defined with ALTSEQ(*NONE) on the definition specification. If ALTSEQ(*SRC) or no alternate sequence is specified, character LOOKUP does not use the alternate sequence.
Graphic and UCS-2 data
The comparison is hexadecimal; the alternate collating sequence is not used in any circumstance.
Numeric data
The decimal point is ignored in numeric data, except when the array or table in Factor 2 is of type float.
Other data types
The considerations for comparison described in Compare Operations apply to other types.

If a table is named in factor 1, the search argument used is the element of the table last selected in a LOOKUP operation, or it is the first element of the table if a previous LOOKUP has not been processed. The array or table to be searched is specified in factor 2.

For a table LOOKUP, the result field can contain the name of a second table from which an element (corresponding positionally with that of the first table) can be retrieved. The name of the second table can be used to reference the element retrieved. The result field must be blank if factor 2 contains an array name.

Resulting indicators specify the search condition for LOOKUP. One must be specified in positions 71 through 76 first to determine the search to be done and then to reflect the result of the search. Any specified indicator is set on only if the search is successful. No more than two indicators can be used. Resulting indicators can be assigned to equal and high or to equal and low. The program searches for an entry that satisfies either condition with equal given precedence; that is, if no equal entry is found, the nearest lower or nearest higher entry is selected.

If an indicator is specified in positions 75-76, the %EQUAL built-in function returns '1' if an element is found that exactly matches the search argument. The %FOUND built-in function returns '1' if any specified search is successful.

Resulting indicators can be assigned to equal and low, or equal and high. High and low cannot be specified on the same LOOKUP operation. The compiler assumes a sorted, sequenced array or table when a high or low indicator is specified for the LOOKUP operation. The LOOKUP operation searches for an entry that satisfies the low/equal or high/equal condition with equal given priority.

  • High (71-72): Instructs the program to find the entry that is nearest to, yet higher in sequence than, the search argument. If such a higher entry is found, the high indicator is set on. For example, if an ascending array contains the values A B C C C D E, and the search argument is B, then the first C will satisfy the search. If a descending array contains E D C C C B A, and the search argument is B, then the last C will satisfy the search. If an entry higher than the search argument is not found in the array or table, then the search is unsuccessful.
  • Low (73-74): Instructs the program to find the entry that is nearest to, yet lower in sequence than, the search argument. If such a lower entry is found, the low indicator is set on. For example, if an ascending array contains the values A B C C C D E, and the search argument is D, then the last C will satisfy the search. If a descending array contains E D C C C B A, and the search argument is D, then the first C will satisfy the search. If an entry lower than the search argument is not found in the array or table, then the search is unsuccessful.
  • Equal (75-76): Instructs the program to find the entry equal to the search argument. The first equal entry found sets the equal indicator on. If an entry equal to the search argument is not found, then the search is unsuccessful.

When you use the LOOKUP operation, remember:

  • The search argument and array or table must have the same type and length (except Time and Date fields which can have a different length). If the array or table is fixed-length character, graphic, or UCS-2, the search argument must also be fixed-length. For variable length, the length of the search argument can have a different length from the array or table.
  • When LOOKUP is processed on an array and an index is used, the LOOKUP begins with the element specified by the index. The index value is set to the position number of the element located. An error occurs if the index is equal to zero or is higher than the number of elements in the array when the search begins. The index is set equal to one if the search is unsuccessful. If the index is a named constant, the index value will not change.
  • A search can be made for high, low, high and equal, or low and equal only if a sequence is specified for the array or table on the definition specifications with the ASCEND or DESCEND keywords.
  • No resulting indicator is set on if the search is not successful.
  • If only an equal indicator (positions 75-76) is used, the LOOKUP operation will search the entire array or table. If your array or table is in ascending sequence and you want only an equal comparison, you can avoid searching the entire array or table by specifying a high indicator.
  • The LOOKUP operation can produce unexpected results when the array is not in ascending or descending sequence.
  • A LOOKUP operation to a dynamically allocated array without all defined elements allocated may cause errors to occur.

Figure 284. LOOKUP Operation with Arrays


*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* In this example, the programmer wants to know which element in
* ARY the LOOKUP operation locates. The Z-ADD operation sets the
* field X to 1. The LOOKUP starts at the element ARY that is
* indicated by field X and continues running until it finds the
* first element equal to SRCHWD. The index value, X, is set to
* the position number of the element located.
C
C Z-ADD 1 X 3 0
C SRCHWD LOOKUP ARY(X) 26
C

* In this example, the programmer wants to know if an element
* is found that is equal to SRCHWD. LOOKUP searches ARY until it
* finds the first element equal to SRCHWD. When this occurs,
* indicator 26 is set on and %EQUAL is set to return '1'.
C
C SRCHWD LOOKUP ARY 26
C

* The LOOKUP starts at a variable index number specified by
* field X. Field X does not have to be set to 1 before the
* LOOKUP operation. When LOOKUP locates the first element in
* ARY equal to SRCHWD, indicator 26 is set on and %EQUAL is set
* to return '1'. The index value, X, is set to the position
* number of the element located.
*
C
C SRCHWD LOOKUP ARY(X) 26

Figure 285. LOOKUP Operation with Subarrays


  * In this example, an array of customer information actually consists

* of several subarrays. You can search either the main array or the
* subarrays overlaying the main array.
D custInfo DS
D cust DIM(100)
D name 30A OVERLAY(cust : *NEXT)
D id_number 10I 0 OVERLAY(cust : *NEXT)
D amount 15P 3 OVERLAY(cust : *NEXT)


* You can search for a particular set of customer information
* by doing a search on the "cust" array
C custData LOOKUP cust(i) 10

* You can search on a particular field of the customer information
* by doing a search on one of the overlay arrays
C custName LOOKUP name(i) 11
* After the search, the array index can be used with any of the
* overlaying arrays. If the search on name(i) is successful,
* the id_number and amount for that customer are available
* in id_number(i) and amount(i).

MHHZO (Move High to High Zone)


Free-Form Syntax (not allowed - use %BITxxx built-in functions)

Code Factor 1 Factor 2 Result Field Indicators
MHHZO
Source field Target field


The MHHZO operation moves the zone portion of a character from the leftmost zone in factor 2 to the leftmost zone in the result field. Factor 2 and the result field must both be defined as character fields. For further information on the MHHZO operation, see Move Zone Operations.

The function of the MHHZO operation is shown in Figure 153.


MHLZO (Move High to Low Zone)


Free-Form Syntax (not allowed - use %BITxxx built-in functions)

Code Factor 1 Factor 2 Result Field Indicators
MHLZO
Source field Target field


The MHLZO operation moves the zone portion of a character from the leftmost zone in factor 2 to the rightmost zone in the result field. Factor 2 must be defined as a character field. The result field can be character or numeric data. For further information on the MHLZO operation, see Move Zone Operations.

The function of the MHLZO operation is shown in Figure 153.


MLHZO (Move Low to High Zone)


Free-Form Syntax (not allowed - use %BITxxx built-in functions)

Code Factor 1 Factor 2 Result Field Indicators
MLHZO
Source field Target field


The MLHZO operation moves the zone portion of a character from the rightmost zone in factor 2 to the leftmost zone in the result field. Factor 2 can be defined as a numeric field or as a character field, but the result field must be a character field. For further information on the MLHZO operation, see Move Zone Operations.

The function of the MLHZO operation is shown in Figure 153.


MLLZO (Move Low to Low Zone)


Free-Form Syntax (not allowed - use %BITxxx built-in functions)

Code Factor 1 Factor 2 Result Field Indicators
MLLZO
Source field Target field


The MLLZO operation moves the zone portion of a character from the rightmost zone in factor 2 to the rightmost zone in the result field. Factor 2 and the result field can be either character data or numeric data. For further information on the MLLZO, see Move Zone Operations.

The function of the MLLZO operation is shown in Figure 153.


MONITOR (Begin a Monitor Group)


Free-Form Syntax MONITOR

Code Factor 1 Factor 2 Result Field Indicators
MONITOR





The monitor group performs conditional error handling based on the status code. It consists of:

After the MONITOR statement, control passes to the next statement. The monitor block consists of all the statements from the MONITOR statement to the first ON-ERROR statement. If an error occurs when the monitor block is processed, control is passed to the appropriate ON-ERROR group.

If all the statements in the MONITOR block are processed without errors, control passes to the statement following the ENDMON statement.

The monitor group can be specified anywhere in calculations. It can be nested within IF, DO, SELECT, or other monitor groups. The IF, DO, and SELECT groups can be nested within monitor groups.

If a monitor group is nested within another monitor group, the innermost group is considered first when an error occurs. If that monitor group does not handle the error condition, the next group is considered.

Level indicators can be used on the MONITOR operation, to indicate that the MONITOR group is part of total calculations. For documentation purposes, you can also specify a level indicator on an ON-ERROR or ENDMON operation but this level indicator will be ignored.

Conditioning indicators can be used on the MONITOR statement. If they are not satisfied, control passes immediately to the statement following the ENDMON statement of the monitor group. Conditioning indicators cannot be used on ON-ERROR operations individually.

If a monitor block contains a call to a subprocedure, and the subprocedure has an error, the subprocedure's error handling will take precedence. For example, if the subprocedure has a *PSSR subroutine, it will get called. The MONITOR group containing the call will only be considered if the subprocedure fails to handle the error and the call fails with the error-in-call status of 00202.

The monitor group does handle errors that occur in a subroutine. If the subroutine contains its own monitor groups, they are considered first.

Branching operations are not allowed within a monitor block, but are allowed within an ON-ERROR block.

A LEAVE or ITER operation within a monitor block applies to any active DO group that contains the monitor block. A LEAVESR or RETURN operation within a monitor block applies to any subroutine, subprocedure, or procedure that contains the monitor block.

Figure 286. MONITOR Operation


 * The MONITOR block consists of the READ statement and the IF

* group.
* - The first ON-ERROR block handles status 1211 which
* is issued for the READ operation if the file is not open.
* - The second ON-ERROR block handles all other file errors.
* - The third ON-ERROR block handles the string-operation status
* code 00100 and array index status code 00121.
* - The fourth ON-ERROR block (which could have had a factor 2
* of *ALL) handles errors not handled by the specific ON-ERROR
* operations.
*
* If no error occurs in the MONITOR block, control passes from the
* ENDIF to the ENDMON.
C MONITOR
C READ FILE1
C IF NOT %EOF
C EVAL Line = %SUBST(Line(i) :
C %SCAN('***': Line(i)) + 1)
C ENDIF
C ON-ERROR 1211
C ... handle file-not-open
C ON-ERROR *FILE
C ... handle other file errors
C ON-ERROR 00100 : 00121
C ... handle string error and array-index error
C ON-ERROR
C ... handle all other errors
C ENDMON


MOVE (Move)


Free-Form Syntax (not allowed - use the EVALR operation code, or built-in functions such as %CHAR, %DATE, %DEC, %DECH, %GRAPH, %INT, %INTH, TIME, %TIMESTAMP, %UCS2, %UNS or %UNSH)

Code Factor 1 Factor 2 Result Field Indicators
MOVE (P) Data Attributes Source field Target field + - ZB

The MOVE operation transfers characters from factor 2 to the result field. Moving starts with the rightmost character of factor 2.

When moving Date, Time or Timestamp data, factor 1 must be blank unless either the source or the target is a character or numeric field.

Otherwise, factor 1 contains the date or time format compatible with the character or numeric field that is the source or target of the operation. For information on the formats that can be used see Date Data Type, Time Data Type, and Timestamp Data Type.

If the source or target is a character field, you may optionally indicate the separator following the format in factor 1. Only separators that are valid for that format are allowed.

If factor 2 is *DATE or UDATE and the result is a Date field, factor 1 is not required. If factor 1 contains a date format it must be compatible with the format of *DATE or UDATE as specified by the DATEDIT keyword on the control specification.

When moving character, graphic, UCS-2, or numeric data, if factor 2 is longer than the result field, the excess leftmost characters or digits of factor 2 are not moved. If the result field is longer than factor 2, the excess leftmost characters or digits in the result field are unchanged, unless padding is specified.

You cannot specify resulting indicators if the result field is an array; you can specify them if it is an array element, or a non-array field.

If factor 2 is shorter than the length of the result field, a P specified in the operation extender position causes the result field to be padded on the left after the move occurs.

Float numeric fields and literals are not allowed as Factor 2 or Result-Field entries.

If CCSID(*GRAPH : IGNORE) is specified or assumed for the module, MOVE operations between UCS-2 and graphic data are not allowed.

When moving variable-length character, graphic, or UCS-2 data, the variable-length field works in exactly the same way as a fixed-length field with the same current length. A MOVE operation does not change the length of a variable-length result field. For examples, see Figures Figure 291 to Figure 296.

The tables which appear following the examples, show how data is moved from factor 2 to the result field. For further information on the MOVE operation, see Move Operations.

Figure 287. MOVE Operation with Date


*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

* Control specification date format
H DATFMT(*ISO)
*
DName++++++++++ETDsFrom+++To/L+++IDc.Functions+++++++++++++++++++++++++++
D DATE_ISO S D
D DATE_YMD S D DATFMT(*YMD)
D INZ(D'1992-03-24')
D DATE_EUR S D DATFMT(*EUR)
D INZ(D'2197-08-26')
D DATE_JIS S D DATFMT(*JIS)
D NUM_DATE1 S 6P 0 INZ(210991)
D NUM_DATE2 S 7P 0
D CHAR_DATE S 8 INZ('02/01/53')
D CHAR_LONGJUL S 8A INZ('2039/166')
D DATE_USA S D DATFMT(*USA)

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+H1LoEq..
* Move between Date fields. DATE_EUR will contain 24.03.1992
*
C MOVE DATE_YMD DATE_EUR
*
* Convert numeric value in ddmmyy format into a *ISO Date.
* DATE_ISO will contain 1991-09-21 after each of the 2 moves.
C *DMY MOVE 210991 DATE_ISO
C *DMY MOVE NUM_DATE1 DATE_ISO

*
* Move a character value representing a *MDY date to a *JIS Date.
* DATE_JIS will contain 1953-02-01 after each of the 2 moves.
C *MDY/ MOVE '02/01/53' DATE_JIS
C *MDY/ MOVE CHAR_DATE DATE_JIS

*
* Move a date field to a character field, using the
* date format and separators based on the job attributes
C *JOBRUN MOVE (P) DATE_JIS CHAR_DATE
*
* Move a date field to a numeric field, using the
* date format based on the job attributes
*
* Note: If the job format happens to be *JUL, the date will
* be placed in the rightmost 5 digits of NUM_DATE1.
* The MOVEL operation might be a better choice.
*
C *JOBRUN MOVE (P) DATE_JIS NUM_DATE1
*
* DATE_USA will contain 12-31-9999
C MOVE *HIVAL DATE_USA
*
* Execution error, resulting in error code 114. Year is not in
* 1940-2039 date range. DATE_YMD will be unchanged.
C MOVE DATE_USA DATE_YMD
*
* Move a *EUR date field to a numeric field that will
* represent a *CMDY date. NUM_DATE2 will contain 2082697
* after the move.
C *CMDY MOVE DATE_EUR NUM_DATE2
*
* Move a character value representing a *LONGJUL date to
* a *YMD date. DATE_YMD will be 39/06/15 after the move.
C *LONGJUL MOVE CHAR_LONGJUL DATE_YMD

Figure 288. MOVE Operation with Date and Time without Separators


*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

* Specify default format for date fields
H DATFMT(*ISO)
DName++++++++++ETDsFrom+++To/L+++IDc.Functions+++++++++++++++++++++++++++
D date_USA S D DATFMT(*USA)
D datefld S D
D timefld S T INZ(T'14.23.10')
D chr_dateA S 6 INZ('041596')
D chr_dateB S 7 INZ('0610807')
D chr_time S 6

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+H1LoEq..
* Move a character value representing a *MDY date to a D(Date) value.
* *MDY0 indicates that the character date in Factor 2 does not
* contain separators.
* datefld will contain 1996-04-15 after the move.
C *MDY0 MOVE chr_dateA datefld
* Move a field containing a T(Time) value to a character value in the
* *EUR format. *EUR0 indicates that the result field should not
* contain separators.
* chr_time will contain '142310' after the move.
C *EUR0 MOVE timefld chr_time
* Move a character value representing a *CYMD date to a *USA
* Date. Date_USA will contain 08/07/1961 after the move.
* 0 in *CYMD indicates that the character value does not
* contain separators.
C *CYMD0 MOVE chr_dateB date_USA

Figure 289. MOVE Operation with Timestamp


*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

* Control specification DATEDIT format
*
H DATEDIT(*MDY)
*
DName+++++++++++ETDsFrom+++To/L+++IDc.Functions+++++++++++++++++++++++
D Jobstart S Z
D Datestart S D
D Timestart S T
D Timebegin S T inz(T'05.02.23')
D Datebegin S D inz(D'1991-09-24')
D TmStamp S Z inz

*
* Set the timestamp Jobstart with the job start Date and Time
*
* Factor 1 of the MOVE *DATE (*USA = MMDDYYYY) is consistent
* with the value specified for the DATEDIT keyword on the
* control specification, since DATEDIT(*MDY) indicates that
* *DATE is formatted as MMDDYYYY.
*
* Note: It is not necessary to specify factor 1 with *DATE or
* UDATE.
*
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq..
C *USA MOVE *DATE Datestart
C TIME StrTime 6 0
C *HMS MOVE StrTime Timestart
C MOVE Datestart Jobstart
C MOVE Timestart Jobstart

*
* After the following C specifications are performed, the field
* stampchar will contain '1991-10-24-05.17.23.000000'.
*
* First assign a timestamp the value of a given time+15 minutes and
* given date + 30 days. Move tmstamp to a character field.
* stampchar will contain '1991-10-24-05.17.23.000000'.
*
C ADDDUR 15:*minutes Timebegin
C ADDDUR 30:*days Datebegin
C MOVE Timebegin TmStamp
C MOVE Datebegin TmStamp
C MOVE TmStamp stampchar 26

* Move the timestamp to a character field without separators. After
* the move, STAMPCHAR will contain ' 19911024051723000000'.
C *ISO0 MOVE(P) TMSTAMP STAMPCHAR0

Figure 290. MOVE between character and graphic fields


*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

DName++++++++++ETDsFrom+++To/L+++IDc.Functions+++++++++++++++++++
*
* Example of MOVE between graphic and character fields
*
D char_fld1 S 10A inz('oK1K2K3 i')
D dbcs_fld1 S 4G
D char_fld2 S 10A inz(*ALL'Z')
D dbcs_fld2 S 3G inz(G'oK1K2K3i')

*
*
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiL
*
* Value of dbcs_fld1 after MOVE operation is 'K1K2K3 '
* Value of char_fld2 after MOVE oepration is 'ZZoK1K2K3i'
*
C MOVE char_fld1 dbcs_fld1
C MOVE dbcs_fld2 char_fld2

Figure 291. MOVE from a variable-length field to variable-length field


*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

DName++++++++++ETDsFrom+++To/L+++IDc.Functions+++++++++++++++++++
*
* Example of MOVE from variable to variable length
* for character fields
*
D var5a S 5A INZ('ABCDE') VARYING
D var5b S 5A INZ('ABCDE') VARYING
D var5c S 5A INZ('ABCDE') VARYING
D var10a S 10A INZ('0123456789') VARYING
D var10b S 10A INZ('ZXCVBNM') VARYING
D var15a S 15A INZ('FGH') VARYING
D var15b S 15A INZ('FGH') VARYING
D var15c S 15A INZ('QWERTYUIOPAS') VARYING

*
*
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiL
*
C MOVE var15a var5a
* var5a = 'ABFGH' (length=5)
C MOVE var10a var5b
* var5b = '56789' (length=5)
C MOVE var5c var15a
* var15a = 'CDE' (length=3)
C MOVE var10b var15b
* var15b = 'BNM' (length=3)
C MOVE var15c var10b
* var10b = 'YUIOPAS' (length=7)

Figure 292. MOVE from a variable-length field to a fixed-length field


*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

DName++++++++++ETDsFrom+++To/L+++IDc.Functions+++++++++++++++++++
*
* Example of MOVE from variable to fixed length
* for character fields
*
D var5 S 5A INZ('ABCDE') VARYING
D var10 S 10A INZ('0123456789') VARYING
D var15 S 15A INZ('FGH') VARYING
D fix5a S 5A INZ('MNOPQ')
D fix5b S 5A INZ('MNOPQ')
D fix5c S 5A INZ('MNOPQ')

*
*
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiL
*
C MOVE var5 fix5a
* fix5a = 'ABCDE'
C MOVE var10 fix5b
* fix5b = '56789'
C MOVE var15 fix5c
* fix5c = 'MNFGH'

Figure 293. MOVE from a fixed-length field to a variable-length field


*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

DName++++++++++ETDsFrom+++To/L+++IDc.Functions+++++++++++++++++++
*
* Example of MOVE from fixed to variable length
* for character fields
*
D var5 S 5A INZ('ABCDE') VARYING
D var10 S 10A INZ('0123456789') VARYING
D var15 S 15A INZ('FGHIJKL') VARYING
D fix5 S 5A INZ('.....')
D fix10 S 10A INZ('PQRSTUVWXY')

*
*
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiL
*
C MOVE fix10 var5
* var5 = 'UVWXY' (length=5)
C MOVE fix5 var10
* var10 = '01234.....' (length=10)
C MOVE fix10 var15
* var15 = 'STUVWXY' (length=7)

Figure 294. MOVE(P) from a variable-length field to a variable-length field


*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

DName++++++++++ETDsFrom+++To/L+++IDc.Functions+++++++++++++++++++
*
* Example of MOVE(P) from variable to variable length
* for character fields
*
D var5a S 5A INZ('ABCDE') VARYING
D var5b S 5A INZ('ABCDE') VARYING
D var5c S 5A INZ('ABCDE') VARYING
D var10 S 10A INZ('0123456789') VARYING
D var15a S 15A INZ('FGH') VARYING
D var15b S 15A INZ('FGH') VARYING
D var15c S 15A INZ('FGH') VARYING

*
*
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiL
*
C MOVE(P) var15a var5a
* var5a = ' FGH' (length=5)
C MOVE(P) var10 var5b
* var5b = '56789' (length=5)
C MOVE(P) var5c var15b
* var15b = 'CDE' (length=3)
C MOVE(P) var10 var15c
* var15c = '789' (length=3)

Figure 295. MOVE(P) from a variable-length field to a fixed-length field


*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

DName++++++++++ETDsFrom+++To/L+++IDc.Functions+++++++++++++++++++
*
* Example of MOVE(P) from variable to fixed length
* for character fields
*
D var5 S 5A INZ('ABCDE') VARYING
D var10 S 10A INZ('0123456789') VARYING
D var15 S 15A INZ('FGH') VARYING
D fix5a S 5A INZ('MNOPQ')
D fix5b S 5A INZ('MNOPQ')
D fix5c S 5A INZ('MNOPQ')

*
*
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiL
*
C MOVE(P) var5 fix5a
* fix5a = 'ABCDE'
C MOVE(P) var10 fix5b
* fix5b = '56789'
C MOVE(P) var15 fix5c
* fix5c = ' FGH'

Figure 296. MOVE(P) from a fixed-length field to a variable-length field


*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

DName++++++++++ETDsFrom+++To/L+++IDc.Functions+++++++++++++++++++
*
* Example of MOVE(P) from fixed to variable length
* for character fields
*
D var5 S 5A INZ('ABCDE') VARYING
D var10 S 10A INZ('0123456789') VARYING
D var15a S 15A INZ('FGHIJKLMNOPQR') VARYING
D var15b S 15A INZ('FGHIJ') VARYING
D fix5 S 5A INZ('')
D fix10 S 10A INZ('PQRSTUVWXY')

*
*
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiL
*
C MOVE(P) fix10 var5
* var5 = 'UVWXY' (length=5 before and after)
C MOVE(P) fix10 var10
* var10 = 'PQRSTUVWXY' (length=10 before and after)
C MOVE(P) fix10 var15a
* var15a = ' PQRSTUVWXY' (length=13 before and after)
C MOVE(P) fix10 var15b
* var15b = 'UVWXY' (length=5 before and after)

Table 53. Moving a Character Field to a Date-Time Field

Factor 1 specifies the format of the Factor 2 entry
Factor 1
Entry
Factor 2
(Character)
Result Field
Value DTZ Type
*MDY- 11-19-75 75/323 D(*JUL)
*JUL 92/114 23/04/92 D(*DMY)
*YMD 14/01/28 01/28/2014 D(*USA)
*YMD0 140128 01/28/2014 D(*USA)
*USA 12/31/9999 31.12.9999 D(*EUR)
*ISO 2036-05-21 21/05/36 D(*DMY)
*JUL 45/333 11/29/1945 D(*USA)
*MDY/ 03/05/33 03.05.33 D(*MDY.)
*CYMD& 121 07 08 08.07.2021 D(*EUR)
*CYMD0 1210708 07,08,21 D(*MDY,)
*CMDY. 107.08.21 21-07-08 D(*YMD-)
*CDMY0 1080721 07/08/2021 D(*USA)
*LONGJUL- 2021-189 08/07/2021 D(*EUR)
*HMS& 23 12 56 23.12.56 T(*ISO)
*USA 1:00 PM 13.00.00 T(*EUR)
*EUR 11.10.07 11:10:07 T(*JIS)
*JIS 14:16:18 14.16.18 T(*HMS.)
*ISO 24.00.00 12:00 AM T(*USA)
Blank 1991-09-14-13.12.56.123456 1991-09-14-13.12.56.123456 Z(*ISO)
*ISO 1991-09-14-13.12.56.123456 1991-09-14-13.12.56.123456 Z(*ISO)

Table 54. Moving a Numeric Field to a Date-Time Field

Factor 1 specifies the format of the Factor 2 entry
Factor 1
Entry1
Factor 2
(Numeric)
Result Field
Value DTZ Type
*MDY 111975 75/323 D(*JUL)
*JUL 92114 23/04/92 D(*DMY)
*YMD 140128 01/28/2014 D(*USA)
*USA2 12319999 31.12.9999 D(*EUR)
*ISO 20360521 21/05/36 D(*DMY)
*JUL 45333 11/29/1945 D(*USA)
*MDY 030533 03.05.33 D(*MDY.)
*CYMD 1210708 08.07.2021 D(*EUR)
*CMDY 1070821 21-07-08 D(*YMD-)
*CDMY 1080721 07/08/2021 D(*USA)
*LONGJUL 2021189 08/07/2021 D(*EUR)
*USA *DATE (092195)3 1995-09-21 D(*JIS)
Blank *DATE (092195)3 1995-09-21 D(*JIS)
*MDY UDATE (092195)3 21.09.1995 D(*EUR)
*HMS 231256 23.12.56 T(*ISO)
*EUR 111007 11:10:07 T(*JIS)
*JIS 141618 14.16.18 T(*HMS.)
*ISO 240000 12:00 AM T(*USA)
Blank4 19910914131256123456 1991-09-14-13.12.56.123456 Z(*ISO)

Notes:

  1. A separator of zero (0) is not allowed in factor 1 for movement between date, time or timestamp fields and numeric classes.
  2. Time format *USA is not allowed for movement between time and numeric classes.
  3. For *DATE and UDATE, assume that the job date in the job description is of *MDY format and contains 092195. Factor 1 is optional and will default to the correct format. If factor 2 is *DATE, and factor 1 is coded, it must be a 4-digit year date format. If factor 2 is UDATE, and factor 1 is coded, it must be a 2-digit year date format.
  4. For moves of timestamp fields, factor 1 is optional. If it is coded it must be *ISO or *ISO0.


Table 55. Moving a Date-Time Field to a Character Field

Factor 1
Entry
Factor 2
Result Field
(Character)
Value DTZ Type
*JUL 11-19-75 D(*MDY-) 75/323
*DMY- 92/114 D(*JUL) 23-04-92
*USA 14/01/28 D(*YMD) 01/28/2014
*EUR 12/31/9999 D(*USA) 31.12.9999
*DMY, 2036-05-21 D(*ISO) 21,05,36
*USA 45/333 D(*JUL) 11/29/1945
*USA0 45/333 D(*JUL) 11291945
*MDY& 03/05/33 D(*MDY) 03 05 33
*CYMD, 03 07 08 D(*MDY&); 108,03,07
*CYMD0 21/07/08 D(*DMY) 1080721
*CMDY 21-07-08 D(*YMD-) 107/08/21
*CDMY- 07/08/2021 D(*USA) 108-07-21
*LONGJUL& 08/07/2021 D(*EUR) 2021 189
*ISO 23 12 56 T(*HMS&); 23.12.56
*EUR 11:00 AM T(*USA) 11.00.00
*JIS 11.10.07 T(*EUR) 11:10:07
*HMS, 14:16:18 T(*JIS) 14,16,18
*USA 24.00.00 T(*ISO) 12:00 AM
Blank 2045-10-27-23.34.59.123456 Z(*ISO) 2045-10-27-23.34.59.123456

Table 56. Moving a Date-Time Field to a Numeric Field

Factor 1
Entry
Factor 2
Result Field
(Numeric)
Value DTZ Type
*JUL 11-19-75 D(*MDY-) 75323
*DMY- 92/114 D(*JUL) 230492
*USA 14/01/28 D(*YMD) 01282014
*EUR 12/31/9999 D(*USA) 31129999
*DMY, 2036-05-21 D(*ISO) 210536
*USA 45/333 D(*JUL) 11291945
*MDY& 03/05/33 D(*MDY) 030533
*CYMD, 03 07 08 D(*MDY&); 1080307
*CMDY 21-07-08 D(*YMD-) 1070821
*CDMY- 07/08/2021 D(*USA) 1080721
*LONGJUL& 08/07/2021 D(*EUR) 2021189
*ISO 23 12 56 T(*HMS&); 231256
*EUR 11:00 AM T(*USA) 110000
*JIS 11.10.07 T(*EUR) 111007
*HMS, 14:16:18 T(*JIS) 141618
*ISO 2045-10-27-23.34.59.123456 Z(*ISO) 20451027233459123456

Table 57. Moving Date-Time Fields to Date-Time Fields

Assume that the initial value of the timestamp is 1985-12-03-14.23.34.123456.
Factor 1 Factor 2 Result Field
Value DTZ Type Value DTZ Type
N/A 1986-06-24 D(*ISO) 86/06/24 D(*YMD)
N/A 23 07 12 D(*DMY&); 23.07.2012 D(*EUR)
N/A 11:53 PM T(USA) 23.53.00 T(*EUR)
N/A 19.59.59 T(*HMS.) 19:59:59 T(*JIS)
N/A 1985-12-03-14.23.34.123456 Z(*ISO.) 1985-12-03-14.23.34.123456 Z(*ISO)
N/A 75.06.30 D(*YMD.) 1975-06-30-14.23.34.123456 Z(*ISO)
N/A 09/23/2234 D(*USA) 2234-09-23-14.23.34.123456 Z(*ISO)
N/A 18,45,59 T(*HMS,) 1985-12-03-18.45.59.000000 Z(*ISO)
N/A 2:00 PM T(*USA) 1985-12-03-14.00.00.000000 Z(*ISO)
N/A 1985-12-03-14.23.34.123456 Z(*ISO.) 12/03/85 D(*MDY)
N/A 1985-12-03-14.23.34.123456 Z(*ISO.) 12/03/1985 D(*USA)
N/A 1985-12-03-14.23.34.123456 Z(*ISO.) 14:23:34 T(*HMS)
N/A 1985-12-03-14.23.34.123456 Z(*ISO.) 02:23 PM T(*USA)

Table 58. Moving a Date field to a Character field

The result field is larger than factor 2. Assume that Factor 1 contains *ISO and that the result field is defined as

D     Result_Fld        20A   INZ('ABCDEFGHIJabcdefghij')

Operation
Code
Factor 2 Value of Result Field
after move operation
Value DTZ Type
MOVE 11 19 75 D(*MDY&); 'ABCDEFGHIJ1975-11-19'
MOVE(P) 11 19 75 D(*MDY&); ' 1975-11-19'
MOVEL 11 19 75 D(*MDY&); '1975-11-19abcdefghij'
MOVEL(P) 11 19 75 D(MDY&); '1975-11-19 '

Table 59. Moving a Time field to a Numeric field

The result field is larger than factor 2. Assume that Factor 1 contains *ISO and that the result field is defined as

D     Result_Fld        20S   INZ(11111111111111111111)

Operation
Code
Factor 2 Value of Result Field
after move operation
Value DTZ Type
MOVE 9:42 PM T(*USA) 11111111111111214200
MOVE(P) 9:42 PM T(*USA) 00000000000000214200
MOVEL 9:42 PM T(*USA) 21420011111111111111
MOVEL(P) 9:42 PM T(*USA) 21420000000000000000

Table 60. Moving a Numeric field to a Time field

Factor 2 is larger than the result field. The highlighted portion shows the part of the factor 2 field that is moved.
Operation
Code
Factor 2 Result Field
DTZ Type Value
MOVE 11:12:13:14 T(*EUR) 12.13.14
MOVEL 11:12:13:14 T(*EUR) 11.12.13

Table 61. Moving a Numeric field to a Timestamp field

Factor 2 is larger than the result field. The highlighted portion shows the part of the factor 2 field that is moved.
Operation
Code
Factor 2 Result Field
DTZ Type Value
MOVE 12340618230323123420123456 Z(*ISO) 1823-03-23-12.34.20.123456
MOVEL 12340618230323123420123456 Z(*ISO) 1234-06-18-23.03.23.123420

Figure 297. MOVE Operation



MOVEA (Move Array)


Free-Form Syntax (not allowed)

Code Factor 1 Factor 2 Result Field Indicators
MOVEA (P)
Source Target + - ZB

The MOVEA operation transfers character, graphic, UCS-2, or numeric values from factor 2 to the result field. (Certain restrictions apply when moving numeric values.) Factor 2 or the result field must contain an array. Factor 2 and the result field cannot specify the same array even if the array is indexed. You can:

  • Move several contiguous array elements to a single field
  • Move a single field to several contiguous array elements
  • Move contiguous array elements to contiguous elements of another array.

Movement of data starts with the first element of an array if the array is not indexed or with the element specified if the array is indexed. The movement of data ends when the last array element is moved or filled. When the result field contains the indicator array, all indicators affected by the MOVEA operation are noted in the cross-reference listing.

The coding for and results of MOVEA operations are shown in Figure 298.

Character, graphic, and UCS-2 MOVEA Operations

Both factor 2 and the result field must be the same type - either character, graphic, or UCS-2. Graphic or UCS-2 CCSIDs must be the same, unless one of the CCSIDs is 65535, or in the case of graphic fields, CCSID(*GRAPH: *IGNORE) was specified on the control specification.

On a character, graphic, or UCS-2 MOVEA operation, movement of data ends when the number of characters moved equals the shorter length of the fields specified by factor 2 and the result field; therefore, the MOVEA operation could end in the middle of an array element. Variable-length arrays are not allowed.

Numeric MOVEA Operations

Moves are only valid between fields and array elements with the same numeric length defined. Factor 2 and the result field entries can specify numeric fields, numeric array elements, or numeric arrays; at least one must be an array or array element. The numeric types can be binary, packed decimal, or zoned decimal but need not be the same between factor 2 and the result field.

Factor 2 can contain a numeric literal if the result field entry specifies a numeric array or numeric array-element:

  • The numeric literal cannot contain a decimal point.
  • The length of the numeric literal cannot be greater than the element length of the array or array element specified in the result field.

Decimal positions are ignored during the move and need not correspond. Numeric values are not converted to account for the differences in the defined number of decimal places.

The figurative constants *BLANK, *ALL, *ON and *OFF are not valid in factor 2 of a MOVEA operation on a numeric array.

General MOVEA Operations

If you need to use a MOVEA operation in your application, but restrictions on numeric MOVEA operations prevent you, you might be able to use character MOVEA operations. If the numeric array is in zoned decimal format:

  • Define the numeric array as a subfield of a data structure
  • Redefine the numeric array in the data structure as a character array.

If a figurative constant is specified with MOVEA, the length of the constant generated is equal to the portion of the array specified. For figurative constants in numeric arrays, the element boundaries are ignored except for the sign that is put in each array element. Examples are:

  • MOVEA *BLANK ARR(X)

    Beginning with element X, the remainder of ARR will contain blanks.

  • MOVEA *ALL'XYZ' ARR(X)

    ARR has 4-byte character elements. Element boundaries are ignored, as is always the case with character MOVEA. Beginning with element X, the remainder of the array will contain 'XYZXYZXYZXYZ. . .'.

For character, graphic, UCS-2, and numeric MOVEA operations, you can specify a P operation extender to pad the result from the right.

For further information on the MOVEA operation, see Move Operations.

Figure 298. MOVEA Operation


*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
C MOVEA ARRX ARRY
* Array-to-array move. No indexing; different length array,
* same element length.
*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
C MOVEA ARRX ARRY(3)
* Array-to-array move with index result field.
*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
C MOVEA ARRX ARRY
* Array-to-array move, no indexing and different length array
* elements.
*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
C MOVEA ARRX(4) ARRY
* Array-to-array move, index factor 2 with different length array
* elements.
*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
C MOVEA FIELDA ARRY
* Field-to-array move, no indexing on array.
*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* In the following example, N=3. Array-to-field move with variable
* indexing.
C MOVEA ARRX(N) FIELD
*
*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
C MOVEA ARRB ARRZ
*
* An array-to-array move showing numeric elements.
*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
C MOVEA(P) ARRX ARRY
* Array-to-array move with padding. No indexing; different length
* array with same element length.
*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
C MOVEA(P) ARRB ARRZ
*
* An array-to-array move showing numeric elements with padding.
*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
C MOVEA(P) ARRX(3) ARRY
* Array-to-array move with padding. No indexing; different length
* array with different element length.

MOVEL (Move Left)


Free-Form Syntax (not allowed - use the EVAL operation code, or built-in functions such as %CHAR, %DATE, %DEC, %DECH, %GRAPH, %INT, %INTH, TIME, %TIMESTAMP, %UCS2, %UNS or %UNSH)

Code Factor 1 Factor 2 Result Field Indicators
MOVEL (P) Data Attributes Source field Target field + - ZB

The MOVEL operation transfers characters from factor 2 to the result field. Moving begins with the leftmost character in factor 2. You cannot specify resulting indicators if the result field is an array. You can specify them if the result field is an array element, or a non-array field.

When data is moved to a numeric field, the sign (+ or -) of the result field is retained except when factor 2 is as long as or longer than the result field. In this case, the sign of factor 2 is used as the sign of the result field.

Factor 1 can contain a date or time format to specify the format of a character or numeric field that is the source or target of the operation. For information on the formats that can be used see Date Data Type, Time Data Type, and Timestamp Data Type.

If the source or target is a character field, you may optionally indicate the separator following the format in factor 1. Only separators that are valid for that format are allowed.

If factor 2 is *DATE or UDATE and the result is a Date field, factor 1 is not required. If factor 1 contains a date format it must be compatible with the format of *DATE or UDATE in factor 2 as specified by the DATEDIT keyword on the control specification.

If factor 2 is longer than the result field, the excess rightmost characters of factor 2 are not moved. If the result field is longer than factor 2, the excess rightmost characters in the result field are unchanged, unless padding is specified.

Float numeric fields and literals are not allowed as Factor 2 or Result-Field entries.

If factor 2 is UCS-2 and the result field is character, or if factor 2 is character and the result field is UCS-2, the number of characters moved is variable since the character data may or may not contain shift characters and graphic characters. For example, five UCS-2 characters can convert to:

  • Five single-byte characters
  • Five double-byte characters
  • A combination of single-byte and double-byte characters with shift characters separating the modes

If the resulting data is too long to fit the result field, the data will be truncated. If the result is single-byte character, it is the responsibility of the user to ensure that the result contains complete characters, and contains matched SO/SI pairs.

The MOVEL operation is summarized in Figure 299.

A summary of the rules for MOVEL operation for four conditions based on field lengths:

  1. Factor 2 is the same length as the result field:
    1. If factor 2 and the result field are numeric, the sign is moved into the rightmost position.
    2. If factor 2 is numeric and the result field is character, the sign is moved into the rightmost position.
    3. If factor 2 is character and the result field is numeric, a minus zone is moved into the rightmost position of the result field if the zone from the rightmost position of factor 2 is a hexadecimal D (minus zone). However, if the zone from the rightmost position of factor 2 is not a hexadecimal D, a positive zone is moved into the rightmost position of the result field. Digit portions are converted to their corresponding numeric characters. If the digit portions are not valid digits, a data exception error occurs.
    4. If factor 2 and the result field are character, all characters are moved.
    5. If factor 2 and the result field are both graphic or UCS-2, all graphic or UCS-2 characters are moved.
    6. If factor 2 is graphic and the result field is character, one graphic character will be lost, because 2 positions (bytes) in the character result field will be used to hold the SO/SI inserted by the compiler.
    7. If factor 2 is character and the result field is graphic, the factor 2 character data must be completely enclosed by one single pair of SO/SI. The SO/SI will be removed by the compiler before moving the data to the graphic result field.
  2. Factor 2 is longer than the result field:
    1. If factor 2 and the result field are numeric, the sign from the rightmost position of factor 2 is moved into the rightmost position of the result field.
    2. If factor 2 is numeric and the result field is character, the result field contains only numeric characters.
    3. If factor 2 is character and the result field is numeric, a minus zone is moved into the rightmost position of the result field if the zone from the rightmost position of factor 2 is a hexadecimal D (minus zone). However, if the zone from the rightmost position of factor 2 is not a hexadecimal D, a positive zone is moved into the rightmost position of the result field. Other result field positions contain only numeric characters.
    4. If factor 2 and the result field are character, only the number of characters needed to fill the result field are moved.
    5. If factor 2 and the result field are graphic or UCS-2, only the number of graphic or UCS-2 characters needed to fill the result field are moved.
    6. If factor 2 is graphic and the result field is character, the graphic data will be truncated and SO/SI will be inserted by the compiler.
    7. If factor 2 is character and the result is graphic, the character data will be truncated. The character data must be completely enclosed by one single pair of SO/SI.
  3. Factor 2 is shorter than the result field:
    1. If factor 2 is either numeric or character and the result field is numeric, the digit portion of factor 2 replaces the contents of the leftmost positions of the result field. The sign in the rightmost position of the result field is not changed.
    2. If factor 2 is either numeric or character and the result field is character data, the characters in factor 2 replace the equivalent number of leftmost positions in the result field. No change is made in the zone of the rightmost position of the result field.
    3. If factor 2 is graphic and the result field is character, the SO/SI are added immediately before and after the graphic data. This may cause unbalanced SO/SI in the character field due to residual data in the field, but this is users' responsibility.
    4. Notice that when moving from a character to graphic field, the entire character field should be enclosed in SO/SI. For example, if the character field length is 8, the character data in the field should be "oAABB i" and not "oAABBi ".
  4. Factor 2 is shorter than the result field and P is specified in the operation extender field:
    1. The move is performed as described above.
    2. The result field is padded from the right. See Move Operations for more information on the rules for padding.

When moving variable-length character, graphic, or UCS-2 data, the variable-length field works in exactly the same way as a fixed-length field with the same current length. A MOVEL operation does not change the length of a variable-length result field. For examples, see Figures Figure 302 to Figure 307.

For further information on the MOVEL operation, see Move Operations.

Figure 299. MOVEL Operation


Figure 300. MOVEL between character and graphic fields


*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

DName++++++++++ETDsFrom+++To/L+++IDc.Functions+++++++++++++++++++++++++++
D
*
* Example of MOVEL between graphic and character fields
*
D char_fld1 S 8A inz(' ')
D dbcs_fld1 S 4G inz('oAABBCCDDi')
D char_fld2 S 4A inz(' ')
D dbcs_fld2 S 3G inz(G'oAABBCCi')
D char_fld3 S 10A inz(*ALL'X')
D dbcs_fld3 S 3G inz(G'oAABBCCi')
D char_fld4 S 10A inz('oAABBCC i')
D dbcs_fld4 S 2G

*
*
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq..
*
* The result field length is equal to the factor 2 length in bytes.
* One DBCS character is lost due to insertion of SO/SI.
* Value of char_fld1 after MOVEL operation is 'oAABBCCi'
*
C MOVEL dbcs_fld1 char_fld1
*
* Result field length shorter than factor 2 length. Truncation occurs.
* Value of char_fld2 after MOVEL operation is 'oAAi'
*
C MOVEL dbcs_fld2 char_fld2
*
* Result field length longer than factor 2 length. Example shows
* SO/SI are added immediately before and after graphic data.
* Before the MOVEL, Result Field contains 'XXXXXXXXXX'
* Value of char_fld3 after MOVEL operation is 'oAABBCCiXX'
*
C MOVEL dbcs_fld3 char_fld3
*
* Character to Graphic MOVEL
* Result Field shorter than Factor 2. Truncation occurs.
* Value of dbcs_fld4 after MOVEL operation is 'AABB'
*
C MOVEL char_fld4 dbcs_fld4

Figure 301. MOVEL between character and date fields


*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

HKeywords+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* Example of MOVEL between character and date fields
*
* Control specification date format
H DATFMT(*MDY)
*
DName++++++++++ETDsFrom+++To/L+++IDc.Functions+++++++++++++++++++++++++++
D datefld S D INZ(D'04/15/96')
D char_fld1 S 8A
D char_fld2 S 10A INZ('XXXXXXXXXX')
D char_fld3 S 10A INZ('04/15/96XX')
D date_fld3 S D
D char_fld4 S 10A INZ('XXXXXXXXXX')

D char_fld5 S 9A INZ('015/04/50')
D date_fld2 S D INZ(D'11/16/10')

*
*
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+H1LoEq..
* Date to Character MOVEL
* The result field length is equal to the factor 2 length. Value of
* char_fld1 after the MOVEL operation is '04/15/96'.
C *MDY MOVEL datefld char_fld1
* Date to Character MOVEL
* The result field length is longer than the factor 2 length.
* Before MOVEL, result field contains 'XXXXXXXXXX'
* Value of char_fld2 after the MOVEL operation is '04/15/96XX'.
C *MDY MOVEL datefld char_fld2
* Character to Date MOVEL
* The result field length is shorter than the factor 2 length.
* Value of date_fld3 after the MOVEL operation is '04/15/96'.
C *MDY MOVEL char_fld3 date_fld3
* Date to Character MOVEL (no separators)
* The result field length is longer than the factor 2 length.
* Before MOVEL, result field contains 'XXXXXXXXXX'
* Value of char_fld4 after the MOVEL operation is '041596XXXX'.
C *MDY0 MOVEL datefld char_fld4
* Character to date MOVEL
* The result field length is equal to the factor 2 length.
* The value of date_fld3 after the move is 04/15/50.
C *CDMY MOVEL char_fld5 date_fld3
* Date to character MOVEL (no separators)
* The result field length is longer than the factor 2 length.
* The value of char_fld4 after the move is '2010320XXX'.
C *LONGJUL0 MOVEL date_fld2 char_fld4

Figure 302. MOVEL from a variable-length field to a variable-length field


*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

DName++++++++++ETDsFrom+++To/L+++IDc.Functions+++++++++++++++++++
*
* Example of MOVEL from variable to variable length
* for character fields
*
D var5a S 5A INZ('ABCDE') VARYING
D var5b S 5A INZ('ABCDE') VARYING
D var5c S 5A INZ('ABCDE') VARYING
D var10 S 10A INZ('0123456789') VARYING
D var15a S 15A INZ('FGH') VARYING
D var15b S 15A INZ('FGH') VARYING

*
*
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiL
*
C MOVEL var15a var5a
* var5a = 'FGHDE' (length=5)
C MOVEL var10 var5b
* var5b = '01234' (length=5)
C MOVEL var5c var15a
* var15a = 'ABC' (length=3)
C MOVEL var10 var15b
* var15b = '012' (length=3)

Figure 303. MOVEL from a variable-length field to fixed-length field


*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

DName++++++++++ETDsFrom+++To/L+++IDc.Functions+++++++++++++++++++
*
* Example of MOVEL from variable to fixed length
* for character fields
*
D var5 S 5A INZ('ABCDE') VARYING
D var10 S 10A INZ('0123456789') VARYING
D var15 S 15A INZ('FGH') VARYING
D fix5a S 5A INZ('MNOPQ')
D fix5b S 5A INZ('MNOPQ')
D fix5c S 5A INZ('MNOPQ')
D fix10 S 10A INZ('')

*
*
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiL
*
C MOVEL var5 fix5a
* fix5a = 'ABCDE'
C MOVEL var10 fix5b
* fix5b = '01234'
C MOVEL var15 fix5c
* fix5c = 'FGHPQ'

Figure 304. MOVEL from a fixed-length field to variable-length field


*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

DName++++++++++ETDsFrom+++To/L+++IDc.Functions+++++++++++++++++++
*
* Example of MOVEL from fixed to variable length
* for character fields
*
D var5 S 5A INZ('ABCDE') VARYING
D var10 S 10A INZ('0123456789') VARYING
D var15a S 15A INZ('FGHIJKLMNOPQR') VARYING
D var15b S 15A INZ('WXYZ') VARYING
D fix10 S 10A INZ('PQRSTUVWXY')

*
*
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiL
*
C MOVEL fix10 var5
* var5 = 'PQRST' (length=5)
C MOVEL fix10 var10
* var10 = 'PQRSTUVWXY' (length=10)
C MOVEL fix10 var15a
* var15a = 'PQRSTUVWXYPQR' (length=13)
C MOVEL fix10 var15b
* var15b = 'PQRS' (length=4)

Figure 305. MOVEL(P) from a variable-length field to a variable-length field


*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

DName++++++++++ETDsFrom+++To/L+++IDc.Functions+++++++++++++++++++
*
* Example of MOVEL(P) from variable to variable length
* for character fields
*
D var5a S 5A INZ('ABCDE') VARYING
D var5b S 5A INZ('ABCDE') VARYING
D var5c S 5A INZ('ABCDE') VARYING
D var10 S 10A INZ('0123456789') VARYING
D var15a S 15A INZ('FGH') VARYING
D var15b S 15A INZ('FGH') VARYING
D var15c S 15A INZ('FGHIJKLMN') VARYING

*
*
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiL
*
C MOVEL(P) var15a var5a
* var5a = 'FGH ' (length=5)
C MOVEL(P) var10 var5b
* var5b = '01234' (length=5)
C MOVEL(P) var5c var15b
* var15b = 'ABC' (length=3)
C MOVEL(P) var15a var15c
* var15c = 'FGH ' (length=9)

Figure 306. MOVEL(P) from a variable-length field to fixed-length field


*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

DName++++++++++ETDsFrom+++To/L+++IDc.Functions+++++++++++++++++++
*
* Example of MOVEL(P) from variable to fixed length
* for character fields
*
D var5 S 5A INZ('ABCDE') VARYING
D var10 S 10A INZ('0123456789') VARYING
D var15 S 15A INZ('FGH') VARYING
D fix5a S 5A INZ('MNOPQ')
D fix5b S 5A INZ('MNOPQ')
D fix5c S 5A INZ('MNOPQ')

*
*
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiL
*
C MOVEL(P) var5 fix5a
* fix5a = 'ABCDE'
C MOVEL(P) var10 fix5b
* fix5b = '01234'
C MOVEL(P) var15 fix5c
* fix5c = 'FGH '

Figure 307. MOVEL(P) from a fixed-length field to variable-length field


*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

DName++++++++++ETDsFrom+++To/L+++IDc.Functions+++++++++++++++++++
*
* Example of MOVEL(P) from fixed to variable length
* for character fields
*
D var5 S 5A INZ('ABCDE') VARYING
D var10 S 10A INZ('0123456789') VARYING
D var15a S 15A INZ('FGHIJKLMNOPQR') VARYING
D var15b S 15A INZ('FGH') VARYING
D fix5 S 10A INZ('.....')
D fix10 S 10A INZ('PQRSTUVWXY')

*
*
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiL
*
C MOVEL(P) fix10 var5
* var5 = 'PQRST' (length=5)
C MOVEL(P) fix5 var10
* var10 = '..... ' (length=10)
C MOVEL(P) fix10 var15a
* var15a = 'PQRSTUVWXY ' (length=13)
C MOVEL(P) fix10 var15b
* var15b = 'PQR' (length=3)

MULT (Multiply)


Free-Form Syntax (not allowed - use the * or *= operators)

Code Factor 1 Factor 2 Result Field Indicators
MULT (H) Multiplicand Multiplier Product + - Z

If factor 1 is specified, factor 1 is multiplied by factor 2 and the product is placed in the result field. Be sure that the result field is large enough to hold it. Use the following rule to determine the maximum result field length: result field length equals the length of factor 1 plus the length of factor 2. If factor 1 is not specified, factor 2 is multiplied by the result field and the product is placed in the result field. Factor 1 and factor 2 must be numeric, and each can contain one of: an array, array element, field, figurative constant, literal, named constant, subfield, or table name. The result field must be numeric, but cannot be a named constant or literal. You can specify half adjust to have the result rounded.

For further information on the MULT operation, see Arithmetic Operations.

See Figure 146 for examples of the MULT operation.


MVR (Move Remainder)


Free-Form Syntax (not allowed - use the %REM built-in function)

Code Factor 1 Factor 2 Result Field Indicators
MVR

Remainder + - Z

The MVR operation moves the remainder from the previous DIV operation to a separate field named in the result field. Factor 1 and factor 2 must be blank. The MVR operation must immediately follow the DIV operation. If you use conditioning indicators, ensure that the MVR operation is processed immediately after the DIV operation. If the MVR operation is processed before the DIV operation, undesirable results occur. The result field must be numeric and can contain one of: an array, array element, subfield, or table name.

Leave sufficient room in the result field if the DIV operation uses factors with decimal positions. The number of significant decimal positions is the greater of:

  • The number of decimal positions in factor 1 of the previous divide operation
  • The sum of the decimal positions in factor 2 and the result field of the previous divide operation.

The sign (+ or -) of the remainder is the same as the dividend (factor 1).

You cannot specify half adjust on a DIV operation that is immediately followed by an MVR operation.

The maximum number of whole number positions in the remainder is equal to the whole number of positions in factor 2 of the previous divide operation.

The MVR operation cannot be used if the previous divide operation has an array specified in the result field. Also, the MVR operation cannot be used if the previous DIV operation has at least one float operand.

For further information on the MVR operation, see Arithmetic Operations.

See Figure 146 for an example of the MVR operation.


NEXT (Next)


Free-Form Syntax NEXT{(E)} program-device file-name

Code Factor 1 Factor 2 Result Field Indicators
NEXT (E) program-device file-name
_ ER _

The NEXT operation code forces the next input for a multiple device file to come from the program device specified by the program-device operand, providing the input operation is a cycle read or a READ-by-file-name. Any read operation, including CHAIN, EXFMT, READ, and READC, ends the effect of the previous NEXT operation. If NEXT is specified more than once between input operations, only the last operation is processed. The NEXT operation code can be used only for a multiple device file.

For the program-device operand, enter the name of a 10-character field that contains the program device name, a character literal, or named constant that is the program device name. The file-name operand is the name of the multiple device WORKSTN file for which the operation is requested.

To handle NEXT exceptions (file status codes greater than 1000), either the operation code extender 'E' or an error indicator ER can be specified, but not both. For more information on error handling, see File Exception/Errors.

Figure 308. NEXT Operations


*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
C
* Assume devices Dev1 and Dev2 are connected to the WORKSTN file
* DEVICEFILE. The first READ reads data from DEV1, the second READ
* reads data from DEV2. The NEXT operation will direct the program
* to wait for data from the device specified in factor 1 (i.e. DEV1)
* for the third READ.
C
C READ (E) Devicefile
C :
C READ (E) Devicefile
C :
C 'DEV1' NEXT
C :
C READ (E) Devicefile


OCCUR (Set/Get Occurrence of a Data Structure)


Free-Form Syntax (not allowed - use the %OCCUR built-in function)

Code Factor 1 Factor 2 Result Field Indicators
OCCUR (E) Occurrence value Data structure Occurrence value _ ER _

The OCCUR operation code specifies the occurrence of the data structure that is to be used next within an RPG IV program.

The OCCUR operation establishes which occurrence of a multiple occurrence data structure is used next in a program. Only one occurrence can be used at a time. If a data structure with multiple occurrences or a subfield of that data structure is specified in an operation, the first occurrence of the data structure is used until an OCCUR operation is specified. After an OCCUR operation is specified, the occurrence of the data structure that was established by the OCCUR operation is used.

Factor 1 is optional; if specified, it can contain a numeric, zero decimal position literal, field name, named constant, or a data structure name. Factor 1 is used during the OCCUR operation to set the occurrence of the data structure specified in factor 2. If factor 1 is blank, the value of the current occurrence of the data structure in factor 2 is placed in the result field during the OCCUR operation.

If factor 1 is a data structure name, it must be a multiple occurrence data structure. The current occurrence of the data structure in factor 1 is used to set the occurrence of the data structure in factor 2.

Factor 2 is required and must be the name of a multiple occurrence data structure.

The result field is optional; if specified, it must be a numeric field name with no decimal positions. During the OCCUR operation, the value of the current occurrence of the data structure specified in factor 2, after being set by any value or data structure that is optionally specified in factor 1, is placed in the result field.

At least one of factor 1 or the result field must be specified.

If the occurrence is outside the valid range set for the data structure, an error occurs, and the occurrence of the data structure in factor 2 remains the same as before the OCCUR operation was processed.

To handle OCCUR exceptions (program status code 122), either the operation code extender 'E' or an error indicator ER can be specified, but not both. For more information on error handling, see Program Exception/Errors.

When a multiple-occurrence data structure is imported or exported, the information about the current occurrence is not imported or exported. See the EXPORT{(external_name)} and IMPORT{(external_name)} keywords for more information.

Figure 309. Uses of the OCCUR Operation


*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++
*
* DS1 and DS2 are multiple occurrence data structures.
* Each data structure has 50 occurrences.
D DS1 DS OCCURS(50)
D FLDA 1 5
D FLDB 6 80

*
D DS2 DS OCCURS(50)
D FLDC 1 6
D FLDD 7 11

*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
* DS1 is set to the third occurrence. The subfields FLDA
* and FLDB of the third occurrence can now be used. The MOVE
* and Z-ADD operations change the contents of FLDA and FLDB,
* respectively, in the third occurrence of DS1.
C
C 3 OCCUR DS1
C MOVE 'ABCDE' FLDA
C Z-ADD 22 FLDB

*
* DS1 is set to the fourth occurrence. Using the values in
* FLDA and FLDB of the fourth occurrence of DS1, the MOVE
* operation places the contents of FLDA in the result field,
* FLDX, and the Z-ADD operation places the contents of FLDB
* in the result field, FLDY.
C
C 4 OCCUR DS1
C MOVE FLDA FLDX
C Z-ADD FLDB FLDY

*
* DS1 is set to the occurrence specified in field X.
* For example, if X = 10, DS1 is set to the tenth occurrence.
C X OCCUR DS1
*
* DS1 is set to the current occurrence of DS2. For example, if
* the current occurrence of DS2 is the twelfth occurrence, DSI
* is set to the twelfth occurrence.
C DS2 OCCUR DS1
*
* The value of the current occurrence of DS1 is placed in the
* result field, Z. Field Z must be numeric with zero decimal
* positions. For example, if the current occurrence of DS1
* is 15, field Z contains the value 15.
C OCCUR DS1 Z
C

* DS1 is set to the current occurrence of DS2. The value of the
* current occurrence of DS1 is then moved to the result field,
* Z. For example, if the current occurrence of DS2 is the fifth
* occurrence, DS1 is set to the fifth occurrence. The result
* field, Z, contains the value 5.
C
C DS2 OCCUR DS1 Z

*
* DS1 is set to the current occurrence of X. For example, if
* X = 15, DS1 is set to the fifteenth occurrence.
* If X is less than 1 or is greater than 50,
* an error occurs and %ERROR is set to return '1'.
* If %ERROR returns '1', the LR indicator is set on.
C
C X OCCUR (E) DS1
C IF %ERROR
C SETON LR
C ENDIF

Figure 310. Exporting a Multiple Occurrence DS


*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords++++++++++++++++++++++++++
*
* Procedure P1 exports a multiple occurrence data structure.
* Since the information about the current occurrence is
* not exported, P1 can communicate this information to
* other procedures using parameters, but in this case it
* communicates this information by exporting the current
* occurrence.
*
D EXP_DS DS OCCURS(50) EXPORT
D FLDA 1 5
D NUM_OCCUR C %ELEM(EXP_DS)
D EXP_DS_CUR S 5P 0 EXPORT

*
*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq.
*
* Loop through the occurrences. For each occurrence, call
* procedure P2 to process the occurrence. Since the occurrence
* number EXP_DS_CUR is exported, P2 will know which occurrence
* to process.
*
C DO NUM_OCCUR EXP_DS_CUR
C EXP_DS_CUR OCCUR EXP_DS
C :
C CALLB 'P2'
C ENDDO
C :

*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords++++++++++++++++++++++++++
*
* Procedure P2 imports the multiple occurrence data structure.
* The current occurrence is also imported.
*
D EXP_DS DS OCCURS(50) IMPORT
D FLDA 1 5
D EXP_DS_CUR S 5P 0 IMPORT

*
*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq.
*
* Set the imported multiple-occurrence data structure using
* the imported current occurrence.
*
C EXP_DS_CUR OCCUR EXP_DS
*
* Process the current occurrence.
C :

ON-ERROR (On Error)


Free-Form Syntax ON-ERROR {exception-id1 {:exception-id2...}}

Code Factor 1 Extended Factor 2
ON-ERROR
List of exception IDs

You specify which error conditions the on-error block handles in the list of exception IDs (exception-id1:exception-id2...). You can specify any combination of the following, separated by colons:

nnnnn
A status code
*PROGRAM
Handles all program-error status codes, from 00100 to 00999
*FILE
Handles all file-error status codes, from 01000 to 09999
*ALL
Handles both program-error and file-error codes, from 00100 to 09999. This is the default.

Status codes outside the range of 00100 to 09999, for example codes from 0 to 99, are not monitored for. You cannot specify these values for an on-error group. You also cannot specify any status codes that are not valid for the particular version of the compiler being used.

If the same status code is covered by more than one on-error group, only the first one is used. For this reason, you should specify special values such as *ALL after the specific status codes.

Any errors that occur within an on-error group are not handled by the monitor group. To handle errors, you can specify a monitor group within an on-error group.

When all the statements in an on-error block have been processed, control passes to the statement following the ENDMON statement.

For an example of the ON-ERROR statement, see MONITOR (Begin a Monitor Group).


OPEN (Open File for Processing)


Free-Form Syntax OPEN{(E)} file-name

Code Factor 1 Factor 2 Result Field Indicators
OPEN (E)
file-name
_ ER _

The explicit OPEN operation opens the file named in the file-name operand. The file named cannot be designated as a primary, secondary, or table file.

To handle OPEN exceptions (file status codes greater than 1000), either the operation code extender 'E' or an error indicator ER can be specified, but not both. For more information on error handling, see File Exception/Errors.

To open the file specified in the file-name operand for the first time in a program with an explicit OPEN operation, specify the USROPN keyword on the file description specifications. (See File Description Specifications for restrictions when using the USROPN keyword.)

If a file is opened and later closed by the CLOSE operation in the program, the programmer can reopen the file with the OPEN operation and the USROPN keyword on the file description specification is not required. When the USROPN keyword is not specified on the file description specification, the file is opened at program initialization. If an OPEN operation is specified for a file that is already open, an error occurs.

Multiple OPEN operations in a program to the same file are valid as long as the file is closed when the OPEN operation is issued to it.

When you open a file with the DEVID keyword specified (on the file description specifications), the fieldname specified as a parameter on the DEVID keyword is set to blanks. See the description of the DEVID keyword, in File Description Specifications.

Figure 311. OPEN Operation with CLOSE Operation


*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

FFilename++IPEASFRlen+LKlen+AIDevice+.Keywords++++++++++++++++++++++++++++
F
FEXCEPTN O E DISK USROPN
FFILEX F E DISK

F
*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
CL0N01Factor1+++++++Opcode(E)+Extended-factor2+++++++++++++++++++++++++++..
*
* The explicit OPEN operation opens the EXCEPTN file for
* processing if indicator 97 is on and indicator 98 is off.
* Note that the EXCEPTN file on the file description
* specifications has the USROPN keyword specified.
* %ERROR is set to return '1' if the OPEN operation fails.
*
C IF *in97 and not *in98
C OPEN(E) EXCEPTN
C IF not %ERROR
C WRITE ERREC
C ENDIF
C ENDIF

*
* FILEX is opened at program initialization. The explicit
* CLOSE operation closes FILEX before control is passed to RTNX.
* RTNX or another program can open and use FILEX. Upon return,
* the OPEN operation reopens the file. Because the USROPN
* keyword is not specified for FILEX, the file is opened at
* program initialization
*
C CLOSE FILEX
C CALL 'RTNX'
C OPEN FILEX


ORxx (Or)


Free-Form Syntax (not allowed - use the OR operator)

Code Factor 1 Factor 2 Result Field Indicators
ORxx Comparand Comparand



The ORxx operation is optional with the DOUxx, DOWxx, IFxx, WHENxx, and ANDxx operations. ORxx is specified immediately following a DOUxx, DOWxx, IFxx, WHENxx, ANDxx or ORxx statement. Use ORxx to specify a more complex condition for the DOUxx, DOWxx, IFxx, and WHENxx operations.

The control level entry (positions 7 and 8) can be blank or can contain an L1 through L9 indicator, an LR indicator, or an L0 entry to group the statement within the appropriate section of the program. The control level entry must be the same as the entry for the associated DOUxx, DOWxx, IFxx, or WHENxx operation. Conditioning indicator entries (positions 9 through 11) are not allowed.

Factor 1 and factor 2 must contain a literal, a named constant, a figurative constant, a table name, an array element, a data structure name, or a field name. Factor 1 and factor 2 must be of the same type. The comparison of factor 1 and factor 2 follows the same rules as those given for the compare operations. See Compare Operations.

Figure 264 shows an example of ORxx and ANDxx operations with a DOUxx operation.


OTHER (Otherwise Select)


Free-Form Syntax OTHER

Code Factor 1 Factor 2 Result Field Indicators
OTHER





The OTHER operation begins the sequence of operations to be processed if no WHENxx or WHEN (When True Then Select) condition is satisfied in a SELECT group. The sequence ends with the ENDSL or END operation.

Rules to remember when using the OTHER operation:

  • The OTHER operation is optional in a SELECT group.
  • Only one OTHER operation can be specified in a SELECT group.
  • No WHENxx or WHEN operation can be specified after an OTHER operation in the same SELECT group.
  • The sequence of calculation operations in the OTHER group can be empty; the effect is the same as not specifying an OTHER statement.
  • Within total calculations, the control level entry (positions 7 and 8) can be blank or can contain an L1 through L9 indicator, an LR indicator, or an L0 entry to group the statement within the appropriate section of the program. The control level entry is for documentation purposes only. Conditioning indicator entries (positions 9 through 11) are not allowed.

Figure 312. OTHER Operation


*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* Example of a SELECT group with WHENxx and OTHER. If X equals 1,
* do the operations in sequence 1; if X does not equal 1 and Y
* equals 2, do the operations in sequence 2. If neither
* condition is true, do the operations in sequence 3.
*
C SELECT
C X WHENEQ 1

*
* Sequence 1
*
C :
C :
C Y WHENEQ 2

*
* Sequence 2
*
C :
C :
C OTHER

*
* Sequence 3
*
C :
C :
C ENDSL

For more details and examples, see the SELECT and WHENxx operations.


OUT (Write a Data Area)


Free-Form Syntax OUT{(E)} {*LOCK} data-area-name

Code Factor 1 Factor 2 Result Field Indicators
OUT (E) *LOCK data-area-name
_ ER _

The OUT operation updates the data area specified in the data-area-name operand. To specify a data area as the data-area-name operand of an OUT operation, you must ensure two things:

  • The data area must also be specified in the result field of a *DTAARA DEFINE statement, or defined using the DTAARA keyword on the Definition specification.
  • The data area must have been locked previously by a *LOCK IN statement or it must have been specified as a data area data structure by a U in position 23 of the definition specifications. (The RPG IV language implicitly retrieves and locks data area data structures at program initialization.)

You can specify the optional reserved word *LOCK. When *LOCK is specified, the data area remains locked after it is updated. When *LOCK is not specified, the data area is unlocked after it is updated.

*LOCK cannot be specified when the data-area-name operand is the name of the local data area or the Program Initialization Parameters (PIP) data area.

The data-area-name operand must be either the name of the data area or the reserved word *DTAARA. When *DTAARA is specified, all data areas defined in the program are updated. If an error occurs when one or more data areas are updated (for example, if you specify an OUT operation to a data area that has not been locked by the program), an error occurs on the OUT operation and the RPG IV exception/error handling routine receives control. If a message is issued to the requester, the message identifies the data area in error.

To handle OUT exceptions (program status codes 401-421, 431, or 432), either the operation code extender 'E' or an error indicator ER can be specified, but not both. For more information on error handling, see Program Exception/Errors.

Positions 71-72 and 75-76 must be blank.

For further rules for the OUT operation, see Data-Area Operations.

See Figure 279 for an example of the OUT operation.


PARM (Identify Parameters)


Free-Form Syntax (not allowed - use the PR definition specification)

Code Factor 1 Factor 2 Result Field Indicators
PARM Target field Source field Parameter


The declarative PARM operation defines the parameters that compose a parameter list (PLIST). PARM operations can appear anywhere in calculations as long as they immediately follow the PLIST, CALL, or CALLB operation they refer to. PARM statements must be in the order expected by the called program or procedure. One PARM statement, or as many as 255 for a CALL or 399 for a CALLB or PLIST are allowed.

The PARM operation can be specified anywhere within calculations, including total calculations. The control level entry (positions 7 and 8) can be blank or can contain an L1 through L9 indicator, an LR indicator, or an L0 entry to group the statement in the appropriate section of the program. Conditioning indicator entries (positions 9 through 11) are not allowed.

Factor 1 and factor 2 entries are optional. If specified, the entries must be the same type as specified in the result field. If the target field is variable-length, its length will be set to the length of the value of the source field. A literal or named constant cannot be specified in factor 1. Factor 1 and factor 2 must be blank if the result field contains the name of a multiple-occurrence data structure or *OMIT.

TIP

If parameter type-checking is important for the application, you should define a prototype and procedure interface definition for the call interface, rather than use the PLIST and PARM operations.

The result field must contain the name of a:

  • For all PARM statements:
    • Field
    • Data structure
    • Array
  • For non-*ENTRY PLIST PARM statements it can also contain:
    • Array element
    • *OMIT (CALLB only)

The Result-Field entry of a PARM operation cannot contain:

  • *IN, *INxx, *IN(xx)
  • A literal
  • A named constant
  • A table name

In addition, the following are not allowed in the Result-Field entry of a PARM operation in the *ENTRY PLIST:

  • *OMIT
  • A globally initialized data structure
  • A data structure with initialized subfields
  • A data structure with a compile time array as a subfield
  • Fields or data structures defined with the keywords BASED, IMPORT, or EXPORT
  • An array element
  • A data-area name
  • A data-area data structure name
  • A data-structure subfield
  • A compile-time array
  • A program status (PSDS) or file information data structure (INFDS)

A field name can be specified only once in an *ENTRY PLIST.

If an array is specified in the result field, the area defined for the array is passed to the called program or procedure. When a data structure with multiple occurrences is passed to the called program or procedure, all occurrences of the data structure are passed as a single field. However, if a subfield of a multiple occurrence data structure is specified in the result field, only the current occurrence of the subfield is passed to the called program or procedure.

Each parameter field has only one storage location; it is in the calling program or procedure. The address of the storage location of the result field is passed to the called program or procedure on a PARM operation. If the called program or procedure changes the value of a parameter, it changes the data at that storage location. When control returns to the calling program or procedure, the parameter in the calling program or procedure (that is, the result field) has changed. Even if the called program or procedure ends in error after it changes the value of a parameter, the changed value exists in the calling program or procedure. To preserve the information passed to the called program or procedure for later use, specify in factor 2 the name of the field that contains the information you want to pass to the called program or procedure. Factor 2 is copied into the result field, and the storage address of the result field is passed to the called program or procedure.

Because the parameter fields are accessed by address, not field name, the calling and called parameters do not have to use the same field names for fields that are passed. The attributes of the corresponding parameter fields in the calling and called programs or procedures should be the same. If they are not, undesirable results may occur.

When a CALL or CALLB operation runs, the following occurs:

  1. In the calling procedure, the contents of the factor 2 field of a PARM operation are copied into the result field (receiver field) of the same PARM operation.
  2. In the case of a CALLB when the result field is *OMIT, a null address will be passed to the called procedure.
  3. In the called procedure, after it receives control and after any normal program initialization, the contents of the result field of a PARM operation are copied into the factor 1 field (receiver field) of the same PARM operation.
  4. In the called procedure, when control is returned to the calling procedure, the contents of the factor 2 field of a PARM operation are copied into the result field (receiver field) of the same PARM operation. This move does not occur if the called procedure ends abnormally. The result of the move is unpredictable if an error occurs on the move.
  5. Upon return to the calling procedure, the contents of the result field of a PARM operation in the calling procedure are copied into the factor 1 field (receiver field) of the same PARM operation. This move does not occur if the called procedure ends abnormally or if an error occurs on the call operation.

Note:
The data is moved in the same way as data is moved using the EVAL operation code. Strict type compatibility is enforced. For a discussion of how to call and pass parameters to a program through CL, see the CL Programming manual.

Figure 313 illustrates the PARM operation.


PLIST (Identify a Parameter List)


Free-Form Syntax (not allowed - use the PR definition specification)

Code Factor 1 Factor 2 Result Field Indicators
PLIST PLIST name




The declarative PLIST operation defines a unique symbolic name for a parameter list to be specified in a CALL or CALLB operation.

You can specify a PLIST operation anywhere within calculations, including within total calculations and between subroutines. The control level entry (positions 7 and 8) can be blank or can contain an L1 through L9 indicator, an LR indicator, or an L0 entry to group the statement in the appropriate section of the program. The PLIST operation must be immediately followed by at least one PARM operation. Conditioning indicator entries (positions 9 through 11) are not allowed.

Factor 1 must contain the name of the parameter list. If the parameter list is the entry parameter list, factor 1 must contain *ENTRY. Only one *ENTRY parameter list can be specified in a program or procedure. A parameter list is ended when an operation other than PARM is encountered.

TIP

If parameter type-checking is important for the application, you should define a prototype and procedure inter- face definition for the call interface, rather than use the PLIST and PARM operations.

Figure 313. PLIST/PARM Operations


*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* In the calling program, the CALL operation calls PROG1 and
* allows PROG1 to access the data in the parameter list fields.
C CALL 'PROG1' PLIST1
*
* In the second PARM statement, when CALL is processed, the
* contents of factor 2, *IN27, are placed in the result field,
* BYTE. When PROG1 returns control, the contents of the result
* field, BYTE, are placed in the factor 1 field, *IN30. Note
* that factor 1 and factor 2 entries on a PARM are optional.
*
C PLIST1 PLIST
C PARM Amount 5 2
C *IN30 PARM *IN27 Byte 1

*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
C CALLB 'PROG2'
* In this example, the PARM operations immediately follow a
* CALLB operation instead of a PLIST operation.
C PARM Amount 5 2
C *IN30 PARM *IN27 Byte 1

*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
* In the called procedure, PROG2, *ENTRY in factor 1 of the
* PLIST statement identifies it as the entry parameter list.
* When control transfers to PROG2, the contents of the result
* fields (FieldC and FieldG) of the parameter list are placed in
* the factor 1 fields (FieldA and FieldD). When the called procedure
* returns, the contents of the factor 2 fields of the parameter
* list (FieldB and FieldE) are placed in the result fields (FieldC
* and FieldG). All of the fields are defined elsewhere in the
* procedure.
C *ENTRY PLIST
C FieldA PARM FieldB FieldC
C FieldD PARM FieldE FieldG


POST (Post)


Free-Form Syntax POST{(E)} {program-device} file-name

Code Factor 1 Factor 2 Result Field Indicators
POST (E) program-device file-name INFDS name _ ER _

The POST operation puts information in an INFDS (file information data structure). This information contains the following:

  • File Feedback Information specific to RPG I/O for the file
  • Open Feedback Information for the file
  • Input/Output Feedback Information and Device Dependent Feedback Information for the file OR Get Attribute Information

The program-device operand specifies a program device name to get information about that specific program device. If you specify a program device, the file must be defined as a WORKSTN file. If program-device is specified, then the INFDS will contain Get Attribute Information following the Open Feedback Information. Use either a character field of length 10 or less, a character literal, or a character named constant. If program-device is not specified, then the INFDS will contain Input/Output Feedback Information and Device Dependent Feedback Information following the Open Feedback Information.

Specify the name of a file in the file-name operand. Information for this file is posted in the INFDS associated with this file.

In free-form syntax, you must specify a file-name and cannot specify an INFDS name. In traditional syntax, you can specify a file-name, an INFDS name, or both.

  • If you do not specify an INFDS name, the INFDS associated with this file using the INFDS keyword in the file specification will be used.
  • If you do not specify an INFDS name in traditional syntax, you must specify the data structure name that has been used in the INFDS keyword for the file specification in the result field; information from the associated file in the file specification will be posted.

To handle POST exceptions (file status codes greater than 1000), either the operation code extender 'E' or an error indicator ER can be specified, but not both. For more information on error handling, see File Exception/Errors.

Even when a POST operation code is not processed, its existence in your program can affect the way the RPG IV language operates. Usually, the INFDS is updated at each input and output operation or block of operations. However, if anywhere in your program, you have specified a POST operation with no program-device specified, then RPG IV updates the I/O Feedback Information area and the Device Dependent Feedback Information area in the INFDS of any file only when you process a POST operation for that file. The File Dependent Information in the INFDS is updated on all Input/Output operations. If you have opened a file for multiple-member processing, the Open Feedback Information in the INFDS will be updated when an input operation (READ, READP, READE READPE) causes a new member to be opened.

Note that DUMP retrieves its information directly from the Open Data Path and not from the INFDS, so the file information sections of the DUMP do not depend on POST.

If a program has no POST operation code, or if it has only POST operation codes with program-device specified, the Input/Output Feedback and Device Dependent Feedback section is updated with each input/output operation or block of operations. If RPG is blocking records, most of the information in the INFDS will be valid only for the last complete block of records processed. When doing blocked input, from a data base file, RPG will update the relative record number and key information in the INFDS for each read, not just the last block of records processed. If you require more accurate information, do not use record blocking. See File Information Data Structure for more information on record blocking. If you do not require feedback information after every input/output operation, you may be able to improve performance by using the POST operation only when you require the feedback information.

When a POST operation is processed, the associated file must be open. If you specify a program device on the POST operation, it does not have to be acquired by the file.


READ (Read a Record)


Free-Form Syntax READ{(EN)} name {data-structure}

Code Factor 1 Factor 2 Result Field Indicators
READ (E N)
name (file or record format) data-structure _ ER EOF

The READ operation reads the record, currently pointed to, from a full procedural file (identified by an F in position 18 of the file description specifications).

The name operand is required and must be the name of a file or record format. A record format name is allowed only with an externally described file (E in position 22 of the file description specifications). It may be the case that a READ-by-format-name operation will receive a different format from the one you specified in the name operand. If so, your READ operation ends in error.

If the data-structure operand is specified, the record is read directly into the data structure. If name refers to a program-described file (identified by an F in position 22 of the file description specification), the data structure can be any data structure of the same length as the file's declared record length. If name refers to an externally-described file or a record format from an externally described file, the data structure must be a data structure defined with EXTNAME(...:*INPUT) or LIKEREC(...:*INPUT). See File Operations for information on how data is transferred between the file and the data structure.

If a READ operation is successful, the file is positioned at the next record that satisfies the read. If there is an error or an end of file condition, you must reposition the file (using a CHAIN, SETLL, or SETGT operation).

If the file from which you are reading is an update disk file, you can specify an N operation extender to indicate that no lock should be placed on the record when it is read. See the WebSphere Development Studio: ILE RPG Programmer's Guide for more information.

To handle READ exceptions (file status codes greater than 1000), either the operation code extender 'E' or an error indicator ER can be specified, but not both. For more information on error handling, see File Exception/Errors.

You can specify an indicator in positions 75-76 to signal whether an end of file occurred on the READ operation. The indicator is either set on (an EOF condition) or off every time the READ operation is performed. This information can also be obtained from the %EOF built-in function, which returns '1' if an EOF condition occurs and '0' otherwise. The file must be repositioned after an EOF condition, in order to process any further successful sequential operations (for example, READ or READP) to the file.

Figure 314 illustrates the READ operation.

When name specifies a multiple device file, the READ operation does one of the following:

  • Reads data from the device specified in the most recent NEXT operation (if such a NEXT operation has been processed).
  • Accepts the first response from any device that has been acquired for the file, and that was specified for "invite status" with the DDS keyword INVITE. If there are no invited devices, the operation receives an end of file. The input is processed according to the corresponding format. If the device is a workstation, the last format written to it is used. If the device is a communications device, you can select the format.

    Refer to ICF Programming, SC41-5442-00 for more information on format selection processing for an ICF file.

    The READ operation will stop waiting after a period of time in which no input is provided, or when one of the following CL commands has been entered with the controlled option specified:

    • ENDJOB (End Job)
    • ENDSBS (End Subsystem)
    • PWRDWNSYS (Power Down System)
    • ENDSYS (End System).

    This results in a file exception/error that is handled by the method specified in your program (see File Exception/Errors). See ICF Programming, SC41-5442-00 for a discussion of the WAITRCD parameter on the commands to create or modify a file. This parameter controls the length of time the READ operation waits for input.

When name specifies a format name and the format name is associated with a multiple device file, data is read from the device identified by the field specified in the DEVID keyword in file specifications. If there is no such entry, data is read from the device used in the last successful input operation.

See Database Null Value Support for information on reading records with null-capable fields.

Figure 314. READ Operation


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* READ retrieves the next record from the file FILEA, which must
* be a full procedural file.
* %EOF is set to return '1' if an end of file occurs on READ,
* or if an end of file has occurred previously and the file
* has not been repositioned. When %EOF returns '1',
* the program will leave the loop.
*
C DOW '1'
C READ FILEA
C IF %EOF
C LEAVE
C ENDIF

*
* READ retrieves the next record of the type REC1 (factor 2)
* from an externally described file. (REC1 is a record format
* name.) Indicator 64 is set on if an end of file occurs on READ,
* or if it has occurred previously and the file has not been
* repositioned. When indicator 64 is set on, the program
* will leave the loop. The N operation code extender
* indicates that the record is not locked.
*
C READ(N) REC1 64
C 64 LEAVE
C ENDDO


READC (Read Next Changed Record)


Free-Form Syntax READC{(E)} record-name

Code Factor 1 Factor 2 Result Field Indicators
READC (E)
record-name
_ ER EOF

The READC operation can be used only with an externally described WORKSTN file to obtain the next changed record in a subfile. The record-name operand is required and must be the name of a record format defined as a subfile by the SFILE keyword on the file description specifications. (See SFILE(recformat:rrnfield) for information on the SFILE keyword.)

For a multiple device file, data is read from the subfile record associated with a program device; the program device is identified by the field specified in the DEVID keyword on the file specifications. If there is no such entry, data is read from the program device used for the last successful input operation.

To handle READC exceptions (file status codes greater than 1000), either the operation code extender 'E' or an error indicator ER can be specified, but not both. For more information on error handling, see File Exception/Errors.

You can specify an indicator in positions 75-76 that will be set on when there are no more changed records in the subfile. This information can also be obtained from the %EOF built-in function, which returns '1' if there are no more changed records in the subfile and '0' otherwise.

If the data-structure operand is specified, the record is read directly into the data structure. The data structure must be a data structure defined with EXTNAME(...:*INPUT) or LIKEREC(...:*INPUT). See File Operations for information on how data is transferred between the file and the data structure.

Figure 315. READC example


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

FFilename++IPEASFRlen+LKlen+AIDevice+.Keywords++++++++++++++++++++++++++++
* CUSSCR is a WORKSTN file which displays a list of records from
* the CUSINFO file. SFCUSR is the subfile name.
*
FCUSINFO UF E DISK
FCUSSCR CF E WORKSTN SFILE(SFCUSR:RRN)

F
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
* After the subfile has been loaded with the records from the
* CUSINFO file. It is written out to the screen using EXFMT with
* the subfile control record, CTLCUS. If there are any changes in
* any one of the records listed on the screen, the READC operation
* will read the changed records one by one in the do while loop.
* The corresponding record in the CUSINFO file will be located
* with the CHAIN operation and will be updated with the changed
* field.
C :
C EXFMT CTLCUS
C :

* SCUSNO, SCUSNAM, SCUSADR, and SCUSTEL are fields defined in the
* subfile. CUSNAM, CUSADR, and CUSTEL are fields defined in a
* record, CUSREC which is defined in the file CUSINFO.
*
C READC SFCUSR
C DOW %EOF = *OFF
C SCUSNO CHAIN (E) CUSINFO

* Update the record only if the record is found in the file.
C :
C IF NOT %ERROR
C EVAL CUSNAM = SCUSNAM
C EVAL CUSADR = SCUSADR
C EVAL CUSTEL = SCUSTEL
C UPDATE CUSREC
C ENDIF
C READC (E) SFCUSR
C ENDDO


READE (Read Equal Key)


Free-Form Syntax READE{(ENHMR)} search-arg|*KEY name {data-structure}

Code Factor 1 Factor 2 Result Field Indicators
READE (E N) search-arg name (file or record format) data-structure _ ER EOF

The READE operation retrieves the next sequential record from a full procedural file (identified by an F in position 18 of the file description specifications) if the key of the record matches the search argument. If the key of the record does not match the search argument, an EOF condition occurs, and the record is not returned to the program. An EOF condition also applies when end of file occurs.

The search argument, search-arg, identifies the record to be retrieved. The search-arg operand is optional in traditional syntax but is required in free-form syntax. search-arg can be:

  • A field name, a literal, a named constant, or a figurative constant.
  • A KLIST name for an externally described file.
  • A list of key values enclosed in parentheses. See Figure 246 for an example of searching using a list of key values.
  • %KDS to indicate that the search arguments are the subfields of a data structure. See the example at the end of %KDS (Search Arguments in Data Structure) for an illustration of search arguments in a data structure.
  • *KEY or (in traditional syntax only) no value. If the full key of the next record is equal to that of the current record, the next record in the file is retrieved. The full key is defined by the record format or file specified in name.
Note:
If the file being read is defined as update, a temporary lock on the next record is requested and the search argument is compared to the key of that record. If the record is already locked, the program must wait until the record is available before obtaining the temporary lock and making the comparison. If the comparison is unequal, an EOF condition occurs, and the temporary record lock is removed. If no lock ('N' operation extender) is specified, a temporary lock is not requested.

Graphic and UCS-2 keys must have the same CCSID.

The name operand must be the name of the file or record format to be retrieved. A record format name is allowed only with an externally described file (identified by an E in position 22 of the file description specifications).

If the data-structure operand is specified, the record is read directly into the data structure. If name refers to a program-described file (identified by an F in position 22 of the file description specification), the data structure can be any data structure of the same length as the file's declared record length. If name refers to an externally-described file or a record format from an externally described file, the data structure must be a data structure defined with EXTNAME(...:*INPUT) or LIKEREC(...:*INPUT). See File Operations for information on how data is transferred between the file and the data structure.

If the file you are reading is an update disk file, you can specify an N operation extender to indicate that no lock should be placed on the record when it is read. See the WebSphere Development Studio: ILE RPG Programmer's Guide for more information.

To handle READE exceptions (file status codes greater than 1000), either the operation code extender 'E' or an error indicator ER can be specified, but not both. For more information on error handling, see File Exception/Errors.

You can specify an indicator in positions 75-76 that will be set on if an EOF condition occurs: that is, if a record is not found with a key equal to the search argument or if an end of file is encountered. This information can also be obtained from the %EOF built-in function, which returns '1' if an EOF condition occurs and '0' otherwise.

If a READE operation is not successful, you must reposition the file: for example, using a CHAIN, SETGT, or SETLL operation. See CHAIN (Random Retrieval from a File), SETGT (Set Greater Than), or SETLL (Set Lower Limit).

If you specify the search-arg operand and are processing a distributed data management (DDM) file that was created before Version 3 Release 1 Modification 0, a key comparison cannot be done at the data management level. READE will do a key comparison using a hexadecimal collating sequence. This may give different results than expected when DDS features are used that cause more than one search argument to match a given key in the file. For example, if ABSVAL is used on a numeric key, both -1 and 1 would succeed as search arguments for a key in the file with a value of 1. Using the hexadecimal collating sequence, a search argument of -1 will not succeed for an actual key of 1. The followng DDS features will cause the key comparison to differ:

  • ALTSEQ was specified for the file
  • ABSVAL, ZONE, UNSIGNED or DIGIT keywords on key fields
  • Variable length, Date, Time or Timestamp key fields
  • ALWNULL(*USRCTL) is specified as a keyword on a control specification or as a command parameter and a key in the record or search argument has a null value. The key in the file or search argument has null values. This applies only to externally described files.
  • SRTSEQ for the file is not hexadecimal
  • A numeric sign is different from the system-preferred sign

A READE with the search-arg operand specified that immediately follows an OPEN operation or an EOF condition retrieves the first record in the file if the key of the record matches the search argument. A READE with no search-arg specified that immediately follows an OPEN operation or an EOF condition results in an error condition. The error indicator in positions 73 and 74, if specified, is set on or the 'E' extender, checked with %ERROR, if specified, is set on. No further I/O operations can be issued against the file until it is successfully closed and reopened.

See Database Null Value Support for information on handling records with null-capable fields and keys.

Note:
Operation code extenders H, M, and R are allowed only when the search argument is a list or is %KDS().

Figure 316. READE Operation


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* With Factor 1 Specified...
*
* The READE operation retrieves the next record from the file
* FILEA and compares its key to the search argument, KEYFLD.
*
* The %EOF built-in function is set to return '1' if KEYFLD is
* not equal to the key of the record read or if end of file
* is encountered.
*
C KEYFLD READE FILEA
*
* The READE operation retrieves the next record of the type REC1
* from an externally described file and compares the key of the
* record read to the search argument, KEYFLD. (REC1 is a record
* format name.) Indicator 56 is set on if KEYFLD is not equal to
* the key of the record read or if end of file is encountered.
C KEYFLD READE REC1 56
*
* With No Factor 1 Specified...
*
* The READE operation retrieves the next record in the access
* path from the file FILEA if the key value is equal to
* the key value of the record at the current cursor position.
*
* If the key values are not equal, %EOF is set to return '1'.
C READE FILEA
*
* The READE operation retrieves the next record in the access
* path from the file FILEA if the key value equals the key value
* of the record at the current position. REC1 is a record format
* name. Indicator 56 is set on if the key values are unequal.
* N indicates that the record is not locked.
C READE(N) REC1 56

READP (Read Prior Record)


Free-Form Syntax READP{(EN)} name {data-structure}

Code Factor 1 Factor 2 Result Field Indicators
READP (E N)
name (file or record format) data-structure _ ER BOF

The READP operation reads the prior record from a full procedural file (identified by an F in position 18 of the file description specifications).

The name operand must be the name of a file or record format to be read. A record format name is allowed only with an externally described file. If a record format name is specified in name, the record retrieved is the first prior record of the specified type. Intervening records are bypassed.

If the data-structure operand is specified, the record is read directly into the data structure. If name refers to a program-described file (identified by an F in position 22 of the file description specification), the data structure can be any data structure of the same length as the file's declared record length. If name refers to an externally-described file or a record format from an externally described file, the data structure must be a data structure defined with EXTNAME(...:*INPUT) or LIKEREC(...:*INPUT). See File Operations for information on how data is transferred between the file and the data structure.

If a READP operation is successful, the file is positioned at the previous record that satisfies the read.

If the file from which you are reading is an update disk file, you can specify an N operation extender to indicate that no lock should be placed on the record when it is read. See the WebSphere Development Studio: ILE RPG Programmer's Guide for more information.

To handle READP exceptions (file status codes greater than 1000), either the operation code extender 'E' or an error indicator ER can be specified, but not both. For more information on error handling, see File Exception/Errors.

You can specify an indicator in positions 75-76 that will be set on when no prior records exist in the file (beginning of file condition). This information can also be obtained from the %EOF built-in function, which returns '1' if a BOF condition occurs and '0' otherwise.

You must reposition the file (for example, using a CHAIN, SETLL or SETGT operation) after an error or BOF condition to process any further successful sequential operations (for example, READ or READP).

See Database Null Value Support for information on reading records with null-capable fields.

Figure 317 shows READP operations with a file name and record format name specified in factor 2.

Figure 317. READP Operation


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* The READP operation reads the prior record from FILEA.
*
* The %EOF built-in function is set to return '1' if beginning
* of file is encountered. When %EOF returns '1', the program
* branches to the label BOF specified in the GOTO operation.
C READP FILEA
C IF %EOF
C GOTO BOF
C ENDIF

*
* The READP operation reads the next prior record of the type
* REC1 from an externally described file. (REC1 is a record
* format name.) Indicator 72 is set on if beginning of file is
* encountered during processing of the READP operation. When
* indicator 72 is set on, the program branches to the label BOF
* specified in the GOTO operation.
C READP PREC1 72
C 72 GOTO BOF

*
C BOF TAG

READPE (Read Prior Equal)


Free-Form Syntax READPE{(ENHMR)} search-arg|*KEY name {data-structure}

Code Factor 1 Factor 2 Result Field Indicators
READPE (E N) search-arg name (file or record format) data-structure _ ER BOF

The READPE operation retrieves the next prior sequential record from a full procedural file if the key of the record matches the search argument. If the key of the record does not match the search argument, a BOF condition occurs, and the record is not returned to the program. A BOF condition also applies when beginning of file occurs.

The search argument, search-arg, identifies the record to be retrieved. The search-arg operand is optional in traditional syntax but required in free-form syntax. search-arg can be:

  • A field name, a literal, a named constant, or a figurative constant.
  • A KLIST name for an externally described file.
  • A list of key values enclosed in parentheses. See Figure 246 for an example of searching using a list of key values.
  • %KDS to indicate that the search arguments are the subfields of a data structure. See the example at the end of %KDS (Search Arguments in Data Structure) for an illustration of search arguments in a data structure.
  • *KEY or (in traditional syntax only) no value. If the full key of the next prior record is equal to that of the current record, the next prior record in the file is retrieved. The full key is defined by the record format or file used in factor 2.

Graphic and UCS-2 keys must have the same CCSID.

The name operand must be the name of the file or record format to be retrieved. A record format name is allowed only with an externally described file (identified by an E in position 22 of the file description specifications).

If the data-structure operand is specified, the record is read directly into the data structure. If name refers to a program-described file (identified by an F in position 22 of the file description specification), the data structure can be any data structure of the same length as the file's declared record length. If name refers to an externally-described file or a record format from an externally described file, the data structure must be a data structure defined with EXTNAME(...:*INPUT) or LIKEREC(...:*INPUT). See File Operations for information on how data is transferred between the file and the data structure.

If the file from which you are reading is an update disk file, you can specify an N operation extender to indicate that no lock should be placed on the record when it is read. See the WebSphere Development Studio: ILE RPG Programmer's Guide for more information.

To handle READPE exceptions (file status codes greater than 1000), either the operation code extender 'E' or an error indicator ER can be specified, but not both. For more information on error handling, see File Exception/Errors.

You can specify an indicator in positions 75-76 that will be set on if a BOF condition occurs: that is, if a record is not found with a key equal to the search argument or if a beginning of file is encountered. This information can also be obtained from the %EOF built-in function, which returns '1' if a BOF condition occurs and '0' otherwise.

If a READPE operation is not successful, you must reposition the file: for example, using a CHAIN, SETGT, or SETLL operation. See CHAIN (Random Retrieval from a File), SETGT (Set Greater Than), or SETLL (Set Lower Limit).

Note:
If the file being read is defined as update, a temporary lock on the prior record is requested and the search argument is compared to the key of that record. If the record is already locked, the program must wait until the record is available before obtaining the temporary lock and making the comparison. If the comparison is unequal, a BOF condition occurs, and the temporary record lock is removed. If no lock ('N' operation extender) is specified, a temporary lock is not requested.

If you specify the search-arg operand and are processing a distributed data management (DDM) file that was created before Version 3 Release 1 Modification 0, a key comparison cannot be done at the data management level. READPE will do a key comparison using a hexadecimal collating sequence. This may give different results than expected when DDS features are used that cause more than one search argument to match a given key in the file. For example, if ABSVAL is used on a numeric key, both -1 and 1 would succeed as search arguments for a key in the file with a value of 1. Using the hexadecimal collating sequence, a search argument of -1 will not succeed for an actual key of 1. The following DDS features will cause the key comparison to differ:

  • ALTSEQ was specified for the file
  • ABSVAL, ZONE, UNSIGNED or DIGIT keywords on key fields
  • Variable length, Date, Time or Timestamp key fields
  • ALWNULL(*USRCTL) is specified as a keyword on a control specification or as a command parameter and a key in the record or search argument has a null value. The key in the file or search argument has null values. This applies only to externally described files.
  • SRTSEQ for the file is not hexadecimal
  • A numeric sign is different from the system-preferred sign

A READPE with the search-arg operand specified that immediately follows an OPEN operation or a BOF condition returns BOF. A READPE with no search-arg specified that immediately follows an OPEN operation or a BOF condition results in an error condition. The error indicator in positions 73 and 74, if specified, is set on or the 'E' extender, checked with %ERROR, if specified, is set on. The file must be repositioned using a CHAIN, SETLL, READ, READE or READP with search-arg specified, prior to issuing a READPE operation with factor 1 blank. A SETGT operation code should not be used to position the file prior to issuing a READPE (with no search-arg specified) as this results in a record-not-found condition (because the record previous to the current record never has the same key as the current record after a SETGT is issued). If search-arg is specified with the same key for both operation codes, then this error condition will not occur.

See Database Null Value Support for information on handling records with null-capable fields and keys.

Note:
Operation code extenders H, M, and R are allowed only when the search argument is a list or is %KDS().

Figure 318. READPE Operation


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* With Factor 1 Specified...
*
* The previous record is read and the key compared to FieldA.
* Indicator 99 is set on if the record's key does not match
* FieldA.
C FieldA READPE FileA 99
*
* The previous record is read from FileB and the key compared
* to FieldB. The record is placed in data structure Ds1. If
* the record key does not match FieldB, indicator 99 is set on.
C FieldB READPE FileB Ds1 99
*
* The previous record from record format RecA is read, and
* the key compared to FieldC. Indicator 88 is set on if the
* operation is not completed successfully, and 99 is set on if
* the record key does not match FieldC.
C FieldC READPE RecA 8899
*
* With No Factor 1 Specified...
*
* The previous record in the access path is retrieved if its
* key value equals the key value of the current record.
* Indicator 99 is set on if the key values are not equal.
C READPE FileA 99
*
* The previous record is retrieved from FileB if its key value
* matches the key value of the record at the current position
* in the file. The record is placed in data structure Ds1.
* Indicator 99 is set on if the key values are not equal.
C READPE FileB Ds1 99
*
* The previous record from record format RecA is retrieved if
* its key value matches the key value of the current record in
* the access path. Indicator 88 is set on if the operation is
* not successful; 99 is set on if the key values are unequal.
C READPE RecA 8899

REALLOC (Reallocate Storage with New Length)


Free-Form Syntax (not allowed - use the %REALLOC built-in function)

Code Factor 1 Factor 2 Result Field Indicators
REALLOC (E)
Length Pointer _ ER _

The REALLOC operation changes the length of the heap storage pointed to by the result-field pointer to the length specified in factor 2. The result field of REALLOC contains a basing pointer variable. The result field pointer must contain the value previously set by a heap-storage allocation operation (either an ALLOC or REALLOC operation in RPG or some other heap-storage function such as CEEGTST). It is not sufficient to simply point to heap storage; the pointer must be set to the beginning of an allocation.

New storage is allocated of the specified size and the value of the old storage is copied to the new storage. Then the old storage is deallocated. If the new length is shorter, the value is truncated on the right. If the new length is longer, the new storage to the right of the copied data is uninitialized.

The result field pointer is set to point to the new storage.

If the operation does not succeed, an error condition occurs, but the result field pointer will not be changed. If the original pointer was valid and the operation failed because there was insufficient new storage available (status 425), the original storage is not deallocated, so the result field pointer is still valid with its original value.

If the pointer is valid but it does not point to storage that can be deallocated, then status 426 (error in storage management operation) will be set.

To handle exceptions with program status codes 425 or 426, either the operation code extender 'E' or an error indicator ER can be specified, but not both. For more information on error handling, see Program Exception/Errors.

Factor 2 contains a numeric variable or constant that indicates the new size of the storage (in bytes) to be allocated. Factor 2 must be numeric with zero decimal positions. The value must be between 1 and 16776704.

For more information, see Memory Management Operations.

Figure 319. REALLOC Operation


 D Ptr1            S               *

D Fld S 32767A BASED(Ptr1)

* The ALLOC operation allocates 7 bytes to the pointer Ptr1.
* After the ALLOC operation, only the first 7 bytes of variable
* Fld can be used.
C ALLOC 7 Ptr1
C EVAL %SUBST(Fld : 1 : 7) = '1234567'
C REALLOC 10 Ptr1

* Now 10 bytes of Fld can be used.
C EVAL %SUBST(Fld : 1 : 10) = '123456789A'

REL (Release)


Free-Form Syntax REL{(E)} program-device file-name

Code Factor 1 Factor 2 Result Field Indicators
REL (E) program-device file-name
_ ER _

The REL operation releases the program device specified in program-device from the WORKSTN file specified in file-name.

Specify the program device name in the program-device operand. Use either a character field of length 10 or less, a character literal, or a named constant. Specify the file name in file-name operand.

To handle REL exceptions (file status codes greater than 1000), either the operation code extender 'E' or an error indicator ER can be specified, but not both. For more information on error handling, see File Exception/Errors.

When there are no program devices acquired to a WORKSTN file, the next READ-by-file-name or cycle-read gets an end-of-file condition. You must decide what the program does next. The REL operation may be used with a multiple device file or, for error recovery purpose, with a single device file.

Note:
To release a record lock, use the UNLOCK operation. See the UNLOCK operation for more information about releasing record locks for update disk files.

RESET (Reset)


Free-Form Syntax RESET{(E)} {*NOKEY} {*ALL} name

Code Factor 1 Factor 2 Result Field Indicators
RESET (E) *NOKEY *ALL name (variable or record format) _ ER _

The RESET operation is used to restore a variable to the value held at the end of the *INIT phase. This value is called the reset value. If there is no *INZSR subroutine, the reset value is the same as the initial value (either the value specified by the INZ{(initial value)}, or the default value). If there is a *INZSR subroutine, the reset value is the value the variable holds when the *INZSR subroutine has completed.

The RESET operation can also be used to restore all the fields in a record format to their reset values.

See Figure 6 for more information on the *INIT phase.

Note:
For local variables in subprocedures, the reset value is the value of the variable when the subprocedure is first called, but before the calculations begin.

To handle RESET exceptions (program status code 123), either the operation code extender 'E' or an error indicator ER can be specified, but not both. For more information on error handling, see Program Exception/Errors.

Resetting Variables

*ALL is optional. If *ALL is specified and the name operand is a multiple occurrence data structure or a table name, all occurrences or table elements are reset and the occurrence level or table index is set to 1.

The name operand specifies the variable to be reset. The particular value for this operand determines the reset action as follows:

Single occurrence data structure
All fields are reset in the order in which they are declared within the structure.
Multiple-occurrence data structure
If *ALL is not specified, then all fields in the current occurrence are reset. If *ALL is specified, then all fields in all occurrences are reset.
Table name
If *ALL is not specified, then the current table element is reset. If *ALL is specified, then all table elements are reset.
Array name
Entire array is reset
Array element (including indicators)
Only the element specified is reset.

Resetting Record Formats

*NOKEY is optional. If *NOKEY is specified, then key fields are not reset to their reset values.

*ALL is optional. If *ALL is specified and *NOKEY is not, all fields in the record format are reset. If *ALL is not specified, only those fields that are output in that record format are affected. If *NOKEY is specified, then key fields are not reset, even if *ALL is specified.

The result field contains the record format to be reset. For WORKSTN file record formats (positions 36-42 on a file-description specification), if *ALL is not specified, only those fields with a usage of output or both are affected. All field-conditioning indicators of the record format are affected by the operation. When the RESET operation is applied to a record format name, and INDARA has been specified in the DDS, the indicators in the record format are not reset.

Fields in DISK, SEQ, or PRINTER file record formats are affected only if the record format is output in the program. Input-only fields are not affected by the RESET operation, except when *ALL is specified.

A RESET operation of a record format with *ALL specified is not valid when:

  • A field is defined externally as input-only, and the record was not used for input.
  • A field is defined externally as output-only, and the record was not used for output.
  • A field is defined externally as both input and output capable, and the record was not used for either input or output.
Note:
Input-only fields in logical files will appear in the output specifications, although they are not actually written to the file. When a CLEAR or RESET without *ALL specified is done to a record containing these fields, then these fields will be cleared or reset because they appear in the output specifications.

Additional Considerations

Keep in mind the following when coding a RESET operation:

  • RESET is not allowed for based variables and IMPORTed variables, or for parameters in a subprocedure.
  • The RESET operation results in an increase in the amount of storage required by the program. For any variable that is reset, the storage requirement is doubled. Note that for multiple occurrence data structures, tables and arrays, the reset value of every occurrence or element is saved.
  • If a RESET occurs during the initialization routine of the program, an error message will be issued at run time. If a GOTO or CABxx is used to leave subroutine calculations during processing of the *INZSR, or if control passes to another part of the cycle as the result of error processing, the part of the initialization step which initializes the save areas will never be reached. In this case, an error message will be issued for all RESET operations in the program at run time.
  • A RESET operation within a subprocedure to a global variable or structure is valid in the following circumstances:
    • If there is no *INZSR, it is always valid
    • If there is a *INZSR, it is not valid until the *INZSR has completed at least once. After that, it is always valid, even if the main procedure is not active.
Attention!

When the RESET values are saved, a pointer-not-set error will occur if the following are all true:

  • There is no *INZSR
  • An entry parameter to the main procedure is RESET anywhere in the module
  • A subprocedure is called before the main procedure has ever been called

For more information, see CLEAR (Clear).

RESET Examples

Except for the actual operation performed on the fields, the considerations shown in the following examples also apply to the CLEAR operation. Figure 320 shows an example of the RESET operation with *NOKEY.

Figure 320. RESET Operation with *NOKEY


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

FFilename++IPEASFRlen+LKlen+AIDevice+.Keywords++++++++++++++++++++++++++++
FEXTFILE O E DISK
DName+++++++++++ETDsFrom+++To/L+++IDc.Functions+++++++++++++++++++++++++++
* The file EXTFILE contains one record format RECFMT containing
* the character fields CHAR1 and CHAR2 and the numeric fields
* NUM1 and NUM2. It has keyfields CHAR2 and NUM1.
D
D DS1 DS
D DAY1 1 8 INZ('MONDAY')
D DAY2 9 16 INZ('THURSDAY')
D JDATE 17 22
D

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq...
*
* The following operation sets DAY1, DAY2, and JDATE to blanks.
C
C CLEAR DS1
C

* The following operation will set DAY1, DAY2, and JDATE to their
* reset values of 'MONDAY', 'THURSDAY', and UDATE respectively.
* The reset value of UDATE for JDATE is set in the *INZSR.
C
C RESET DS1
C

* The following operation will set CHAR1 and CHAR2 to blanks and
* NUM1 and NUM2 to zero.
C CLEAR RECFMT
* The following operation will set CHAR1, CHAR2, NUM1, and
* NUM2 to their reset values of 'NAME', 'ADDRESS', 1, and 2
* respectively. These reset values are set in the *INZSR.
*
C RESET RECFMT
* The following operation sets all fields in the record format
* to blanks, except the key fields CHAR2 and NUM1.
*
C *NOKEY RESET *ALL RECFMT
C RETURN
C
C *INZSR BEGSR
C MOVEL UDATE JDATE
C MOVEL 'NAME ' CHAR1
C MOVEL 'ADDRESS ' CHAR2
C Z-ADD 1 NUM1
C Z-ADD 2 NUM2
C ENDSR

ORCDNAME+++D...N01N02N03EXCNAM++++........................................
O..............N01N02N03FIELD+++++++++.B..................................
ORECFMT T
O CHAR1
O CHAR2
O NUM1
O NUM2

Figure 321. DDS for EXTFILE


     A          R RECFMT

A CHAR1 10A
A CHAR2 10A
A NUM1 5P 0
A NUM2 7S 2

Figure 322 shows an excerpt of a source listing for a program that uses two externally described files, RESETIB and RESETON. Each has two record formats, and each record format contains an input field FLDIN, an output field FLDOUT, and a field FLDBOTH, that is input-output capable. The DDS are shown in Figure 323 and Figure 324.

Because RESETIB is defined as a combined file, the fields for RECBOTH, which are defined as input-output capable, are available on both input and output specifications. On the other hand, the fields for RECIN are on input specifications only.

Figure 322. RESET with *ALL - Source Listing Excerpt. The input and output specifications with '=' after the listing line number are generated by the compiler.


     1  * The file RESETIB contains 2 record formats RECIN and RECBOTH.

2 FRESETIB CF E WORKSTN
3 * The file RESETON contains 2 record formats RECOUT and RECNONE.
4 FRESETON O E WORKSTN
5
6=IRECIN
7=I A 1 1 *IN02
8=I A 2 11 FLDIN
9=I A 12 21 FLDBOTH
10=IRECBOTH
11=I A 1 1 *IN04
12=I A 2 11 FLDIN
13=I A 12 21 FLDBOTH
14 C WRITE RECOUT
15 C WRITE RECBOTH
16 C READ RECIN ----99
17 C READ RECBOTH ----99
18
19 * RESET without factor 2 means to reset only those fields which
20 * appear on the output specifications for the record format.
21 * Since only RECOUT and RECBOTH have write operations, the
22 * RESET operations for RECNONE and RECIN will have no effect.
23 * The RESET operations for RECOUT and RECBOTH will reset fields
24 * FLDOUT and FLDBOTH. FLDIN will not be affected.
25 C RESET RECNONE
26 C RESET RECIN
27 C RESET RECOUT
28 C RESET RECBOTH
29
30 * RESET with *ALL in factor 2 means to reset all fields. Note
31 * that this can only be done when all fields are used in at least
32 * one of the ways they are defined (for example, an output-capable
33 * field must be used for output by the record format)
34 * Since RECNONE does not have either input or output operations,
35 * the RESET *ALL for RECNONE will fail at compile time.
36 * Since RECIN does not have any output operations, RESET *ALL RECIN
37 * will fail because FLDOUT is not output.
38 * Since RECOUT does not have any input operations, and is not defined
39 * as input capable on the file specification, RESET *ALL RECOUT
40 * will fail because FLDIN is not input.
41 * The RESET *ALL for RECBOTH will reset all fields: FLDIN, FLDOUT
42 * and FLDBOTH.
43 C RESET *ALL RECNONE
44 C RESET *ALL RECIN
45 C RESET *ALL RECOUT
46 C RESET *ALL RECBOTH
47
48 C SETON LR----
49=ORECBOTH
50=O *IN14 1A CHAR 1
51=O FLDOUT 11A CHAR 10
52=O FLDBOTH 21A CHAR 10
53=ORECOUT
54=O *IN13 1A CHAR 1
55=O FLDOUT 11A CHAR 10
56=O FLDBOTH 21A CHAR 10

When the source is compiled, several errors are identified. Both RECNONE and RECIN are identified as having no output fields. The RESET *ALL is disallowed for all but the RECBOTH record, since it is the only record format for which all fields appear on either input or output specifications.

Figure 323. DDS for RESETIB


     A          R RECIN                     CF02(02)

A FLDIN 10A I 2 2
A FLDOUT 10A O 3 2
A 12 FLDBOTH 10A B 4 2
A R RECBOTH CF04(04)
A FLDIN 10A I 2 2
A FLDOUT 10A O 3 2
A 14 FLDBOTH 10A B 4 2

Figure 324. DDS for RESETON


     A          R RECNONE                   CF01(01)

A FLDIN 10A I 2 2
A FLDOUT 10A O 3 2
A 11 FLDBOTH 10A B 4 2
A R RECOUT CF03(03)
A FLDIN 10A I 2 2
A FLDOUT 10A O 3 2
A 13 FLDBOTH 10A B 4 2


RETURN (Return to Caller)


Free-Form Syntax RETURN{(HMR)} expression

Code Factor 1 Extended Factor 2
RETURN (H M/R)
expression

The RETURN operation causes a return to the caller. If a value is returned to the caller, the return value is specified in the expression operand.

The actions which occur as a result of the RETURN operation differ depending on whether the operation is in a subprocedure. When a program or main procedure returns, the following occurs:

  1. The halt indicators are checked. If a halt indicator is on, the procedure ends abnormally. (All open files are closed, an error return code is set to indicate to the calling routine that the procedure has ended abnormally, and control returns to the calling routine.)
  2. If no halt indicators are on, the LR indicator is checked. If LR is on, the program ends normally. (Locked data area structures, arrays, and tables are written, and external indicators are reset.)
  3. If no halt indicator is on and LR is not on, the procedure returns to the calling routine. Data is preserved for the next time the procedure is run. Files and data areas are not written out. See the chapter on calling programs and procedures in the WebSphere Development Studio: ILE RPG Programmer's Guide for information on how running in a *NEW activation group affects the operation of RETURN.

When a subprocedure returns, the return value, if specified on the prototype of the called program or procedure, is passed to the caller. Nothing else occurs automatically. All files and data areas must be closed manually. You can set on indicators such as LR, but this will not cause program termination to occur. For information on how operation extenders H, M, and R are used, see Precision Rules for Numeric Operations.

In a subprocedure that returns a value, a RETURN operation must be coded within the subprocedure. The actual returned value has the same role as the left-hand side of the EVAL expression, while the extended factor 2 of the RETURN operation has the same role as the right-hand side. An array may be returned only if the prototype has defined the return value as an array.

Attention!

If the subprocedure returns a value, you should ensure that a RETURN operation is performed before reaching the end of the procedure. If the subprocedure ends without encountering a RETURN operation, an exception is signalled to the caller.

Figure 325. Examples of the RETURN Operation


      * This is the prototype for subprocedure RETNONE. Since the

* prototype specification does not have a data type, this
* subprocedure does not return a value.
D RetNone PR
* This is the prototype for subprocedure RETFLD. Since the
* prototype specification has the type 5P 2, this subprocedure
* returns a packed value with 5 digits and 2 decimals.
* The subprocedure has a 5-digit integer parameter, PARM,
* passed by reference.
D RetFld PR 5P 2
D Parm 5I 0

* This is the prototype for subprocedure RETARR. The data
* type entries for the prototype specification show that
* this subprocedure returns a date array with 3 elements.
* The dates are in *YMD/ format.
D RetArr PR D DIM(3) DATFMT(*YMD/)
* This procedure (P) specification indicates the beginning of
* subprocedure RETNONE. The data specification (D) specification
* immediately following is the procedure-interface
* specification for this subprocedure. Note that the
* procedure interface is the same as the prototype except for
* the definition type (PI vs PR).
P RetNone B
D RetNone PI

* RetNone does not return a value, so the RETURN
* operation does not have factor 2 specified.
C RETURN
P RetNone E

* The following 3 specifications contain the beginning of
* the subprocedure RETFLD as well as its procedure interface.
P RetFld B
D RetFld PI 5P 2
D Parm 5I 0
D Fld S 12S 1 INZ(13.8)

* RetFld returns a numeric value. The following RETURN
* operations show returning a literal, an expression and a
* variable. Note that the variable is not exactly the same
* format or length as the actual return value.
C RETURN 7
C RETURN Parm * 15
C RETURN Fld
P RetFld E

      * The following 3 specifications contain the beginning of the

* subprocedure RETARR as well as its procedure interface.
P RetArr B
D RetArr PI D DIM(3)
D SmallArr S D DIM(2) DATFMT(*ISO)
D BigArr S D DIM(4) DATFMT(*USA)

* RetArr returns a date array. Note that the date
* format of the value specified on the RETURN operation
* does not have to be the same as the defined return
* value.
* The following RETURN operation specifies a literal.
* The caller receives an array with the value of the
* literal in every element of the array.
C RETURN D'1995-06-27'
* The following return operation returns an array
* with a smaller dimension than the actual return value.
* In this case, the third element would be set to the
* default value for the array.
C RETURN SmallArr
* The following return operation returns an array
* with a larger dimension than the actual return
* value. In this case, the fourth element of BigArr
* would be ignored.
C RETURN BigArr
P RetArr E


ROLBK (Roll Back)


Free-Form Syntax ROLBK{(E)}

Code Factor 1 Factor 2 Result Field Indicators
ROLBK (E)


_ ER _

The ROLBK operation:

  • Eliminates all the changes to your files that have been specified in output operations since the previous COMMIT or ROLBK operation (or since the beginning of operations under commitment control if there has been no previous COMMIT or ROLBK operation).
  • Releases all the record locks for the files you have under commitment control.
  • Repositions the file to its position at the time of the previous COMMIT operation (or at the time of the file OPEN, if there has been no previous COMMIT operation.)

Commitment control starts when the CL command STRCMTCTL is executed. See the chapter on "Commitment Control" in the WebSphere Development Studio: ILE RPG Programmer's Guide for more information.

The file changes and the record-lock releases apply to all the files under commitment control in your activation group or job, whether the changes have been requested by the program issuing the ROLBK operation or by another program in the same activation group or job. The program issuing the ROLBK operation does not need to have any files under commitment control. For example, suppose program A calls program B and program C. Program B has files under commitment control, and program C does not. A ROLBK operation in program C still affects the files changed by program B.

To handle ROLBK exceptions (program status codes 802 to 805), either the operation code extender 'E' or an error indicator ER can be specified, but not both. For more information on error handling, see Program Exception/Errors.

For information on how the rollback function is performed by the system, refer to Backup and Recovery, SC41-5304-06.


SCAN (Scan String)


Free-Form Syntax (not allowed - use the %SCAN built-in function)

Code Factor 1 Factor 2 Result Field Indicators
SCAN (E) Compare string:length Base string:start Left-most position _ ER FD

The SCAN operation scans a string (base string) contained in factor 2 for a substring (compare string) contained in factor 1. The scan begins at a specified location contained in factor 2 and continues for the length of the compare string which is specified in factor 1. The compare string and base string must both be of the same type, either both character, both graphic, or both UCS-2.

Factor 1 must contain either the compare string or the compare string, followed by a colon, followed by the length. The compare string portion of factor 1 can contain one of: a field name, array element, named constant, data structure name, literal, or table name. The length portion must be numeric with no decimal positions and can contain one of: a named constant, array element, field name, literal, or table name. If no length is specified, it is that of the compare string.

Factor 2 must contain either the base string or the base string, followed by a colon, followed by the start location of the SCAN. The base string portion of factor 2 can contain one of: a field name, array element, named constant, data structure name, literal, or table name. The start location portion of factor 2 must be numeric with no decimal positions and can be a named constant, array element, field name, literal, or table name. If graphic or UCS-2 strings are used, the start position and length are measured in double bytes. If no start location is specified, a value of 1 is used.

The result field contains the numeric value of the leftmost position of the compare string in the base string, if found. It must be numeric with no decimal positions and can contain one of: a field name, array element, array name, or table name. The result field is set to 0 if the string is not found. If the result field contains an array, each occurrence of the compare string is placed in the array with the leftmost occurrence in element 1. The array elements following the element containing the rightmost occurrence are all zero. The result array should be as large as the field length of the base string specified in factor 2.

Notes:

  1. The strings are indexed from position 1.
  2. If the start position is greater than 1, the result field contains the position of the compare string relative to the beginning of the source string, not relative to the start position.
  3. Figurative constants cannot be used in the factor 1, factor 2, or result fields.
  4. No overlapping within data structures is allowed for factor 1 and the result field or factor 2 and the result field.

To handle SCAN exceptions (program status code 100), either the operation code extender 'E' or an error indicator ER can be specified, but not both. An error occurs if the start position is greater than the length of factor 2 or if the value of factor 1 is too large. For more information on error handling, see Program Exception/Errors.

You can specify an indicator in positions 75-76 that is set on if the string being scanned for is found. This information can also be obtained from the %FOUND built-in function, which returns '1' if a match is found.

The SCAN begins at the leftmost character of factor 2 (as specified by the start location) and continues character by character, from left to right, comparing the characters in factor 2 to those in factor 1. If the result field is not an array, the SCAN operation will locate only the first occurrence of the compare string. To continue scanning beyond the first occurrence, use the result field from the previous SCAN operation to calculate the starting position of the next SCAN. If the result field is a numeric array, as many occurrences as there are elements in the array are noted. If no occurrences are found, the result field is set to zero; if the result field is an array, all its elements are set to zero.

Leading, trailing, or embedded blanks specified in the compare string are included in the SCAN operation.

The SCAN operation is case-sensitive. A compare string specified in lowercase will not be found in a base string specified in uppercase.

Figure 326. SCAN Operation


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* The SCAN operation finds the substring 'ABC' starting in
* position 3 in factor 2; 3 is placed in the result field.
* Indicator 90 is set on because the string is found. Because
* no starting position is specified, the default of 1 is used.
C 'ABC' SCAN 'XCABCD' RESULT 90
*
* This SCAN operation scans the string in factor 2 for an
* occurrence of the string in factor 1 starting at position 3.
* The 'Y' in position 1 of the base string is ignored because
* the scan operation starts from position 3.
* The operation places the values 5 and 6 in the first and
* second elements of the array. Indicator 90 is set on.
C
C MOVE 'YARRYY' FIELD1 6
C MOVE 'Y' FIELD2 1
C FIELD2 SCAN FIELD1:3 ARRAY 90

*
* This SCAN operation scans the string in factor 2, starting
* at position 2, for an occurrence of the string in factor 1
* for a length of 4. Because 'TOOL' is not found in FIELD1,
* INT is set to zero and indicator 90 is set off.
C
C MOVE 'TESTING' FIELD1 7
C Z-ADD 2 X 1 0
C MOVEL 'TOOL' FIELD2 5
C FIELD2:4 SCAN FIELD1:X INT90 20
C

*
* The SCAN operation is searching for a name. When the name
* is found, %FOUND returns '1' so HandleLine is called.
C SrchName SCAN Line
C IF %FOUND
C EXSR HandleLine
C ENDIF

Figure 327. SCAN Operation using graphic


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

DName+++++++++++ETDsFrom+++To/L+++IDc.Functions+++++++++++++++++++++++++
*
* A Graphic SCAN example
*
* Value of Graffld is graphic 'AACCBBGG'.
* Value of Number after the scan is 3 as the 3rd graphic
* character matches the value in factor 1
D Graffld S 4G inz(G'oAACCBBGGi')
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq..
* The SCAN operation scans the graphic string in factor 2 for
* an occurrence of the graphic literal in factor 1. As this is a
* graphic operation, the SCAN will operate on 2 bytes at a time
C
C G'oBBi' SCAN Graffld:2 Number 5 0 90
C


SELECT (Begin a Select Group)


Free-Form Syntax SELECT

Code Factor 1 Factor 2 Result Field Indicators
SELECT





The select group conditionally processes one of several alternative sequences of operations. It consists of:

After the SELECT operation, control passes to the statement following the first WHENxx condition that is satisfied. All statements are then executed until the next WHENxx operation. Control passes to the ENDSL statement (only one WHENxx is executed). If no WHENxx condition is satisfied and an OTHER operation is specified, control passes to the statement following the OTHER operation. If no WHENxx condition is satisfied and no OTHER operation is specified, control transfers to the statement following the ENDSL operation of the select group.

Conditioning indicators can be used on the SELECT operation. If they are not satisfied, control passes immediately to the statement following the ENDSL operation of the select group. Conditioning indicators cannot be used on WHENxx, WHEN, OTHER and ENDSL operation individually.

The select group can be specified anywhere in calculations. It can be nested within IF, DO, or other select groups. The IF and DO groups can be nested within select groups.

If a SELECT operation is specified inside a select group, the WHENxx and OTHER operations apply to the new select group until an ENDSL is specified.

Figure 328. SELECT Operation


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* In the following example, if X equals 1, do the operations in
* sequence 1 (note that no END operation is needed before the
* next WHENxx); if X does NOT equal 1, and if Y=2 and X<10,>C SELECT
C WHEN X = 1
C Z-ADD A B
C MOVE C D
* Sequence 1
C :
C WHEN ((Y = 2) AND (X <>
*
* The following example shows a select group with conditioning
* indicators. After the CHAIN operation, if indicator 10 is on,
* then control passes to the ADD operation. If indicator 10 is
* off, then the select group is processed.
*
C KEY CHAIN FILE 10
C N10 SELECT
C WHEN X = 1
* Sequence 1
C :
C WHEN Y = 2
* Sequence 2
C :
C ENDSL
C ADD 1 N


SETGT (Set Greater Than)


Free-Form Syntax SETGT{(EHMR)} search-arg name

Code Factor 1 Factor 2 Result Field Indicators
SETGT (E) search-arg name (file or record format)
NR ER _

The SETGT operation positions a file at the next record with a key or relative record number that is greater than the key or relative record number specified in factor 1. The file must be a full procedural file (identified by an F in position 18 of the file description specifications).

The search argument, search-arg, must be the key or relative record number used to retrieve the record. If access is by key, search-arg can be a a single key in the form of a field name, a named constant, a figurative constant, or a literal. See Figure 246 for an example of searching key fields.

If the file is an externally-described file, search-arg can also be a composite key in the form of a KLIST name, a list of values, or %KDS. Graphic and UCS-2 key fields must have the same CCSID as the key in the file. See the example at the end of %KDS (Search Arguments in Data Structure) for an illustration of search arguments in a data structure. If access is by relative record number, search-arg must be an integer literal or a numeric field with zero decimal positions.

The name operand is required and must be either a file name or a record format name. A record format name is allowed only with an externally described file.

You can specify an indicator in positions 71-72 that is set on if no record is found with a key or relative record number that is greater than the search argument specified (search-arg). This information can also be obtained from the %FOUND built-in function, which returns '0' if no record is found, and '1' if a record is found..

To handle SETGT exceptions (file status codes greater than 1000), either the operation code extender 'E' or an error indicator ER can be specified, but not both. For more information on error handling, see File Exception/Errors.

If the SETGT operation is not successful (no-record-found condition), the file is positioned to the end of the file.

Figurative constants can also be used to position the file.

Note:
The discussion and examples of using figurative constants which follow, assume that *LOVAL and *HIVAL are not used as actual keys in the file.

When used with a file with a composite key, figurative constants are treated as though each field of the key contained the figurative constant value. In most cases, *LOVAL positions the file so that the first read retrieves the record with the lowest key. In most cases, *HIVAL positions the file so that a READ receives an end-of-file indication; a subsequent READP retrieves the last record in the file. However, note the following cases for using *LOVAL and *HIVAL:

  • With an externally described file that has a key in descending order, *HIVAL positions the file so that the first read operation retrieves the first record in the file (the record with the highest key), and *LOVAL positions the file so that a READP operation retrieves the last record in the file (the record with the lowest key).
  • If a record is added or a key field is altered after a SETGT operation with either *LOVAL or *HIVAL, the file may no longer be positioned to the record with the lowest or highest key. key value X'99...9D' and *HIVAL for numeric keys represents a key value X'99...9F'. If the keys are float numeric, *LOVAL and *HIVAL are defined differently. See Figurative Constants. When a program described file has a packed decimal key specified in the file specifications but the actual file key field contains character data, records may have keys that are less than *LOVAL or greater than *HIVAL. When a key field contains unsigned binary data, *LOVAL may not be the lowest key.

When *LOVAL or *HIVAL are used with key fields with a Date or Time data type, the values are dependent of the Date-Time format used. For details on these values please see Data Types and Data Formats.

Following the SETGT operation, a file is positioned so that it is immediately before the first record whose key or relative record number is greater than the search argument specified (search-arg). You retrieve this record by reading the file. Before you read the file, however, records may be deleted from the file by another job or through another file in your job. Thus, you may not get the record you expected. For information on preventing unexpected modification of your files, see the discussion of allocating objects in the iSeries Information Center Programming topic at URL http://www.ibm.com/eserver/iseries/infocenter.

See Database Null Value Support for information on handling records with null-capable fields and keys.

Note:
Operation code extenders H, M, and R are allowed only when the search argument is a list or is %KDS().

Figure 329. SETGT Operation


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
* This example shows how to position the file so READ will read
* the next record. The search argument, KEY, specified for the
* SETGT operation has a value of 98; therefore, SETGT positions
* the file before the first record of file format FILEA that
* has a key field value greater than 98. The file is positioned
* before the first record with a key value of 100. The READ
* operation reads the record that has a value of 100 in its key
* field.
C
C KEY SETGT FILEA
C READ FILEA 64

*
* This example shows how to read the last record of a group of
* records with the same key value and format from a program
* described file. The search argument, KEY, specified for the
* SETGT operation positions the file before the first record of
* file FILEB that has a key field value greater than 70.
* The file is positioned before the first record with a key
* value of 80. The READP operation reads the last record that
* has a value of 70 in its key field.
C
C KEY SETGT FILEB
C READP FILEB 64

*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* This example shows the use of *LOVAL. The SETLL operation
* positions the file before the first record of a file in
* ascending order. The READ operation reads the first record
* (key value 97).
C
C *LOVAL SETLL RECDA
C READ RECDA 64
C

* This example shows the use of *HIVAL. The SETGT operation
* positions the file after the last record of a file in ascending
* order. The READP operation reads the last record (key value 91).
C
C *HIVAL SETGT RECDB
C READP RECDB 64


SETLL (Set Lower Limit)


Free-Form Syntax SETLL{(EHMR)} search-arg name

Code Factor 1 Factor 2 Result Field Indicators
SETLL (E) search-arg name (file or record format)
NR ER EQ

The SETLL operation positions a file at the next record that has a key or relative record number that is greater than or equal to the search argument (key or relative record number) operand specified (search-arg). The file must be a full procedural file (identified by an F in position 18 of the file description specifications).

The search argument, search-arg, must be the key or relative record number used to retrieve the record. If access is by key, search-arg can be a a single key in the form of a field name, a named constant, a figurative constant, or a literal. See Figure 246 for an example of searching key fields.

If the file is an externally-described file, search-arg can also be a composite key in the form of a KLIST name, a list of values, or %KDS. Graphic and UCS-2 key fields must have the same CCSID as the key in the file. See the example at the end of %KDS (Search Arguments in Data Structure) for an illustration of search arguments in a data structure. If access is by relative record number, search-arg must be an integer literal or a numeric field with zero decimal positions.

The name operand is required and can contain either a file name or a record format name. A record format name is allowed only with an externally described file.

The resulting indicators reflect the status of the operation. You can specify an indicator in positions 71-72 that is set on when the search argument is greater than the highest key or relative record number in the file. This information can also be obtained from the %FOUND built-in function, which returns '0' if no record is found, and '1' if a record is found.

To handle SETLL exceptions (file status codes greater than 1000), either the operation code extender 'E' or an error indicator ER can be specified, but not both. For more information on error handling, see File Exception/Errors.

You can specify an indicator in positions 75-76 that is set on when a record is present whose key or relative record number is equal to the search argument. This information can also be obtained from the %EQUAL built-in function, which returns '1' if an exact match is found.

When using SETLL with an indicator in positions 75 and 76 or with %EQUAL to process a distributed data management (DDM) file, which was created before Version 3 Release 1 Modification 0, a key comparison cannot be done at the data management level. SETLL will do a key comparison using a hexadecimal collating sequence. This may give different results than expected when DDS features are used that cause more than one search argument to match a given key in the file. For example, if ABSVAL is used on a numeric key, both -1 and 1 would succeed as search arguments for a key in the file with a value of 1. Using the hexadecimal collating sequence, a search argument of -1 will not succeed for an actual key of 1. The following DDS features will cause the key comparison to differ:

  • ALTSEQ was specified for the file
  • ABSVAL, ZONE, UNSIGNED or DIGIT keywords on key fields
  • Variable length, Date, Time or Timestamp key fields
  • ALWNULL(*USRCTL) is specified as a keyword on a control specification or as a command parameter and a key in the record or search argument has a null value. The key in the file or search argument has null values. This applies only to externally described files.
  • SRTSEQ for the file is not hexadecimal
  • A numeric sign is different from the system-preferred sign

If name is a file name for which the lower limit is to be set, the file is positioned at the first record with a key or relative record number equal to or greater than the search argument specified (search-arg).

If name is a record format name for which the lower limit is to be set, the file is positioned at the first record of the specified type that has a key equal to or greater than the search argument specified (search-arg).

Figurative constants can be used to position the file.

Note:
The discussion and examples of using figurative constants which follow, assume that *LOVAL and *HIVAL are not used as actual keys in the file.

When used with a file with a composite key, figurative constants are treated as though each field of the key contained the figurative constant value. Using SETLL with *LOVAL positions the file so that the first read retrieves the record with the lowest key. In most cases (when duplicate keys are not allowed), *HIVAL positions the file so that a READP retrieves the last record in the file, or a READ receives an end-of-file indication. However, note the following cases for using *LOVAL and *HIVAL:

  • With an externally described file that has a key in descending order, *HIVAL positions the file so that the first read operation retrieves the first record in the file (the record with the highest key), and *LOVAL positions the file so that a READP operation retrieves the last record in the file (the record with the lowest key).
  • If a record is added or a key field altered after a SETLL operation with either *LOVAL or *HIVAL, the file may no longer be positioned to the record with the lowest or highest key.
  • *LOVAL for numeric keys represents a key value X'99...9D' and *HIVAL represents a key value X'99...9F'. If the keys are float numeric, *HIVAL and *LOVAL are defined differently. See Figurative Constants. When a program described file has a packed decimal key specified in the file specifications but the actual file key field contains character data, records may have keys that are less than *LOVAL or greater than *HIVAL. When a key field contains unsigned binary data, *LOVAL may not be the lowest key.

When *LOVAL or *HIVAL are used with key fields with a Date or Time data type, the values are dependent of the Date-Time format used. For details on these values please see Data Types and Data Formats.

You can use the special values *START and *END for search-arg. *START positions to the beginning of the file and *END positions to the end of the file. Both positionings are independent of the collating sequence used for keyed files. If you specify either *START or *END for search-arg, note the following:

  • The name operand must be specified.
  • Either an error indicator (positions 73-74) or the 'E' extender may be specified.

Figure 329 (part 3 of 4)shows the use of figurative constants with the SETGT operation. Figurative constants are used the same way with the SETLL operation.

Remember the following when using the SETLL operation:

  • If the SETLL operation is not successful (no records found condition), the file is positioned to the end of the file.
  • When end of file is reached on a file being processed by SETLL, another SETLL can be issued to reposition the file.
  • After a SETLL operation successfully positions the file at a record, you retrieve this record by reading the file. Before you read the file, however, records may be deleted from the file by another job or through another file in your job. Thus, you may not get the record you expected. Even if the %EQUAL built-in function is also set on or the resulting indicator in positions 75 and 76 is set on to indicate you found a matching record, you may not get that record. For information on preventing unexpected modification of your files, see the discussion of allocating objects in the iSeries Information Center Programming topic at URL http://www.ibm.com/eserver/iseries/infocenter..
  • SETLL does not cause the system to access a data record. If you are only interested in verifying that a key actually exists, SETLL with an equal indicator (positions 75-76) or the %EQUAL built-in function is a better performing solution than the CHAIN operation in most cases. Under special cases of a multiple format logical file with sparse keys, CHAIN can be a faster solution than SETLL.

See Database Null Value Support for information on handling records with null-capable fields and keys.

Note:
Operation code extenders H, M, and R are allowed only when the search argument is a list or is %KDS().

In the following example, the file ORDFIL contains order records. The key field is the order number (ORDER) field. There are multiple records for each order. ORDFIL looks like this in the calculation specifications:

Figure 330. SETLL Operation


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* All the 101 records in ORDFIL are to be printed. The value 101
* has previously been placed in ORDER. The SETLL operation
* positions the file at the first record with the key value 101
* and %EQUAL will return '1'.
C
C ORDER SETLL ORDFIL
C

* The following DO loop processes all the records that have the
* same key value.
C
C IF %EQUAL
C DOU %EOF
C ORDER READE ORDFIL
C IF NOT %EOF
C EXCEPT DETAIL
C ENDIF
C ENDDO
C ENDIF
C

* The READE operation reads the second, third, and fourth 101
* records in the same manner as the first 101 record was read.
* After the fourth 101 record is read, the READE operation is
* attempted. Because the 102 record is not of the same group,
* %EOF will return '1', the EXCEPT operation is bypassed, and
* the DOU loop ends.

SETOFF (Set Indicator Off)


Free-Form Syntax (not allowed - use EVAL *INxx = *OFF)

Code Factor 1 Factor 2 Result Field Indicators
SETOFF


OF OF OF

The SETOFF operation sets off any indicators specified in positions 71 through 76. You must specify at least one resulting indicator in positions 71 through 76. Entries of 1P and MR are not valid. Setting off L1 through L9 indicators does not automatically set off any lower control-level indicators.

Figure 331 illustrates the SETOFF operation.


SETON (Set Indicator On)


Free-Form Syntax (not allowed - use EVAL *INxx = *ON)

Code Factor 1 Factor 2 Result Field Indicators
SETON


ON ON ON

The SETON operation sets on any indicators specified in positions 71 through 76. You must specify at least one resulting indicator in positions 71 through 76. Entries of 1P, MR, KA through KN, and KP through KY are not valid. Setting on L1 through L9 indicators does not automatically set on any lower control-level indicators.

Figure 331. SETON and SETOFF Operations


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* The SETON and SETOFF operations set from one to three indicators
* specified in positions 71 through 76 on and off.
* The SETON operation sets indicator 17 on.
C
C SETON 17
C

* The SETON operation sets indicators 17 and 18 on.
C
C SETON 1718
C

* The SETOFF operation sets indicator 21 off.
C
C SETOFF 21


SHTDN (Shut Down)


Free-Form Syntax (not allowed - use the %SHTDN built-in function)

Code Factor 1 Factor 2 Result Field Indicators
SHTDN


ON _ _

The SHTDN operation allows the programmer to determine whether the system operator has requested shutdown. If the system operator has requested shutdown, the resulting indicator specified in positions 71 and 72 is set on. Positions 71 and 72 must contain one of the following indicators: 01 through 99, L1 through L9, U1 through U8, H1 through H9, LR, or RT.

The system operator can request shutdown by specifying the *CNTRLD option on the following CL commands: ENDJOB (End Job), PWRDWNSYS (Power Down System), ENDSYS (End System), and ENDSBS (End Subsystem). For information on these commands, see the iSeries Information Center programming category.

Positions 73 through 76 must be blank.

Figure 332. SHTDN Operation


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* When the SHTDN operation is run, a test is made to determine
* whether the system operator has requested shutdown. If so,
* indicator 27 is set on.
C
C SHTDN 27
C 27 EXSR Term_appl
C :
C :
C Term_appl BEGSR
C CLOSE *ALL
C :
C ENDSR


SORTA (Sort an Array)


Free-Form Syntax SORTA array-name

Code Factor 1 Factor 2 Result Field Indicators
SORTA
array-name



The array-name operand is the name of an array to be sorted. The array is sorted into sequence (ascending or descending), depending on the sequence specified for the array on the definition specification. If no sequence is specified, the array is sorted into ascending sequence. The array *IN cannot be specified.. If the array is defined as a compile-time or prerun-time array with data in alternating form, the alternate array is not sorted. Only the array specified as array-name is sorted.

If the array is defined with the OVERLAY keyword, the base array will be sorted in the sequence defined by the OVERLAY array.

Graphic arrays will be sorted by the hexadecimal values of the array elements, disregarding the alternate collating sequence, in the order specified on the definition specification.

Notes:

  1. Sorting an array does not preserve any previous order. For example, if you sort an array twice, using different overlay arrays, the final sequence will be that of the last sort. Elements that are equal in the sort sequence but have different hexadecimal values (for example, due to alternate collating sequence or the use of an overlay array to determine sequence), may not be in the same order after sorting as they were before.
  2. When sorting arrays of basing pointers, you must ensure that all values in the arrays are addresses within the same space. Otherwise, inconsistent results may occur. See Compare Operations for more information.
  3. If a null-capable array is sorted, the sorting will not take the settings of the null flags into consideration.
  4. Sorting a dynamically allocated array without all defined elements allocated may cause errors to occur.

Figure 333. SORTA Operation


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++
DARRY S 1A DIM(8) ASCEND
D

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* The SORTA operation sorts ARRY into ascending sequence because
* the ASCEND keyword is specified.
* If the unsorted ARRY contents were GT1BA2L0, the sorted ARRY
* contents would be ABGLT012.
C
C SORTA ARRY

Figure 334. SORTA Operation with OVERLAY


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++
* In this example, the base array has the values aa44 bb33 cc22 dd11
* so the overlaid array ARRO has the values 44 33 22 11.
D DS
D ARR 4 DIM(4) ASCEND
D ARRO 2 OVERLAY(ARR:3)
D

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
C
* After the SORTA operation, the base array has the values
* dd11 cc22 bb33 aa44
C
C SORTA ARRO


SQRT (Square Root)


Free-Form Syntax (not allowed - use the %SQRT built-in function)

Code Factor 1 Factor 2 Result Field Indicators
SQRT (H)
Value Root


The SQRT operation derives the square root of the field named in factor 2. The square root of factor 2 is placed in the result field.

Factor 2 must be numeric, and can contain one of: an array, array element, field, figurative constant, literal, named constant, subfield, or table name.

The result field must be numeric, and can contain one of: an array, array element, subfield, or table element.

An entire array can be used in a SQRT operation if factor 2 and the result field contain array names.

The number of decimal positions in the result field can be either less than or greater than the number of decimal positions in factor 2. However, the result field should not have fewer than half the number of decimal positions in factor 2.

If the value of the factor 2 field is zero, the result field value is also zero. If the value of the factor 2 field is negative, the RPG IV exception/error handling routine receives control.

For further rules on the SQRT operation, see Arithmetic Operations.

See Figure 146 for an example of the SQRT operation.


SUB (Subtract)


Free-Form Syntax (not allowed - use the - or -= operators)

Code Factor 1 Factor 2 Result Field Indicators
SUB (H) Minuend Subtrahend Difference + - Z

If factor 1 is specified, factor 2 is subtracted from factor 1 and the difference is placed in the result field. If factor 1 is not specified, the contents of factor 2 are subtracted from the contents of the result field.

Factor 1 and factor 2 must be numeric, and each can contain one of: an array, array element, field, figurative constant, literal, named constant, subfield, or table name.

The result field must be numeric, and can contain one of: an array, array element, subfield, or table name.

For rules for the SUB operation, see Arithmetic Operations.

See Figure 146 for examples of the SUB operation.


SUBDUR (Subtract Duration)


Free-Form Syntax (not allowed - use the - or -= operators, or the %DIFF built-in function)

Code Factor 1 Factor 2 Result Field Indicators
SUBDUR (E) (duration) Date/Time/ Timestamp Date/Time/ Timestamp Duration: Duration code _ ER _
SUBDUR (E) (new date) Date/Time/ Timestamp Duration:Duration Code Date/Time/ Timestamp _ ER _

The SUBDUR operation has been provided to:

Subtract a duration

The SUBDUR operation can be used to subtract a duration specified in factor 2 from a field or constant specified in factor 1 and place the resulting Date, Time or Timestamp in the field specified in the result field.

Factor 1 is optional and may contain a Date, Time or Timestamp field, array, array element, literal or constant. If factor 1 contains a field name, array or array element then its data type must be the same type as the field specified in the result field. If factor 1 is not specified then the duration is subtracted from the field specified in the result field.

Factor 2 is required and contains two subfactors. The first is a numeric field, array or constant with zero decimal positions. If the field is negative then the duration is added to the field. The second subfactor must be a valid duration code indicating the type of duration. The duration code must be consistent with the result field data type. For example, you can subtract a year, month or day duration but not a minute duration from a date field. For list of duration codes and their short forms see Date Operations.

The result field must be a date, time or timestamp data type field, array or array element. If factor 1 is blank, the duration is subtracted from the value in the result field. If the result field is an array, the value in factor 2 is subtracted from each element in the array. If the result field is a time field, the result will always be a valid Time. For example, subtracting 59 minutes from 00:58:59 would give -00:00:01. Since this time is not valid, the compiler adjusts it to 23:59:59.

When subtracting a duration in months from a date, the general rule is that the month portion is decreased by the number of months in the duration, and the day portion is unchanged. The exception to this is when the resulting day portion would exceed the actual number of days in the resulting month. In this case, the resulting day portion is adjusted to the actual month end date. The following examples (which assume a *YMD format) illustrate this point.

  • '95/05/30' SUBDUR 1:*MONTH results in '95/04/30'

    The resulting month portion has been decreased by 1; the day portion is unchanged.

  • '95/05/31' SUBDUR 1:*MONTH results in '95/04/30'

    The resulting month portion has been decreased by 1; the resulting day portion has been adjusted because April has only 30 days.

Similar results occur when subtracting a year duration. For example, subtracting one year from '92/02/29' results in '91/02/28', an adjusted value since the resulting year is not a leap year.

Note:
The system places a 15 digit limit on durations. Subtracting a Duration with more than 15 significant digits will cause errors or truncation. These problems can be avoided by limiting the first subfactor in Factor 2 to 15 digits.

Calculate a duration

The SUBDUR operation can also be used to calculate a duration between:

  1. Two dates
  2. A date and a timestamp
  3. Two times
  4. A time and a timestamp
  5. Two timestamps

The data types in factor 1 and factor 2 must be compatible types as specified above.

Factor 1 is required and must contain a Date, Time or Timestamp field, subfield, array, array element, constant or literal.

Factor 2 is required and must also contain a Date, Time or Timestamp field, array, array element, literal or constant.

The following duration codes are valid:

  • For two dates or a date and a timestamp: *DAYS (*D), *MONTHS (*M), and *YEARS (*Y)
  • For two times or a time and a timestamp: *SECONDS (*S), *MINUTES (*MN), and *HOURS (*H)
  • For two timestamps: *MSECONDS (*MS), *SECONDS (*S), *MINUTES (*MN), *HOURS (*H), *DAYS (*D), *MONTHS (*M), and *YEARS (*Y).

The result is a number of whole units, with any remainder discarded. For example, 61 minutes is equal to 1 hour and 59 minutes is equal to 0 hours.

The result field consists of two subfactors. The first is the name of a zero decimal numeric field, array or array element in which the result of the operation will be placed. The second subfactor contains a duration code denoting the type of duration. The result field will be negative if the date in factor 1 is earlier than the date in factor 2.

For more information on working with date-time fields see Date Operations.

Note:
Calculating a micro-second Duration (*mseconds) can exceed the 15 digit system limit for Durations and cause errors or truncation. This situation will occur when there is more than a 32 year and 9 month difference between the factor 1 and factor 2 entries.

Possible error situations

  1. For subtracting durations:
    • If the value of the Date, Time or Timestamp field in factor 1 is invalid
    • If factor 1 is blank and the value of the result field before the operation is invalid
    • or if the result of the operation is greater than *HIVAL or less than *LOVAL.
  2. For calculating durations:
    • If the value of the Date, Time or Timestamp field in factor 1 or factor 2 is invalid
    • or if the result field is not large enough to hold the resulting duration.

In each of these cases an error will be signalled.

If an error is detected, an error will be generated with one of the following program status codes:

  • 00103: Result field not large enough to hold result
  • 00112: Date, Time or Timestamp value not valid
  • 00113: A Date overflow or underflow occurred (that is, the resulting Date is greater than *HIVAL or less than *LOVAL).

The value of the result field remains unchanged. To handle exceptions with program status codes 103, 112 or 113, either the operation code extender 'E' or an error indicator ER can be specified, but not both. For more information on error handling, see Program Exception/Errors.

SUBDUR Examples

Figure 335. SUBDUR Operations


CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....

* Determine a LOANDATE which is xx years, yy months, zz days prior to
* the DUEDATE.
C DUEDATE SUBDUR XX:*YEARS LOANDATE
C SUBDUR YY:*MONTHS LOANDATE
C SUBDUR ZZ:*DAYS LOANDATE

* Add 30 days to a loan due date
*
C SUBDUR -30:*D LOANDUE
* Calculate the number or days between a LOANDATE and a DUEDATE.
C LOANDATE SUBDUR DUEDATE NUM_DAYS:*D 5 0
* Determine the number of seconds between LOANDATE and DUEDATE.
C LOANDATE SUBDUR DUEDATE NUM_SECS:*S 5 0

SUBST (Substring)


Free-Form Syntax (not allowed - use the %SUBST built-in function)

Code Factor 1 Factor 2 Result Field Indicators
SUBST (E P) Length to extract Base string:start Target string _ ER _

The SUBST operation returns a substring from factor 2, starting at the location specified in factor 2 for the length specified in factor 1, and places this substring in the result field. If factor 1 is not specified, the length of the string from the start position is used. For graphic or UCS-2 strings, the start position is measured in double bytes. The base and target strings must both be of the same type, either both character, both graphic, or both UCS-2.

Factor 1 can contain the length value of the string to be extracted from the string specified in factor 2. It must be numeric with no decimal positions and can contain one of: a field name, array element, table name, literal, or named constant.

Factor 2 must contain either the base string, or the base string followed by ':', followed by the start location. The base string portion can contain one of: a field name, array element, named constant, data structure name, table name, or literal. The start position must be numeric with zero decimal positions, and can contain one of the following: a field name, array element, table name, literal or named constant. If it is not specified, SUBST starts in position 1 of the base string. For graphic or UCS-2 strings, the start position is measured in double bytes.

The start location and the length of the substring to be extracted must be positive integers. The start location must not be greater than the length of the base string, and the length must not be greater than the length of the base string from the start location. If either or both of these conditions is not satisfied, the operation will not be performed.

To handle SUBST exceptions (program status code 100), either the operation code extender 'E' or an error indicator ER can be specified, but not both. For more information on error handling, see Program Exception/Errors.

The result field must be character, graphic, or UCS-2 and can contain one of the following: a field name, array element, data structure, or table name. The result is left-justified. The result field's length should be at least as large as the length specified in factor 1. If the substring is longer than the field specified in the result field, the substring will be truncated from the right. If the result field is variable-length, its length does not change.

Note:
You cannot use figurative constants in the factor 1, factor 2, or result fields. Overlapping is allowed for factor 1 and the result field or factor 2 and the result field. If factor 1 is shorter than the length of the result field, a P specified in the operation extender position indicates that the result field should be padded on the right with blanks after the substring occurs.

Figure 336. SUBST Operation


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* The SUBST operation extracts the substring from factor 2 starting
* at position 3 for a length of 2. The value 'CD' is placed in the
* result field TARGET. Indicator 90 is not set on because no error
* occurred.
C
C Z-ADD 3 T 2 0
C MOVEL 'ABCDEF' String 10
C 2 SUBST String:T Target 90

*
* In this SUBST operation, the length is greater than the length
* of the string minus the start position plus 1. As a result,
* indicator 90 is set on and the result field is not changed.
C
C MOVE 'ABCDEF' String 6
C Z-ADD 4 T 1 0
C 5 SUBST String:T Result 90
C

* In this SUBST operation, 3 characters are substringed starting
* at the fifth position of the base string. Because P is not
* specified, only the first 3 characters of TARGET are
* changed. TARGET contains '123XXXXX'.
C
C Z-ADD 3 Length 2 0
C Z-ADD 5 T 2 0
C MOVE 'TEST123' String 8
C MOVE *ALL'X' Target
C Length SUBST String:T Target 8

 *

* This example is the same as the previous one except P
* specified, and the result is padded with blanks.
* TARGET equals '123 '.
C
C Z-ADD 3 Length 2 0
C Z-ADD5 T 2 0
C MOVE 'TEST123' String 8
C MOVE *ALL'X' Target
C Length SUBST(P) String:T Target 8
C

C
*
* In the following example, CITY contains the string
* 'Toronto, Ontario'. The SCAN operation is used to locate the
* separating blank, position 9 in this illustration. SUBST
* without factor 1 places the string starting at position 10 and
* continuing for the length of the string in field TCNTRE.
* TCNTRE contains 'Ontario'.
C ' ' SCAN City C
C ADD 1 C
C SUBST City:C TCntre

*
* Before the operations STRING=' John &
* RESULT is a 10 character field which contains 'ABCDEFGHIJ'.
* The CHECK operation locates the first nonblank character
* and sets on indicator 10 if such a character exists. If *IN10
* is on, the SUBST operation substrings STRING starting from the
* first non-blank to the end of STRING. Padding is used to ensure
* that nothing is left from the previous contents of the result
* field. If STRING contains the value ' HELLO ' then RESULT
* will contain the value 'HELLO ' after the SUBST(P) operation.
* After the operations RESULT='John '.
C
C ' ' CHECK STRING ST 10
C 10 SUBST(P) STRING:ST RESULT


TAG (Tag)


Free-Form Syntax (not allowed - use other operation codes, such as LEAVE, ITER, and RETURN)

Code Factor 1 Factor 2 Result Field Indicators
TAG Label




The declarative TAG operation names the label that identifies the destination of a GOTO (Go To) or CABxx (Compare and Branch) operation. It can be specified anywhere within calculations, including within total calculations.

A GOTO within a subroutine in the main procedure can be issued to a TAG within the same subroutine, detail calculations or total calculations. A GOTO within a subroutine in a subprocedure can be issued to a TAG within the same subroutine, or within the body of the subprocedure.

The control level entry (positions 7 and 8) can be blank or can contain an L1 through L9 indicator, the LR indicator, or the L0 entry to group the statement within the appropriate section of the program. Conditioning indicator entries (positions 9 through 11) are not allowed.

Factor 1 must contain the name of the destination of a GOTO or CABxx operation. This name must be a unique symbolic name, which is specified in factor 2 of a GOTO operation or in the result field of a CABxx operation. The name can be used as a common point for multiple GOTO or CABxx operations.

Branching to the TAG from a different part of the RPG IV logic cycle may result in an endless loop. For example, if a detail calculation line specifies a GOTO operation to a total calculation TAG operation, an endless loop may occur.

See Figure 276 for examples of the TAG operation.


TEST (Test Date/Time/Timestamp)


Free-Form Syntax TEST{(EDTZ)} {dtz-format} field-name

Code Factor 1

(dtz-format)

Factor 2 Result Field

(field-name)

Indicators
TEST (E)

Date/Time or Timestamp Field _ ER _
TEST (D E) Date Format
Character or Numeric field _ ER _
TEST (E T) Time Format
Character or Numeric field _ ER _
TEST (E Z) Timestamp Format
Character or Numeric field _ ER _

The TEST operation code allows users to test the validity of date, time, or timestamp fields prior to using them.

For information on the formats that can be used see Date Data Type, Time Data Type, and Timestamp Data Type.

  • If the field-name operand is a field declared as Date, Time, or Timestamp:
    • The dtz-format operand cannot be specified
    • Operation code extenders 'D', 'T', and 'Z' are not allowed
  • If the field-name operand is a field declared as character or numeric, then one of the operation code extenders 'D', 'T', or 'Z' must be specified.
    Note:
    If the field-name operand is a character field with no separators, the dtz-format operand must contain the date, time, or timestamp format followed by a zero.
    • If the operation code extender includes 'D' (test Date),
      • dtz-format is optional and may by any of the valid Date formats (See Date Data Type).
      • If dtz-format is not specified, the format specified on the control specification with the DATFMT keyword is assumed. If this keyword is not specified, *ISO is assumed.
    • If the operation code extender includes 'T' (test Time),
      • dtz-format is optional and may be any of the valid Time formats (See Time Data Type).
      • If dtz-format is not specified, the format specified on the control specification with the TIMFMT keyword is assumed. If this keyword is not specified, *ISO is assumed.

      Note:
      The *USA date format is not allowed with the operation code extender (T). The *USA date format has an AM/PM restriction that cannot be converted to numeric when a numeric result field is used.
    • If the operation code extender includes 'Z' (test Timestamp),

Numeric fields and character fields without separators are tested for valid digit portions of a Date, Time, or Timestamp value. Character fields are tested for both valid digits and separators.

If the character or numeric field specified as the field-name operand is longer than required by the format being tested, only the leftmost data is used. For example, if the dtz-format operand is *MDY for a test of a numeric date, only the leftmost 6 digits of the field-name operand are examined.

For the test operation, either the operation code extender 'E' or an error indicator ER must be specified, but not both. If the content of the field-name operand is not valid, program status code 112 is signaled. Then, the error indicator is set on or the %ERROR built-in function is set to return '1' depending on the error handling method specified. For more information on error handling, see Program Exception/Errors.

Figure 337. TEST (E D/T/Z) Example


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++
D
D Datefield S D DATFMT(*JIS)
D Num_Date S 6P 0 INZ(910921)
D Char_Time S 8 INZ('13:05 PM')
D Char_Date S 6 INZ('041596')
D Char_Tstmp S 20 INZ('19960723140856834000')

D Char_Date2 S 9A INZ('402/10/66')
D Char_Date3 S 8A INZ('2120/115')
D

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* Indicator 18 will not be set on, since the character field is a
* valid *ISO timestamp field, without separators.
C *ISO0 TEST (Z) Char_Tstmp 18
* Indicator 19 will not be set on, since the character field is a
* valid *MDY date, without separators.
C *MDY0 TEST (D) Char_Date 19
*
* %ERROR will return '1', since Num_Date is not *DMY.
*
C *DMY TEST (DE) Num_Date
*
* No Factor 1 since result is a D data type field
* %ERROR will return '0', since the field
* contains a valid date
C
C TEST (E) Datefield
C

* In the following test, %ERROR will return '1' since the
* Timefield does not contain a valid USA time.
C
C *USA TEST (ET) Char_Time
C

* In the following test, indicator 20 will be set on since the
* character field is a valid *CMDY, but there are separators.
C
C *CMDY0 TEST (D) char_date2 20
C

* In the following test, %ERROR will return '0' since
* the character field is a valid *LONGJUL date.
C
C *LONGJUL TEST (DE) char_date3


TESTB (Test Bit)


Free-Form Syntax (not allowed - use the %BITAND built-in function)

Code Factor 1 Factor 2 Result Field Indicators
TESTB
Bit numbers Character field OF ON EQ

The TESTB operation compares the bits identified in factor 2 with the corresponding bits in the field named as the result field. The result field must be a one-position character field. Resulting indicators in positions 71 through 76 reflect the status of the result field bits. Factor 2 is always a source of bits for the result field.

Factor 2 can contain:

  • Bit numbers 0-7: From 1 to 8 bits can be tested per operation. The bits to be tested are identified by the numbers 0 through 7. (0 is the leftmost bit.) The bit numbers must be enclosed in apostrophes. For example, to test bits 0, 2, and 5, enter '025' in factor 2.
  • Field name: You can specify the name of a one-position character field, table name, or array element in factor 2. The bits that are on in the field, table name, or array element are compared with the corresponding bits in the result field; bits that are off are not considered. The field specified in the result field can be an array element if each element of the array is a one-position character field.
  • Hexadecimal literal or named constant: You can specify a 1-byte hexadecimal literal or hexadecimal named constant. Bits that are on in factor 2 are compared with the corresponding bits in the result field; bits that are off are not considered.

Figure 338 illustrates uses of the TESTB operation.

Indicators assigned in positions 71 through 76 reflect the status of the result field bits. At least one indicator must be assigned, and as many as three can be assigned for one operation. For TESTB operations, the resulting indicators are set on as follows:

  • Positions 71 and 72: An indicator in these positions is set on if the bit numbers specified in factor 2 or each bit that is on in the factor 2 field is off in the result field. That is, all of the specified bits are equal to off.
  • Positions 73 and 74: An indicator in these positions is set on if the bit numbers specified in factor 2 or the bits that are on in the factor 2 field are of mixed status (some on, some off) in the result field. That is, at least one the specified bits is on.
    Note:
    If only one bit is to be tested, these positions must be blank. If a field name is specified in factor 2 and it has only one bit on, an indicator in positions 73 and 74 is not set on.
  • Positions 75 and 76: An indicator in these positions is set on if the bit numbers specified in the factor 2 or each bit that is on in factor 2 field is on in the result field. That is, all of the specified bits are equal to on.
    Note:
    If the field in factor 2 has no bits on, then no indicators are set on.

Figure 338. TESTB Operation


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* The field bit settings are FieldF = 00000001, and FieldG = 11110001.
*
* Indicator 16 is set on because bit 3 is off (0) in FieldF.
* Indicator 17 is set off.
C TESTB '3' FieldF 16 17
*
* Indicator 16 is set on because both bits 3 and 6 are off (0) in
* FieldF. Indicators 17 and 18 are set off.
C TESTB '36' FieldF 161718
*
* Indicator 17 is set on because bit 3 is off (0) and bit 7 is on
* (1) in FLDF. Indicators 16 and 18 are set off.
C TESTB '37' FieldF 161718
*
* Indicator 17 is set on because bit 7 is on (1) in FLDF.
* Indicator 16 is set off.
C TESTB '7' FieldF 16 17
*
* Indicator 17 is set on because bits 0,1,2, and 3 are off (0) and
* bit 7 is on (1). Indicators 16 and 18 are set off.
C TESTB FieldG FieldF 161718
*
* The hexadecimal literal X'88' (10001000) is used in factor 2.
* Indicator 17 is set on because at least one bit (bit 0) is on
* Indicators 16 and 18 are set off.
C TESTB X'88' FieldG 161718

TESTN (Test Numeric)


Free-Form Syntax (not allowed)

Code Factor 1 Factor 2 Result Field Indicators
TESTN

Character field NU BN BL

The TESTN operation tests a character result field for the presence of zoned decimal digits and blanks. The result field must be a character field. To be considered numeric, each character in the field, except the low-order character, must contain a hexadecimal F zone and a digit (0 through 9). The low-order character is numeric if it contains a hexadecimal C, hexadecimal D, or hexadecimal F zone, and a digit (0 through 9). Note that the alphabetic characters J through R, should they appear in the low-order position of a field, are treated as negative numbers by TESTN. As a result of the test, resulting indicators are set on as follows:

  • Positions 71 and 72: The result field contains numeric characters; the low-order character may also be a letter from A to R, since these characters have a zone of C, D, or F, and a digit of 0 to 9.
  • Positions 73 and 74: The result field contains both numeric characters and at least one leading blank. For example, the values 123 or 123 set this indicator on. However, the value 1 23 is not a valid numeric field because of the embedded blanks, so this value does not set this indicator on.
    Note:
    An indicator cannot be specified in positions 73 and 74 when a field of length one is tested because the character field must contain at least one numeric character and one leading blank.
  • Positions 75 and 76: The result field contains all blanks.

The same indicator can be used for more than one condition. If any of the conditions exist, the indicator is set on.

The TESTN operation may be used to validate fields before they are used in operations where their use may cause undesirable results or exceptions (e.g. arithmetic operations).

Figure 339. TESTN Operation


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* The field values are FieldA = 123, FieldB = 1X4, FieldC = 004,
* FieldD = , FieldE = 1 3, and FieldF = 12.
*
* Indicator 21 is set on because FieldA contains all numeric
* characters.
C TESTN FieldA 21
* Indicator 22 is set on because FieldA contains all numeric
* characters. Indicators 23 and 24 remain off.
C TESTN FieldA 222324
* All indicators are off because FieldB does not contain valid
* numeric data.
C TESTN FieldB 252627
* Indicator 28 is set on because FieldC contains valid numeric data.
* Indicators 29 and 30 remain off.
C TESTN FieldC 282930
* Indicator 33 is set on because FieldD contains all blanks.
* Indicators 31 and 32 remain off.
C TESTN FieldD 313233
* Indicators 34, 35, and 36 remain off. Indicator 35 remains off
* off because FieldE contains a blank after a digit.
C TESTN FieldE 343536
* Indicator 38 is set on because FieldF contains leading blanks and
* valid numeric characters. Indicators 37 and 39 remain off.
C TESTN FieldF 373839

TESTZ (Test Zone)


Free-Form Syntax (not allowed - use the %BITxxx built-in functions)

Code Factor 1 Factor 2 Result Field Indicators
TESTZ

Character field AI JR XX

The TESTZ operation tests the zone of the leftmost character in the result field. The result field must be a character field. Resulting indicators are set on according to the results of the test. You must specify at least one resulting indicator positions 71 through 76. The characters &, A through I, and any character with the same zone as the character A set on the indicator in positions 71 and 72. The characters - (minus), J through R, and any character with the same zone as the character J set on the indicator in positions 73 and 74. Characters with any other zone set on the indicator in positions 75 and 76.


TIME (Retrieve Time and Date)


Free-Form Syntax (not allowed - use the %DATE, %TIME, or %TIMESTAMP built-in function)

Code Factor 1 Factor 2 Result Field Indicators
TIME

Target field


The TIME operation accesses the system time of day and/or the system date at any time during program processing. The system time is based on the 24-hour clock.

The Result field can specify one of the following into which the time of day or the time of day and the system date are written:

Result Field Value Returned Format
6-digit Numeric Time hhmmss
12-digit Numeric Time and Date hhmmssDDDDDD
14-digit Numeric Time and Date hhmmssDDDDDDDD
Time Time Format of Result
Date Date Format of Result
Timestamp Timestamp *ISO

If the Result field is a numeric field, to access the time of day only, specify the result field as a 6-digit numeric field. To access both the time of day and the system date, specify the result field as a 12- (2-digit year portion) or 14-digit (4-digit year portion) numeric field. The time of day is always placed in the first six positions of the result field in the following format:

  • hhmmss (hh=hours, mm=minutes, and ss=seconds)

If the Result field is a numeric field, then if the system date is included, it is placed in positions 7 through 12 or 7 through 14 of the result field. The date format depends on the date format job attribute DATFMT and can be mmddyy, ddmmyy, yymmdd, or Julian. The Julian format for 2-digit year portion contains the year in positions 7 and 8, the day (1 through 366, right-adjusted, with zeros in the unused high-order positions) in positions 9 through 11, and 0 in position 12. For 4-digit year portion, it contains the year in positions 7 through 10, the day (1 through 366, right-adjusted, with zeros in the unused high-order positions) in positions 11 through 13, and 0 in position 14.

If the Result field is a Timestamp field, the last 3 digits in the microseconds part is always 000.

Note:
The special fields UDATE and *DATE contain the job date. These values are not updated when midnight is passed, or when the job date is changed during the running of the program.

Figure 340. TIME Operation


D   Timeres       S               T   TIMFMT(*EUR)

D Dateres S D DATFMT(*USA)
D Tstmpres S Z

*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* When the TIME operation is processed (with a 6-digit numeric
* field), the current time (in the form hhmmss) is placed in the
* result field CLOCK. The TIME operation is based on the 24-hour
* clock, for example, 132710. (In the 12-hour time system, 132710
* is 1:27:10 p.m.)
C TIME Clock 6 0
* When the TIME operation is processed (with a 12-digit numeric
* field), the current time and day is placed in the result field
* TIMSTP. The first 6 digits are the time, and the last 6 digits
* are the date; for example, 093315121579 is 9:33:15 a.m. on
* December 15, 1979.
C TIME TimStp 12 0
C MOVEL TimStp Time 6 0
C MOVE TimStp SysDat 6 0

* This example duplicates the 12-digit example above but uses a
* 14-digit field. The first 6 digits are the time, and the last
* 8 digits are the date; for example, 13120001101992
* is 1:12:00 p.m. on January 10, 1992.
C TIME TimStp 14 0
C MOVEL TimStp Time 6 0
C MOVE TimStp SysDat 8 0

* When the TIME operation is processed with a date field,
* the current date is placed in the result field DATERES.
* It will have the format of the date field. In this case
* it would be in *USA format ie: D'mm/dd/yyyy'.
C TIME Dateres
* When the TIME operation is processed with a time field,
* the current time is placed in the result field TIMERES.
* It will have the format of the time field. In this case
* it would be in *EUR format ie: T'hh.mm.ss'.
C TIME Timeres
* When the TIME operation is processed with a timestamp field,
* the current timestamp is placed in the result field TSTMPRES.
* It will be in *ISO format.
* ie: Z'yyyy-mm-dd-hh.mm.ss.mmmmmm'
C TIME Tstmpres

UNLOCK (Unlock a Data Area or Release a Record)


Free-Form Syntax UNLOCK{(E)} name

Code Factor 1 Factor 2 Result Field Indicators
UNLOCK (E)
name (file or data area)
_ ER _

The UNLOCK operation is used to unlock data areas and release record locks.

To handle UNLOCK exceptions (program status codes 401-421, 431, and 432), either the operation code extender 'E' or an error indicator ER can be specified, but not both. For more information on error handling, see Program Exception/Errors.

Positions 71,72,75 and 76 must be blank.

For further rules for the UNLOCK operation, see Data-Area Operations.

Unlocking data areas

The name operand must be the name of the data area to be unlocked, or the reserved word *DTAARA.

When *DTAARA is specified, all data areas in the program that are locked are unlocked.

The data area must already be specified in the result field of a *DTAARA DEFINE statement or with the DTAARA keyword on the definition specification. name must not refer to the local data area or the Program Initialization Parameters (PIP) data area. If the UNLOCK operation is specified to an already unlocked data area, an error does not occur.

Figure 341. Data area unlock operation


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* TOTAMT, TOTGRS, and TOTNET are defined as data areas in the
* system. The IN operation retrieves all the data areas defined in
* the program. The program processes calculations, and
* then unlocks the data areas. The data areas can them be used
* by other programs.
*
C *LOCK IN *DTAARA
C :
C :
C UNLOCK *DTAARA
C *DTAARA DEFINE TOTAMT 8 2
C *DTAARA DEFINE TOTGRS 10 2
C *DTAARA DEFINE TOTNET 10 2

Releasing record locks

The UNLOCK operation also allows the most recently locked record to be unlocked for an update disk file.

name must be the name of the UPDATE disk file.

Figure 342. Record unlock operation


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

FFilename++IPEASFRlen+LKlen+AIDevice+.Keywords++++++++++++++++++++++++++++
*
FUPDATA UF E DISK
*
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* Assume that the file UPDATA contains record format vendor.
* A record is read from UPDATA. Since the file is an update
* file, the record is locked. *IN50 is set somewhere else in
* the program to control whether an UPDATE should take place.
* otherwise the record is unlocked using the UNLOCK operation.
* Note that factor 2 of the UNLOCK operation is the file name,
* UPDATA, not the record format, VENDOR
*
C READ VENDOR 12
C :
C *IN50 IFEQ *ON
C UPDATE VENDOR
C ELSE
C UNLOCK UPDATA 99
C ENDIF


UPDATE (Modify Existing Record)


Free-Form Syntax UPDATE{(E)} name {data-structure | %FIELDS(name{:name...})}

Code Factor 1 Factor 2 Result Field Indicators
UPDATE (E)
name (file or record format) data-structure _ ER _

The UPDATE operation modifies the last locked record retrieved for processing from an update disk file or subfile. No other operation should be performed on the file between the input operation that retrieved the record and the UPDATE operation.

The name operand must be the name of a file or record format to be updated. A record format name is required with an externally described file. The record format name must be the name of the last record read from the file; otherwise, an error occurs. A file name as the name operand is required with a program described file.

If the data-structure operand is specified, the record is updated directly from the data structure. If name refers to a program described file (identified by an F in position 22 of the file description specification), the data structure can be any data structure of the same length as the file's declared record length. If name refers to an externally-described file, the data structure must be a data structure defined with EXTNAME(...:*INPUT) or LIKEREC(...:*INPUT). The updated record is written directly from the data structure to the file.

A list of the fields to update can be specified using %FIELDS. The parameter to %FIELDS is a list of the field names to update. See the example at the end of %FIELDS (Fields to update) for an illustration of updating fields.

To handle UPDATE exceptions (file status codes greater than 1000), either the operation code extender 'E' or an error indicator ER can be specified, but not both. For more information on error handling, see File Exception/Errors.

Remember the following when using the UPDATE operation:

  • When name is a record format name, the current values in the program for the fields in the record definition are used to modify the record.
  • If some but not all fields in a record are to be updated, use the output specifications and not the UPDATE operation.
  • Before UPDATE is issued to a file or record, a valid input operation with lock (READ, READC, READE, READP, READPE, CHAIN, or primary/secondary file) must be issued to the same file or record. If the read operation returns with an error condition or if it was read without locking, the record is not locked and UPDATE cannot be issued. The record must be read again with the default of a blank operation extender to specify a lock request.
  • Consecutive UPDATE operations to the same file or record are not valid. Intervening successful read operations must be issued to position to and lock the record to be updated.
  • Beware of using the UPDATE operation on primary or secondary files during total calculations. At this stage in the RPG IV cycle, the fields from the current record (the record that is about to be processed) have not yet been moved to the processing area. Therefore, the UPDATE operation updates the current record with the fields from the preceding record. Also, when the fields from the current record are moved to the processing area, they are the fields that were updated from the preceding record.
  • For multiple device files, specify a subfile record format as the name operand. The operation is processed for the program device identified in the fieldname specified using the DEVID keyword in the file specification. If the program device is not specified, the device used in the last successful input operation is used. This device must be the same one you specified for the input operation that must precede the UPDATE operation. You must not process input or output operations to other devices in between the input and UPDATE operations. If you do, your UPDATE operation will fail.
  • For a display file which has multiple subfile record formats, you must not process read-for-update operations to one subfile record in between the input and UPDATE operations to another subfile in the same display file. If you do, the UPDATE operation will fail.
  • An UPDATE operation is valid to a subfile record format as long as at least one successful input operation (READ, READC, READE, READP, READPE, CHAIN, or primary/secondary file) has occurred to that format name without an intervening input operation to a different format name. The record updated will be the record retrieved on the last successful input operation. This means that if you read a record successfully, then read unsuccessfully to the same format, an update will succeed, but will update the first record. This is different from the behavior of DISK files.

    To avoid updating the wrong record, check the resulting indicator or record-identifying indicator to ensure that a successful input operation has occurred before doing the update operation.

See Database Null Value Support for information on updating records with null-capable fields containing null values.


WHEN (When True Then Select)


Free-Form Syntax WHEN{(MR)} indicator-expression

Code Factor 1 Extended Factor 2
WHEN (M/R)
indicator-expression

The WHEN operation code is similar to the WHENxx operation code in that it controls the processing of lines in a SELECT operation. It differs in that the condition is specified by a logical expression in the indicator-expression operand. The operations controlled by the WHEN operation are performed when the expression in the indicator-expression operand is true. See Expressions for details on expressions. For information on how operation extenders M and R are used, see Precision Rules for Numeric Operations.

Figure 343. WHEN Operation


CL0N01Factor1+++++++Opcode(E)+Extended-factor2+++++++++++++++++++++++++++..

*
C SELECT
C WHEN *INKA
C :
C :
C :
C WHEN NOT(*IN01) AND (DAY = 'FRIDAY')
C :
C :
C :
C WHEN %SUBST(A:(X+4):3) = 'ABC'
C :
C :
C :
C OTHER
C :
C :
C :
C ENDSL


WHENxx (When True Then Select)


Free-Form Syntax (not allowed - use the WHEN operation code)

Code Factor 1 Factor 2 Result Field Indicators
WHENxx Comparand Comparand



The WHENxx operations of a select group determine where control passes after the SELECT (Begin a Select Group) operation is processed.

The WHENxx conditional operation is true if factor 1 and factor 2 have the relationship specified by xx If the condition is true, the operations following the WHENxx are processed until the next WHENxx, OTHER, ENDSL, or END operation.

When performing the WHENxx operation remember:

  • After the operation group is processed, control passes to the statement following the ENDSL operation.
  • You can code complex WHENxx conditions using ANDxx and ORxx. Calculations are processed when the condition specified by the combined WHENxx, ANDxx, and ORxx operations is true.
  • The WHENxx group can be empty.
  • Within total calculations, the control level entry (positions 7 and 8) can be blank or can contain an L1 through L9 indicator, an LR indicator, or an L0 entry to group the statement within the appropriate section of the program. The control level entry is for documentation purposes only. Conditioning indicator entries (positions 9 through 11) are not allowed.

Refer to Compare Operations for valid values for xx.

Figure 344. WHENxx Operation


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* The following example shows nested SELECT groups. The employee
* type can be one of 'C' for casual, 'T' for retired, 'R' for
* regular, and 'S' for student. Depending on the employee type
* (EmpTyp), the number of days off per year (Days) will vary.
*
C SELECT
C EmpTyp WHENEQ 'C'
C EmpTyp OREQ 'T'
C Z-ADD 0 Days
C EmpTyp WHENEQ 'R'

*
* When the employee type is 'R', the days off depend also on the
* number of years of employment. The base number of days is 14.
* For less than 2 years, no extra days are added. Between 2 and
* 5 years, 5 extra days are added. Between 6 and 10 years, 10
* extra days are added, and over 10 years, 20 extra days are added.
*
C Z-ADD 14 Days
* Nested select group.
C SELECT
C Years WHENLT 2
C Years WHENLE 5
C ADD 5 Days
C Years WHENLE 10
C ADD 10 Days
C OTHER
C ADD 20 Days
C ENDSL

* End of nested select group.
C EmpTyp WHENEQ 'S'
C Z-ADD 5 Days
C ENDSL

 *--------------------------------------------------------------------

* Example of a SELECT group with complex WHENxx expressions. Assume
* that a record and an action code have been entered by a user.
* Select one of the following:
* - When F3 has been pressed, do subroutine QUIT.
* - When action code(Acode) A (add) was entered and the record
* does not exist (*IN50=1), write the record.
* - When action code A is entered, the record exists, and the
* active record code for the record is D (deleted); update
* the record with active rec code=A. When action code D is
* entered, the record exists, and the action code in the
* record (AcRec) code is A; mark the record as deleted.
* - When action code is C (change), the record exists, and the
* action code in the record (AcRec) code is A; update the record.
* - Otherwise, do error processing.
*--------------------------------------------------------------------
*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
C RSCDE CHAIN FILE 50
C SELECT
C *INKC WHENEQ *ON
C EXSR QUIT
C Acode WHENEQ 'A'
C *IN50 ANDEQ *ON
C WRITE REC
C Acode WHENEQ 'A'
C *IN50 ANDEQ *OFF
C AcRec ANDEQ 'D'
C Acode OREQ 'D'
C *IN50 ANDEQ *OFF
C AcRec ANDEQ 'A'
C MOVE Acode AcRec
C UPDATE REC
C Acode WHENEQ 'C'
C *IN50 ANDEQ *OFF
C AcRec ANDEQ 'A'
C UPDATE REC
C OTHER
C EXSR ERROR
C ENDSL


WRITE (Create New Records)


Free-Form Syntax WRITE{(E)} name {data-structure}

Code Factor 1 Factor 2 Result Field Indicators
WRITE (E)
name (file or record format) data-structure _ ER EOF

The WRITE operation writes a new record to a file.

The name operand must be the name of a file or record format. A record format name is allowed only with an externally described file. A file name is required with a program described file.

If the data-structure operand is specified, the record is written directly from the data structure to the file. If name refers to a program described file (identified by an F in position 22 of the file description specification), the data structure is required and can be any data structure of the same length as the file's declared record length. If name refers to an externally-described file or a record format from an externally described file, the data structure must be a data structure defined with EXTNAME(...:*OUTPUT) or LIKEREC(...:*OUTPUT).

To handle WRITE exceptions (file status codes greater than 1000), either the operation code extender 'E' or an error indicator ER can be specified, but not both. An error occurs if overflow is reached to an externally described print file and no overflow indicator has been specified on the File description specification. For more information on error handling, see File Exception/Errors.

You can specify an indicator in positions 75-76 to signal whether an end of file occurred (subfile is filled) on the WRITE operation. The indicator is set on (an EOF condition) or off every time the WRITE operation is performed. This information can also be obtained from the %EOF built-in function, which returns '1' if an EOF condition occurs and '0' otherwise.

When using the WRITE operation remember:

  • When name is a record format name, the current values in the program for all the fields in the record definition are used to construct the record.
  • When records that use relative record numbers are written to a file, you must update the field name specified on the RECNO File specification keyword (relative record number), so it contains the relative record number of the record to be written.
  • When you use the WRITE operation to add records to a DISK file, you must specify an A in position 20 of the file description specifications. (See Position 20 (File Addition).)
  • Device dependent functions are limited. For example, if a "WRITE" is issued to a "PRINTER" device, the space after will be set to 1 if the keyword PRTCTL is not specified on the file specification (normally spacing or skipping information are specified in columns 41 through 51 of the output specifications). If the file is externally described, these functions are part of the external description.
  • For a multiple device file, data is written to the program device named in the field name specified with the DEVID keyword on the file description specifications. (See DEVID(fieldname).) If the DEVID keyword is not specified, data is written to the program device for which the last successful input operation was processed.

See Database Null Value Support for information on adding records with null-capable fields containing null values.

Figure 345. WRITE Operation


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* The WRITE operation writes the fields in the data structure
* DS1 to the file, FILE1.
*
C WRITE FILE1 DS1

XFOOT (Summing the Elements of an Array)


Free-Form Syntax (not allowed - use the %XFOOT built-in function)

Code Factor 1 Factor 2 Result Field Indicators
XFOOT (H)
Array name Sum + - Z

XFOOT adds the elements of an array together and places the sum into the field specified as the result field. Factor 2 contains the name of the array.

If half-adjust is specified, the rounding occurs after all elements are summed and before the results are moved into the result field. If the result field is an element of the array specified in factor 2, the value of the element before the XFOOT operation is used to calculate the total of the array.

If the array is float, XFOOT will be performed as follows: When the array is in descending sequence, the elements will be added together in reverse order. Otherwise, the elements will be added together starting with the first elements of the array.

For further rules for the XFOOT operation, see Arithmetic Operations.

See Figure 146 for an example of the XFOOT operation.


XLATE (Translate)


Free-Form Syntax (not allowed - use the %XLATE built-in function)

Code Factor 1 Factor 2 Result Field Indicators
XLATE (E P) From:To Source-String:start Target String _ ER _

Characters in the source string (factor 2) are translated according to the From and To strings (both in factor 1) and put into a receiver field (result field). Source characters with a match in the From string are translated to corresponding characters in the To string. The From, To, Source, and Target strings must be of the same type, either all character, all graphic, or all UCS-2. As well, their CCSIDs must be the same, unless one of the CCSIDs is 65535, or in the case of graphic fields, CCSID(*GRAPH : *IGNORE) was specified on the Control Specification.

XLATE starts translating the source at the location specified in factor 2 and continues character by character, from left to right. If a character of the source string exists in the From string, the corresponding character in the To string is placed in the result field. Any characters in the source field before the starting position are placed unchanged in the result field.

Factor 1 must contain the From string, followed by a colon, followed by the To string. The From and To strings can contain one of the following: a field name, array element, named constant, data structure name, literal, or table name.

Factor 2 must contain either the source string or the source string followed by a colon and the start location. The source string portion of factor 2 can contain one of the following: a field name, array element, named constant, data structure name, data structure subfield, literal, or table name. If the operation uses graphic or UCS-2 data, the start position refers to double-byte characters. The start location portion of factor 2 must be numeric with no decimal positions and can be a named constant, array element, field name, literal, or table name. If no start location is specified, a value of 1 is used.

The result field can be a field, array element, data structure, or table. The length of the result field should be as large as the source string specified in factor 2. If the result field is larger than the source string, the result will be left adjusted. If the result field is shorter than the source string, the result field will contain the leftmost part of the translated source. If the result field is variable-length, its length does not change.

If a character in the From string is duplicated, the first occurrence (leftmost) is used.

Note:
Figurative constants cannot be used in factor 1, factor 2, or result fields. No overlapping in a data structure is allowed for factor 1 and the result field, or factor 2 and the result field.

Any valid indicator can be specified in columns 7 to 11.

If factor 2 is shorter than the result field, a P specified in the operation extender position indicates that the result field should be padded on the right with blanks after the translation. If the result field is graphic and P is specified, graphic blanks will be used. If the result field is UCS-2 and P is specified, UCS-2 blanks will be used.

To handle XLATE exceptions (program status code 100), either the operation code extender 'E' or an error indicator ER can be specified, but not both. For more information on error handling, see Program Exception/Errors.

Columns 75-76 must be blank.

Figure 346. XLATE Operation


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* The following translates the blank in NUMBER to '-'. The result
* in RESULT will be '999-9999'.
*
C MOVE '999 9999' Number 8
C ' ':'-' XLATE Number Result 8

Figure 347. XLATE Operation With Named Constants


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....

DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++
D Up C 'ABCDEFGHIJKLMNOPQRS-
D 'TUVWXYZ'
D Lo C 'abcdefghijklmnopqrs-
'tuvwxyz'

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq..
*
* In the following example, all values in STRING are translated to
* uppercase. As a result, RESULT='RPG DEPT'.
*
C MOVE 'rpg dept' String 8
C Lo:Up XLATE String Result

*
* In the following example only part of the string is translated
* to lowercase. As a result, RESULT='RPG Dept'.
*
C Up:Lo XLATE String:6 Result

Z-ADD (Zero and Add)


Free-Form Syntax (not allowed - use the EVAL operation code)

Code Factor 1 Factor 2 Result Field Indicators
Z-ADD (H)
Addend Sum + - Z

Factor 2 is added to a field of zeros. The sum is placed in the result field. Factor 1 is not used. Factor 2 must be numeric and can contain one of: an array, array element, field, figurative constant, literal, named constant, subfield, or table name.

The result field must be numeric, and can contain one of: an array, array element, field, subfield, or table name.

Half-adjust can be specified.

For the rules for the Z-ADD operation, see Arithmetic Operations.

See Figure 146 for an example of the Z-ADD operation.


Z-SUB (Zero and Subtract)


Free-Form Syntax (not allowed - use the EVAL operation code)

Code Factor 1 Factor 2 Result Field Indicators
Z-SUB (H)
Subtrahend Difference + - Z

Factor 2 is subtracted from a field of zeros. The difference, which is the negative of factor 2, is placed in the result field. You can use the operation to change the sign of a field. Factor 1 is not used. Factor 2 must be numeric and can contain one of the following: an array, array element, field, figurative constant, literal, named constant, subfield, or table name.

The result field must be numeric, and can contain one of the following: an array, array element, field, subfield, or table name.

Half-adjust can be specified.

*take from http://publib.boulder.ibm.com/iseries/v5r2/ic2924/books/c092508430.htm#HDROPERXCL