BUILT-IN FUNCTION SYNTAX SUMMARY


The original release of RPG IV included a set of built-in functions. Those built-in functions are: %ADDR, %PADDR, %SIZE, %ELEM, %SUBST, %TRIM, %TRIML, and %TRIMR.

In OS/400 V3R2 and V3R7, the %PARMS built-in function was introduced. Since then, several built-in functions have been added to RPG. Table 4.1 lists the syntax for each built-in function. In addition, the OS/400 version and release in which the specific built-in function was introduced or enhanced is specified.

Table 4.1: Built-in Function Syntax Summary

Version Release

Built-in Function

Parameters

Return Value Description

V3R7

%ABS

numeric expression

(D) Absolute value of expression.

V3R1

%ADDR

variable name

(D) Address of variable.

V5R1

%ALLOC

bytes to allocate

Pointer to allocated memory.

V5R2

%BITAND

expression1 : expression2

(D) Returns a value whose bits are on (set to '1') when the bits in both expression1 and expression2 are on.

V5R2

%BITNOT

expression

(D) Retuns a value whose bits are the reverse of those in the expression.

V5R2

%BITOR

expression1 : expression2

(D) Returns a value whose bits are on (set to '1') when the bits in both expression1 and expression2 are on.

V5R2

%BITXOR

expression1 : expression2

(D) Returns a value where each bit of the return value is on if the corresponding two bits of expression1 and expression2 are opposite; that is one bit is on and the other bit is off.

V4R2

V4R4

V5R1

%CHAR

graphic, date, time, time stamp, or numeric expression { : date-format-code }

Value in character data type.

V5R1

%CHECK

compare-value : base-string {: starting-position }

The first position in the base-string that contains a character that does not appear in compare-value. If all of the characters in base-string also appear in compare-value, %CHECK returns 0.

V5R1

%CHECKR

compare-value : base-string {: starting-position }

The last position of the base-string that contains a character that does not appear in compare-value. If all of the characters in base-string also appear in compare-value, %CHECKR returns 0.

V5R1

%DATE

expression {: date-format }

A date value after converting the expression into the date format specified. The expression may be any valid RPG datatype, including character, numeric, date, time, or timestamp.

V5R1

%DAYS

number of days

A valid duration of the number of day specified. Use this to add the number-of-days to an existing date value.

V3R7

V5R2

%DEC

numeric expression {:digits : decpos}character-string : digits : decpos

Value in packed numeric format. If digits and DECPOS are specified, the result value is formatted to fit in a variable of the number of digits specified.If a character string is specified, the value is converted to packed decimal and returned based on the required digits and DECPOS parameters.

V3R7

V5R2

%DECH

numeric expression {:digits : decpos}

character-string : digits : decpos

Half-adjusted value in packed numeric format. The length and decimal positions.

If a character string is specified, the value is converted to packed decimal and returned based on the required digits and DECPOS parameters.

V3R7

%DECPOS

numeric expression

(D) Number of decimal digits.

V5R1

%DIFF

date1 : date2 : duration

The duration between two date, time or timestamp values. Valid duration codes include: *MSECONDS, *SECONDS, *MINUTES, *HOURS, *DAYS, *MONTHS, *YEARS. Alternatively the short-hand duration codes may be specified: *MS, *S, *MN, *H, *D, *M, *Y

V4R4

%DIV

Numerator : denominator

(D) Performs integer division and returns the quotient (result) of that division operation.

V3R7

%EDITC

non-float numeric expression : edit code {:*cursym | *astfill | currency symbol}

(D) String representing edited value.

V3R7

%EDITFLT

numeric expression

Character external display representation of float.

V3R7

%EDITW

non-float numeric expression : edit word

(D) String representing edited value.

V3R1

%ELEM

array, table, or multiple occurrence data structure name

(D) Number of elements or occurrences.

V4R2

%EOF

{file name}

'1' if the most recent file input operation or write to a subfile (for a particular file, if specified); | ended in an end-of-file or | beginning-of-file condition '0' otherwise.

V4R2

%EQUAL

{file name}

'1' if the most recent SETLL (for a particular file, if specified) or LOOKUP operation found an exact match; '0' otherwise.

V4R2

%ERROR

'1' if the most recent operation code with extender 'E' specified resulted in an error; '0' otherwise.

V5R2

%FIELDS

field1 {: field2 : }

Used with the UPDATE operation code to indicate the fields that should be updated by the operation. Only those fields enclosed within the %FIELDS built-in function are modified in the database record.

V3R7 V5R2

%FLOAT

numeric expression character-string

Value in float format.

When a character value is specified, it is converted to floating point form. This is particularly useful when creating applications that accept only character data as input, such as EDI applications or CGI programs.

V4R2

%FOUND

{file name}

'1' if the most recent relevant operation (for a particular file, if specified) found a record (CHAIN, DELETE, SETGT, SETLL), an element (LOOKUP), or a match (CHECK, CHECKR, SCAN); '0' otherwise.

V4R4

%GRAPH

character value

(D) Converts character data to double-byte character set value.

V5R1

%HOURS

number of hours

A valid duration of the number of hours specified. Use this to add the number-of-hours to an existing date, time, or timestamp value.

V3R7

V5R2

%INT

numeric expression character-string

Value in integer format.

When a character value is specified, it is converted to integer form. This is particularly useful when creating applications that accept only character data as input, such as EDI applications or CGI programs.

V3R7

V5R2

%INTH

numeric expression charater-string

Half-adjusted value in integer format.

When a character value is specified, it is converted to integer form. This is particularly useful when creating applications that accept only character data as input, such as EDI applications or CGI programs.

V5R2

%KDS

data-structure { : field-cnt }

Used with the CHAIN, SETLL, SETGT, READE and READPE operation codes to allow a data structure to be used as a key list for file access.

The first parameter is the name of a data structure whose subfields must match the key structure of the file being accessed. The second parameter is optional and, if specified, indicates the number of subfields used as the key list. If the second parameter is not specified, then all subfields in the data structure are used as the key list.

V3R7

%LEN

any expression

(D) Returns the length of a variable or literal value, or the current length of a varying length field.

When used on the left side of the equal sign, sets the length of varying length fields.

V5R1

%LOOKUPXX

%LOOKUP(arg : array {: startindex {: numelems}}) %LOOKUPLT(arg : array {: startindex {: numelems}}) %LOOKUPGE(arg : array {: startindex {: numelems}}) %LOOKUPGT(arg : array {: startindex {: numelems}}) %LOOKUPLE(arg : array {: startindex {: numelems}})

Returns the array index of the LOOKUP built-in function.

V5R1

%MINUTES

number of minutes

A valid duration of the number of minutes specified. Use this to add the number-of-minutes to an existing date, time, or timestamp value.

V5R1

%MONTHS

number of months

A valid duration of the number of months specified. Use this to add the number-of-months to an existing date or timestamp value.

V5R1

%MSECONDS

number of microseconds

A valid duration of the number of microseconds specified. Use this to add the number-of-microseconds to an existing date, time, or timestamp value.

V3R7

%NULLIND

null-capable field name

Value in indicator format representing the null indicator setting for the null-capable field.

V5R1

%OCCURS

data structure name

If used on the left-side of the assignment operation, the data structure occurrence is set. If used on the right-side of the equals sign for assignment expressions or on either side of the comparator for a comparison operation, the current data structure occurrence is retrieved.

V4R2

%OPEN

file name

'1' if the specified file is open '0' if the specified file is closed.

V3R1

%PADDR

'procedure name' | prototype name

(D) Address of procedure.

V3R2

V3R6

%PARMS

Number of parameters passed to procedure.

V5R1

%REALLOC

ptr : number-of-bytes

Pointer to the newly allocated memory. The returned pointer may be the same as the original PTR parameter or it may be different. Up to 16776704 bytes of memory may be allocated.

V4R4

%REM

Numerator : Denominator

(D) Performs integer division and returns the remainder from the division operation.

V4R2

%REPLACE

replacement string: source string {:start position {:source length to replace}}

(D) String produced by inserting replacement string into source string, starting at start position and replacing the specified number of characters.

V3R7

%SCAN

search argument : string to be searched {:start position}

(D) First position of search argument in string or zero, if not found.

V5R1

%SECONDS

number of seconds

A valid duration of the number of seconds specified. Use this to add the number-of-seconds to an existing date, time or timestamp value.

V5R1

%SHTDN

*ON if job-end is requested, *OFF is job-end has not been requested.

V3R1

%SIZE

variable, data structure, array, or literal {: *ALL}

(D) Number of bytes used by variable or literal. *ALL returns the number of bytes used by all the elements of the array, or all the occurrences of the data structure.

V5R1

%SQRT

numeric expression

The square root of the numeric value.

V4R2

%STATUS

{file name}

Returns 0 if no program or file error occurred since the most recent operation code with extender 'E' specified as the most recent value set for any program or file status. If an error occurs as a file is specified, the value returned is the most recent status for that file.

V3R7

%STR

pointer{:maximum length}pointer : maximum length

Characters addressed by pointer argument up to but not including the first x'00' are retrieved or modified.

V5R1

%SUBDT

date1 : duration-component

The duration component of the date, time, or timestamp value. Valid duration components include: *MSECONDS, *SECONDS, *MINUTES, *HOURS, *DAYS, *MONTHS, *YEARS. Alternatively the short-hand duration components may be specified: *MS, *S, *MN, *H, *D, *M, *Y

V3R1

%SUBST

string:start{:length}

(D) Substring value. If length is not specified, the substring begins with start and continues through the end of the string.

V5R1

%THIS

reference to an object

Used only as a parameter to a procedure or method, this built-in function returns a reference pointer to the "this" object for those method calls.

V5R1

%TIME

expression {: time-format }

A time value after converting the expression from the time format specified. The expression may be any valid RPG datatype, including character, numeric, date, time, or timestamp.

V5R1

%TIMESTAMP

expression {: *ISO | *ISO0 }

A timestamp value after converting the expression from the timestamp format specified. The expression may be any valid RPG datatype, including character, numeric, date, time, or timestamp.

V5R1

%TLOOKUPXX

%TLOOKUP(arg : search-table {: alt-table}) %TLOOKUPLT(arg : search-table {: alt-table}) %TLOOKUPGE(arg : search-table {: alt-table}) %TLOOKUPGT(arg : search-table {: alt-table}) %TLOOKUPLE(arg : search-table {: alt-table})

*ON if a match is found; the table element is set to the found element. If a match is not found, *OFF is returned.

V3R1

%TRIM

string

(D) String with left and right blanks trimmed (removed).

V3R1

%TRIML

string

(D) String with left blanks trimmed.

V3R1

%TRIMR

string

(D) String with right blanks trimmed.

V4R4

%UCS2

Any character value

(D) Returns a varying-length value.

V4R2

%UNS

numeric expression character-expression

Value in unsigned format.

When a character value is specified, it is converted to integer form. This is particularly useful when creating applications that accept only character data as input, such as EDI applications or CGI programs.

V4R2

%UNSH

numeric expression character-expression

Half-adjusted value in unsigned integer format.

When a character value is specified, it is converted to integer form. This is particularly useful when creating applications that accept only character data as input, such as EDI applications or CGI programs.

V4R4

%XFOOT

Array name

Cross foots (totals) all the elements in an array.

V5R1

%XLATE

original-characters : translate-to-characters : data-to-translate {: start-pos}

Returns the data-to-translate after it is translated using the first and second parameters. The original data is not modified by the function.

V5R1

%YEARS

number of years

A valid duration of the number of years specified. Use this to add the number-of-years to an existing date or timestamp value.

All built-in functions may be used only in the calculation specifications. If noted with (D) in their description column, the build-in function may also be used on the Definition specifications. An (F) indicates that they may also be used on the file specification. And an (FD) indicates that they may be used on the file or definition specifications in addition to calculation specifications.

The %FIELD and %KDS built-in functions are unique to specific operation codes. That is they cannot be used in any general RPG statement, but rather are allowed only with specification operation codes.

The syntax diagram for each built-in function appears on the pages that follow. An example use of a typical built-in function is illustrated in Figure 4.1. The built-in function is %SUBST. The first parameter is the variable CUSTNAME, the second parameter is the starting position (7), and the third parameter (5) is the number of bytes to extract.

start figure

 .....CSRn01..............OpCode(ex)Extended-factor2+++++++++++++++++++++++++++++      C                   eval      lastname = %subst(custname : 7 : 5) 

end figure

Figure 4.1: Example usage of a built-in function.

As shown in Figure 4.1, five characters of the CUSTNAME field, beginning at position 7, are assigned to the LASTNAME field. In all cases, built-in functions can appear on either side of the comparison operator for an IF, DOW, DOU, FOR, and WHEN operation. For assignments, however, only %SUBST and %STR have the ability to allow the target of the operation to be extracted. While most operations may appear within %SUBST, only %SUBST and %STR actually allows the value on the left side of the equals sign to be modified.

%ABS (Absolute Value)

This function returns the absolute value of a given value.

%ABS Syntax Diagram

 absolute value of variable = %ABS( variable or expression ) 

Specify any numeric expression or variable, data structure subfield, or array element on the %ABS function. The return value has the same properties as the variable specified for the %ABS function. In other words, a packed decimal value is returned when a packed decimal value is specified as the argument to the %ABS function.

Use this function to return the positive value of any number (negative or positive). The absolute value of a number is the non-negative value of the number. For example, the absolute value of -38 is 38 and the absolute value of 400 is 400. Figure 4.2 shows an example of the use of the %ABS built-in function. In Figure 4.2, the area of a sphere is calculated using the absolute value of its radius.

start figure

 .....DName+++++++++++EUDS.......Length+TDc.Functions++++++++++++++++++++++++++++ 0010 D Radius          S              5I   INZ( -12 ) 0020 D PI              C                   const( 3.1415926 ) 0030 D Area            S              7P 3 .....CSRn01..............OpCode(ex)Extended-factor2+++++++++++++++++++++++++++++ 0040 C                   Eval      Area = 4 * PI * %Abs(Radius)**2 

end figure

Figure 4.2: An example of the %ABS built-in function.

%ADDR (Get Address)

The %ADDR function returns the memory location assigned to a variable. This memory location is known as the variable's address. It can be copied into a pointer variable, for further processing, or compared to another address.

%ADDR Syntax Diagram

 pointer to variable = %ADDR( variable ) 

See also %PADDR and PROCPTR.

Specify any variable, data structure, subfield, array, or array element on the %ADDR function. The %ADDR function can be used to copy the address of the variable to a pointer variable or it can be used with a comparison operation, such as IF or WHEN.

Use this function to return the address of a variable when pointers are being used. For example, if a pointer variable named MYPOINTER is defined, store the address of another variable in MYPOINTER by using the %ADDR function as shown in Figure 4.3.

start figure

 .....DName+++++++++++EUDS.......Length+TDc.Functions++++++++++++++++++++++++++++ 0010 D Comp_Desc       S             35A 0020 D desc            S                   LIKE(Comp_Desc) 0030 D myPointer       S               *   INZ(%ADDR(Comp_Desc)) .....CSRn01..............OpCode(ex)Extended-factor2+++++++++++++++++++++++++++++ 0040 C                   Eval      myPointer = %ADDR( desc ) 0050 C                   If        %addr( desc ) = MyPointer 

end figure

Figure 4.3: An example of the %ADDR built-in function.

In Figure 4.3, the stand-alone field named COMP_DESC is defined as a 35-position character field (line 10). This variable's address in memory is allocated at runtime. Line 20 defines the DESC field with the same attributes as COMP_DESC.

The variable MYPOINTER is declared (line 30). Its data type is POINTER. Pointers contain the addresses of other variables. The address of COMP_DESC is stored in MYPOINTER by the INZ keyword.

Another method of assigning pointer values is the EVAL operation. Line 40 illustrates how the %ADDR built-in function can be used to assign the address of a variable to a pointer variable, while line 50 illustrates its use in a comparison operation.

%BITAND (Bitwise "ANDing" of Values)

%BITAND returns the bit-wise ANDing of the bits of all the parameters. The result bit is on when all of the corresponding bits in the parameters are on; otherwise the resulting bit is off.

%BITAND Syntax Diagram

 resulting-bit-pattern = %BITAND( expr1 : expr2 : expr3... ) 

See also: %BITXOR, %BITOR, %BITNOT

%BITAND can have two or more parameters. All parameters must be of the same datatype and must be either character or numeric.

The resulting value is the same datatype as the datatypes of the parameters, and its length is the same as the longest parameter value specified. If the parameter lengths are not the same, the longest length is used and the shorter parameters are padded on the left with X'00' if numeric, and on the right with X'FF' if character.

All bitwise built-in functions operate on fields of any length and may be specified in both the Calculation specifications and as a parameter of a keyword on the Definition and File specifications. When referring to the bits of a single byte, the 8 bits are enumerated as 0 through 7, starting with the high-order bit.

Bitwise operations are often used with single-byte character fields or values to test for or set a specific bit pattern. For example, to set the bits on in a result when all the bits of the comparison parameters are on, the %BITAND built-in function can be used as follows:

 .....DName+++++++++++EUDS.......Length+TDc.Functions+++++++++++++++++++ 0001 D first           S              1A   Inz('1') 0002 D second          S              1A   Inz('2') 0003 D third           S              1A   Inz('3') 0004 D answer          S              1A   Inz(X'00') .....CSRn01..............OpCode(ex)Extended-factor2++++++++++++++++++++ 0005 C                   if        answer = %BitAND(first : second : third) 

The ANSWER field is initialized to the bit pattern: 0000 0000 which is X'00' in hex. Line 5 performs a bitwise AND of the FIRST, SECOND and THIRD fields. The result is a bit pattern whose bits are set on if all the corresponding bits in the three parameters are also on; otherwise the resulting bit is off. The result of the %BITAND operation on line 5 is X'F0' or a bit pattern of 1111 0000.

Bit Pattern

Hex Value

FIRST

1111 0001

X'F1'

SECOND

1111 0010

X'F2'

THIRD

1111 0011

X'F3'

%BITAND

AND

Result

1111 0000

(X'F0')

%BITAND can also be used to set off specific bits within a field. To do this, create a secondary value that contains the bit pattern needed to set off the bits in the original value. For example, a value initialized to X'C4' represents a bit pattern of 1100 0100. To set off the low-order bits in this value, it can be ANDed with a value of 1111 0000 or X'F0'.

 .....DName+++++++++++EUDS.......Length+TDc.Functions+++++++++++++++++++ 0001 D myValue         S              1A   Inz(X'C4') .....CSRn01..............OpCode(ex)Extended-factor2++++++++++++++++++++ 0002 C                   if        myValue = %BitAND(myValue : X'F0') 

Since bits 0 and 1 are the only two bits on in both values, the result of the %bitand built-in function is X'C0'.

Bit Pattern

Hex Value

MYVALUE

1100 0400

X'F1'

%BITAND

AND

Literal

1111 0000

X'F0'

Result

1100 0000

(X'C0')

%BITNOT (Bit Inversion)

%BITNOT returns the bit-wise inversion of the bits of the parameters. The resulting bit pattern is the opposite of the value specified on the parameter.

%BITNOT Syntax Diagram

 resulting-bit-pattern = %BITNOT( expr1 ) 

See also: %BITXOR, %BITOR, %BITAND

%BITNOT accepts one parameter and returns a value with the same datatype as its parameter.

The resulting value is the same datatype as the datatypes of the parameter, and its length is the same as the parameter value specified. If the parameter is character, the result is character; if the parameter is numeric the result is either unsigned integer if the parameter is unsigned, otherwise the result is an 8-byte integer (20I 0) value.

All bitwise built-in functions operate on fields of any length and may be specified in both the Calculation specifications and as a parameter of a keyword on the Definition and File specifications. When referring to the bits of a single byte, the 8 bits are enumerated as 0 through 7, starting with the high-order bit.

Bitwise operations are often used with single-byte character fields or values to test for or set a specific bit pattern. For example, to reverse the bit pattern of a field the %BITNOT built-in function can be used as follows:

 .....DName+++++++++++EUDS.......Length+TDc.Functions+++++++++++++++++++ 0001 D myValue         S              1A   Inz('1') 0002 D flip            S              1A   Inz(X'00') .....CSRn01..............OpCode(ex)Extended-factor2++++++++++++++++++++ 0003 C                   eval      flip = %BitNot(myValue) 

The MYVALUE field is initialized to the bit pattern: 1111 0001 which is X'F1' in hex. Line 2 initializes the XVALUE field to hex zeros; if represents a bit pattern of 1111 1000. The %BITNOT operation (line 3) returns the bitwise NOTing of MYVALUE. The result is a bit pattern whose bits are the opposite of the original value in MYVALUE. The NOTing of MYVALUE produces the following result:

Bit Pattern

Hex Value

MYVALUE

1111 0001

X'F1'

%BITNOT

NOT

XVALUE

0000 0000

X'00'

Result

0000 1110

X'0E'

%BITOR (Bitwise "ORing" of Values)

%BITOR returns the bit-wise ORing of the bits of all the parameters. The result bits are on when any of the corresponding bits in the parameters are on. The resulting bits are off when all of the bits in the corresponding bit position of the parameters are off.

%BITOR Syntax Diagram

 resulting-bit-pattern = %BITOR( expr1 : expr2 : expr3 ... ) 

See also: %BITXOR, %BITAND, %BITNOT

%BITOR can have two or more parameters. All parameters must be of the same datatype and must be either character or numeric.

The resulting value is the same datatype as the datatypes of the parameters, and its length is the same as the longest parameter value specified. If the parameter lengths are not the same, the longest length is used and the shorter parameters are padded on the left with X'00' if numeric, and on the right with X'FF' if character.

All bitwise built-in functions operate on fields of any length and may be specified in both the Calculation specifications and as a parameter of a keyword on the Definition and File specifications. When referring to the bits of a single byte, the 8 bits are enumerated as 0 through 7, starting with the high-order bit.

Bitwise operations are often used with single-byte character fields or values to test for or set a specific bit pattern. The %BITOR can be used to combined add bit values to existing values.

For example, to detect if some of the bits of one field are on in a second field, the %BITXOR built-in function can be used as follows:

 .....DName+++++++++++EUDS.......Length+TDc.Functions+++++++++++++++++++ 0001 D myValue         S              1A   Inz('1') 0002 D xValue          S              1A   Inz('8') .....CSRn01..............OpCode(ex)Extended-factor2++++++++++++++++++++ 0003 C                   if        myValue = %BitOR(myValue : xValue) 

The MYVALUE field is initialized to the bit pattern: 1111 0001 which is X'F1' in hex. Line 2 initializes the XVALUE field to '8' which represents a bit pattern of 1111 1000 and a value of X'F8' in hex. The %BITOR operation (line 3) returns the bitwise ORing of MYVALUE with XVALUE. The result is a bit pattern whose bits are on if either of the two parameters' corresponding bits are on, otherwise the bit is off.

The ORing of MYVALUE with XVALUE produces the following results.

Bit Pattern

Hex Value

MYVALUE

1111 0001

X'F1'

%BITOR

OR

XVALUE

1111 1000

X'F8'

Result

1111 1001

X'F9'

%BITXOR (Bitwise Exlusive "ORing" of Values)

%BITXOR returns the bit-wise XORing of the bits of all the parameters. The result bit is on when either of the corresponding bits in the parameters are on, but not both; otherwise the result bit is off.

%BITXOR Syntax Diagram

 resulting-bit-pattern = %BITXOR( expr1 : expr2 ) 

See also: %BITAND, %BITOR, %BITNOT

%BITXOR must have two parameters. Both parameters must be of the same datatype, that is, character or numeric.

The resulting value is the same datatype as the datatype of the parameters, and its length is the same as the longest parameter value specified. If the parameter lengths are not the same, the longest length is used and the shorter parameters are padded on the left with X'00' if numeric, and on the right with X'FF' if character.

All bitwise built-in functions operate on fields of any length and may be specified in both the Calculation specifications and as a parameter of a keyword on the Definition and File specifications. When referring to the bits of a single byte, the 8 bits are enumerated as 0 through 7, starting with the high-order bit.

Bitwise operations are often used with single-byte character fields or values to test for or set a specific bit pattern. For example, to set off specific bits within a field, the %BIT the bit pattern of a field name MYVALUE and store that reversed pattern in a field named FLIP, following example may be used.

 .....DName+++++++++++EUDS.......Length+TDc.Functions+++++++++++++++++++ 0001 D myValue         S              1A   Inz(X'FC') 0002 D flip            S              1A   Inz(X'00') .....CSRn01..............OpCode(ex)Extended-factor2++++++++++++++++++++ 0003 C                   Eval      flip = %BitXOR(myValue : X'FF') 

The MYVALUE field is initialized to the bit pattern: 1111 1100 which is X'FC' in hex. The flip field is initialized to hex zeros, but that is irrelevant for this example.

On line 3, the MYVALUE field is exclusively ORed with the hex value X'FF'. Since X'FF' represents all the bits as being on, that is it is the same as a bit pattern of 1111 1111, the resulting bit pattern is the reverse of that in the MYVALUE field.

Exclusive ORing of MYVALUE with X'FF' produces the following results:

Bit Pattern

Hex Value

MYVALUE

1111 1100

X'F0'

%BITXOR

XOR

2nd Value

1111 1111

X'FF'

Result

0000 0011

X'03'

%CHAR (Convert to Character)

The %CHAR function returns the character form of a noncharacter value or expression.

%CHAR Syntax Diagram

 character value = %CHAR( numeric-value or expression | date-value | :                          date-format ) 

See also %EDITC and %EDITW.

The %CHAR function returns the numeric variable or expression or date value in character format. Any conventional noncharacter value—such as a date, time, timestamp, double-byte character, UCS-2, or numeric expression—may be specified.

For date, time, and timestamp values, the returned value includes the date, time, and timestamp value and the edit symbols. The edit symbols, or date separators, are based on the field's DATFMT (date format) keyword. The value is returned in the format of the date variable's DATFMT keyword unless the optional second parameter is specified.

The second parameter indicator, for date values, is the return-format of the date value. For example, if the date being converted is an *ISO date and the requirement is that the returned character value is to be formatted as *DMY, specifying *DMY on the second parameter will cause the returned value to be in *DMY format.

For numeric values and expressions, the returned value includes the decimal notation and, if applicable, the negative sign. Leading blanks and zeros are trimmed from the returned value. For example, a nine-digit number with two decimal positions, such as 000456789, would be returned as '4567.89' by %CHAR. If the numeric value is less than zero, a negative sign is inserted into the returned character string preceding the leading significant digit. Figure 4.4 shows an example of using %CHAR.

start figure

 .....DName+++++++++++EUDS.......Length+TDc.Functions++++++++++++++++++++++++++++ 0010 D textDate        S             35A 0020 D textPrice       S             35A 0030 D ordDate         S               D   INZ(D'1999-02-14') DATFMT(*ISO) 0040 D ordTime         S               D   INZ(T'15:30:00') TIMFMT(*USA) 0050 D MarkUp          S             11P 2 INZ(11.25) 0060 D Cost            S             11P 2 INZ(37.50) .....CSRn01..............OpCode(ex)Extended-factor2++++++++++++++++++++++++++++ 0070 C                   Eval      textDate = 'Order date and time is ' 0080 C                                        + %Char(ordDate) + ' at ' 0090 C                                        + %Char(ordTime)      **  The value of textDate is 'Order date and time is 1999-02-14 at 03:30 PM' 0100 C                   Eval      textPrice = 'Your price is ' + 0110 C                                       + %Char( Cost + MarkUp )      **  The value of textPrice is 'Your price is 48.75' 

end figure

Figure 4.4: An example of the %CHAR built-in function.

%CHECK (Verify Field Content Left-to-Right)

The %CHECK function performs a character-by-character verification of a character value. Each character in the character field or value is tested to ensure that they are also in the verification list.

%CHECK Syntax Diagram

 position = %CHECK( verification-list : searched-value {: start-position } ) 

See also: %CHECKR

The check function returns the first position of the searched-value that contains a character that does not appear in verification-list. If all of the characters in the searched-value also appear in verification-list, zero is returned.

The verification begins at the optional start-position and continues to the right until a character that is not contained in the comparator string is found or the end of the searched-value is detected.

The first parameter is the list of characters used as the verification-list and must be of a character field, expression, or named constant. In addition, it may be a graphic, UCS-2, fixed, or varying length field.

The second parameter must be of the same datatype (character, graphic, USC-2, etc.) as the first parameter. It is verified on a character-by-character basis against the verification-list.

The third parameter is optional and indicates the starting position as the verification. If unspecified, the verification begins with the first position of the searched-value.

%CHECKR (Verify Field Content Right-to-Left)

The %CHECKR function performs a character-by-character verification of a character value. Each character in the character field or value is tested, beginning with the right-most character, to ensure that each character is also in the verification list.

%CHECKR Syntax Diagram

 position = %CHECKR(  verification-list : searched-value                    {: start-position } ) 

See also: %CHECK

The check-right function returns the right-most position of the searched-value that contains a character that does not appear in verification-list. If all of the characters in the searched-value also appear in verification-list, zero is returned.

The verification begins at the optional start-position and continues to the left until a character that is not contained in the comparator string is found or the end of the searched-value is detected.

The first parameter is the list of characters used as the verification-list and must be of a character field, expression, or named constant. In addition, it may be a graphic, UCS-2, fixed, or varying length field.

The second parameter must be of the same datatype (character, graphic, USC-2, etc.) as the first parameter. It is verified on a character-by-character basis against the verification-list.

The third parameter is optional and indicates the starting position to being the verification. If unspecified, the verification begins with the last (right-most) position of the searched-value.

%DATE (Convert to Date Value)

The %DATE function converts a numeric, character or timestamp value to a valid date datatype value.

%DATE Syntax Diagram

 date-value  = %DATE( { expression {: date-format-code }} ) 

See also: %TIME, %TIMESTAMP

The date function performs two functions: (1) It converts a non-date value into a date value using the optional date-format code, and (2) if no parameters are specified, it returns the current system date.

The date format codes that may be specified in parameter 2 of the %DATE function are as follows:

Format Code

Date Format

*YMD

YYMMDD

*DMY

DDMMYY

*MDY

MMDDYY

*CYMD

CYYMMDD

*CDMY

CDDMMYY

*CMDY

CMMDDYY

*ISO

YYYYDDYY

*USA

MMDDYYY

*EUR

DDMMYYYY

*JIS

YYYYMMDD

*JUL

YYDDD

*LONGJUL

YYYYDDD

The date format code may be specified with a separator character when converting from a character value to a date value, to indicate that a separator other than the default separator is used in the character date value. The separator is not allowed when converting from a numeric value. In addition, a separator of 0 (zero) may be specified with the date-format code to indicate that the character date value contains no separators.

%DIFF (Difference between Two Date,Time, or Timestamp Values)

The %DIFF function calculates the duration between two date, time, or timestamp values.

%DIFF Syntax Diagram

 duration = %DIFF( date1 : date2 : duration-code ) 

See also: %SUBDT

The difference operation returns an integer (the duration value) that may be assigned to a numeric field, or added or subtracted from another date, time, or timestamp value. The first and second parameters must be the same or compatible date or time data types. That is, they must be both date values, or time values, or a date or time value and a timestamp value.

The duration code (parameter 3) is required and indicates the format for the returned value. The value duration codes are as follows:

  • *DAYS, *MONTHS, *YEARS or *D, *M, *Y

  • *MSECONDS, *SECONDS, *MINUTES, *HOURS, or *MS, *S, *MN, *H

%DEC and %DECH (Convert to Packed Decimal)

The %DEC and the %DECH functions convert a numeric value or expression to packed decimal notation.

%DEC Syntax Diagram

 packed decimal value  = %DEC( numeric expression [: length : decimal positions ] ) packed decimal value  = %DEC( character-string : length : decimal positions ) 

or

 packed decimal value = %DECH( numeric expression : length : decimal positions ) packed decimal value = %DECH( character-string : length : decimal positions ) 

%DEC converts the numeric value or expression to packed decimal. Alternatively, %DEC also converts a character string containing a number to a numeric value. The length and decimal positions are used to create the resulting value. If the length and decimal positions are not specified, the length and decimal positions of the expression arguments are used to determine a default length and decimal positions.

%DECH converts the numeric value or expression to packed decimal and performs the half adjust (rounding) of the result value. Alternatively, %DECH also converts a character string containing a number to a numeric value. Unlike %DEC, the %DECH built-in function requires the length and decimal positions in order to perform the half-adjust function.

%DECPOS (Retrieve Decimal Positions)

The %DECPOS function retrieves the numeric decimal positions declared for any non-floating point numeric variable or expression.

%DECPOS Syntax Diagram

 decimal positions = %DECPOS( numeric variable or expression ) 

See also %LEN

The %DECPOS function retrieves the number of decimal digits for a numeric variable. In addition, it can retrieve the decimal digits used to produce the temporary result of an expression. When multiple variables are specified for an expression, the result is the sum of the decimal positions.

start figure

 .....DName+++++++++++EUDS.......Length+TDc.Functions++++++++++++++++++++++++++++ 0010 D Price           S              7P 2 0020 D Cost            S              5P 3 0030 D MarkUp          S              5P 2 0030 D PosA            S              5I 0 0030 D PosB            S              5I 0 0030 D PosC            S              5I 0 0030 D PosD            S              5I 0 .....CSRn01..............OpCode(ex)Extended-factor2++++++++++++++++++++++++++++ 0070 C                   Eval      PosA = %DECPOS( price )      **  PosA = 2 0070 C                   Eval      PosB = %DECPOS( cost )      **  PosB = 3 0070 C                   Eval      PosC = %DECPOS( MarkUp )      **  PosC = 2 0070 C                   Eval      PosD = %DECPOS( Cost + MarkUp )      **  PosD = 5 

end figure

Figure 4.5: An example of the %DECPOS built-in function.

%DIV (Integer Division)

The %DIV function performs integer division on the two arguments. The first argument is the numerator and the second is the denominator.

%DIV Syntax Diagram

 integer quotient  = %DIV( numerator  :  denominator ) 

See also %REM

The divide operation returns an integer (whole number) result value (quotient). The numerator and the denominator must be numeric values with no decimal digits. In other words, numeric variables cannot contain decimal positions.

The %DIV operation can be specified on the definition specification when the two arguments are constant values that fit within an 8-byte integer value (20 digits).

By definition, integer division doesn't perform rounding. Therefore, the half-adjust operation extender is not supported.

The %DIV operation is only for integer (whole number) division. For all other divide operations, the / operator or the DIV operation should be used. Figure 4.6 shows an example of the use of %DIV.

start figure

 .....DName+++++++++++EUDS.......Length+TDc.Functions++++++++++++++++++++++++++++ 0010 D Cost            S              5P 3 0020 D MarkUp          S              5P 2 0030 D Count           S              7S 0 Inz(25) 0040 D Total           S              7P 0 Inz(220) 0050 D ValueA          S              5I 0 0060 D ValueB          S              5I 0 0070 D ValueC          S              5I 0 .....CSRn01..............OpCode(ex)Extended-factor2++++++++++++++++++++++++++++ 0080 C                   Eval      valueA = %DIV( 15 : 5 )      **  ValueA = 3 0090 C                   Eval      valueB = %DIV( MarkUp : Cost )      **  ERROR ** MarkUp and Cost must have zero decimal positions. 0100 C                   Eval      valueC = %DIV( Total : Count )      **  ValueC = 8 

end figure

Figure 4.6: Example of %DIV built-in function.

Duration Built-In Functions

The duration built-in functions work with date arithmetic. That is, they convert a non-date value, such as a number, into a duration value, such as an hour, minute, day, or year.

Duration Built-In Functions' Syntax Diagrams

 microseconds value = %MSECONDS( numeric-value ) seconds value = %SECONDS( numeric-value ) minutes value = %MINUTES( numeric-value ) hours value = %HOURS( numeric-value ) days value = %DAYS( numeric-value ) months value = %MONTHS( numeric-value ) years value = %YEARS( numeric-value ) 

The first parameter can be any numeric value, expression, literal value, or named constant. That value is converted to the duration specified and the return value may be used with a corresponding date arithmetic or comparison operation.

%EDITC (Edit with Edit Code)

This function edits a numeric value and returns a character form of that value after applying the specified edit code.

%EDITC Syntax Diagram

 character value = %EDITC( numeric exp : 'editcode' [:*ASTFILL | *CURSYM ] ) 

See also %EDITW, %EDITFLT, and %CHAR

The first parameter can be any numeric value, variable, literal, or expression.

The second parameter must be a valid edit code. The edit code must be a constant such as a quoted character or named constant. The valid edit codes are: 'A' through 'D', 'J' through 'Q', 'X', 'Y', 'Z' and '1' through '9'.

The third parameter can be one of the following values:

  • *ASTFILL — Leading asterisks are inserted in place of any leading zeros in the value.

  • *CURSYM — The currency symbol specified by the CURSYM keyword on the header specification is inserted into the edited value to the left of the first significant digit. 'quoted value' — This 1-byte quoted character value is used as the currency symbol for the edited value. The placement and function is the same as *CURSYM.

The length of the returned value is the length of the numeric value with the edit code applied. Leading blanks are included in the resulting edited value. When using %EDITC with the concatenation operator (+), use the %TRIML built-in function to trim off leading blanks.

Only one of the *CURSYM and *ASTFILL functions can be specified. It is often necessary to produce a result value that contains both leading asterisks and the currency symbol. This can be accomplished by using code similar to that shown in Figure 4.7.

start figure

 .....DName+++++++++++EUDS.......Length+TDc.Functions++++++++++++++++++++++++++++ 0010 D MSG               S           40A 0010 D NetDue            S            7P 2 Inz(12.65) 0020 D Amount            S           11P 2 Inz(10500.00) .....CSRn01..............OpCode(ex)Extended-factor2+++++++++++++++++++++++++++++ 0020 C                   Eval     msg = 'Total due is ' 0030 C                                + '$' + %EditC( netdue : 'J' : *ASTFILL)      ** MSG = 'Total due is $***12.65' 0080 C                   Eval     MSG = %EditC( Amount : 'J' : *CURSYM)      ** MSG = '     $10,500.00' 

end figure

Figure 4.7: An example of the %EDITC built-in function.

%EDITFLT (Edit with Floating Point)

The %EDITFLT function edits any numeric value and returns a character form of that value. The result is a 23-position character value, representing the numeric value in floating-point notation. If a 4-byte floating-point value is specified, the result value is 14 positions in length.

%EDITFLT Syntax Diagram

 character value = %EDITFLT( numeric expression ) 

See also %EDITC

The first parameter can be any numeric value, variable, literal, or expression. It is converted into the external representation (character form) of a floating-point value.

%EDITW (Edit with Edit Word)

The %EDITW function edits a numeric value and returns a character form of that value after applying the specified edit word.

%EDITW Syntax Diagram

 character value = %EDITC( numeric expression : 'edit word' ) 

See also %EDITC, %EDITFLT, and %CHAR.

The first parameter can be any numeric value, variable, literal, or expression (except floating point). If a floating point value is required, the %DEC built-in function can be used to convert the floating point value to packed decimal.

The second parameter must contain a valid edit word mask. The edit word is applied to the numeric expression and the character form of the value is returned. The same editing rules that apply to output field edit words apply to the %EDITW built-in function. See the example shown in Figure 4.8.

start figure

 .. ...CSRn01..............OpCode(ex)Extended-factor2+++++++++++++++++++++++++++++      C                   Eval     msg = 'Total due is '      C                                    + %EditW( amount : '$ ,  0.  CR') 

end figure

Figure 4.8: An example of the %EDITW built-in function.

%ELEM (Get Number of Elements)

The %ELEM function returns the number of elements declared for an array or table, or the number of occurrences of a multiple-occurrence data structure.

%ELEM Syntax Diagram

 number of elements = %ELEM( array ) number of occurrences = %ELEM( data structure ) 

See also %SIZE and %LEN

Specify an array, table, or multiple-occurrence data structure name as the first argument of the %ELEM function.

Use %ELEM in place of "hard coding" a reference to the number of elements of an array or occurrences of a data structure. Figure 4.9 shows an example.

start figure

 .....DName+++++++++++EUDSFrom+++To/Len+TDc.Functions+++++++++++++++++++++++++++ 0010 D States          S              2A   DIM(50) 0020 D I               S              5I 0 .....CSRn01..............OpCode(ex)Extended-factor2+++++++++++++++++++++++++++++ 0030 C                   For        I = 1 TO %ELEM(States) 0040 C                   MOVEL     States(I)     Where_Ever 0050 C* ....... other code can go here....... 0060 C                   endFOR 

end figure

Figure 4.9: An example of the %ELEM built-in function.

In Figure 4.9, the number of elements in the STATES array sets the limit for the FOR/ENDFOR loop. Because there are 50 elements in the STATES array, the FOR loop is performed 50 times.

%EOF (End of File Status)

The %EOF function checks the status of the last input operation for a file. If the beginning or end of the file has been reached as a result of that input operation, %EOF returns '1'; otherwise, %EOF returns '0'.

%EOF Syntax Diagram

 boolean indicator = %EOF( [ file name ] ) 

See also %FOUND, %ERROR, and %OPEN.

The first parameter is optional and can specify the name of a file being checked for the beginning or end of file condition. If a file name is not specified, %EOF applies to the most recent file operation. Figure 4.10 shows an example.

start figure

 .....CSRn01Factor1++++++OpCode(ex)Factor2+++++++Result++++++++Len++DcHiLoEq      C                   READ      ItemMast      C                   READ      CustMast      C                   IF        %EOF or %EOF(ItemMast)      **...      C                   endif 

end figure

Figure 4.10: An example of the %EOF built-in function.

The %EOF built-in function can be used in place of resulting indicator 3 for any of the operation codes shown in Table 4.2.

Table 4.2: Use of %EOF in Place of Indicator

Operation

Condition Tested

Description

READ

End of file.

Read next record.

READC

No more changed records.

Read next change subfile record.

READP

Beginning of file.

Read prior record.

READPE

Beginning of file.

Read prior record with equal key.

READE

End of file.

Read next record with equal key.

WRITE

Subfile full.

Write subfile detail record.

%EQUAL (Equal Condition Status)

The %EQUAL function checks the status of the last SETLL or LOOKUP operation.

%EQUAL Syntax Diagram

 boolean indicator = %EQUAL [ ( file name ) ] 

See also %FOUND and %EOF

The first parameter is optional and can specify the name of a file of a previous SETLL operation. The %EQUAL checks for an equal key condition (SETLL) or an equal match on a array/table search (LOOKUP). If a file name is not specified, %EQUAL applies to the most recent SETLL or LOOKUP operation. Figure 4.11 shows an example.

start figure

 .....CSRn01Factor1+++++++OpCode(ex)Factor2+++++++Result++++++++Len++DcHiLoEq      C     ItemNo        SETLL     ItemMast      C                   IF        %EQUAL( ItemMast )      C     ItemNo        LOOKUP    SaveItems                              75      C                   IF        %EQUAL      C                   CallP     RestoreItem      C                   endif      C                   endif 

end figure

Figure 4.11: An example of the %EQUAL built-in function.

The %EQUAL built-in function can be used in place of resulting indicator 3 for the SETLL operation (see Table 4.3). For the LOOKUP operation, resulting indicators are required because they control how the LOOKUP operation functions.

Table 4.3: Use of % EQUAL in Place of Indicator

Operation

Condition Tested

Operation Description

SETLL

Equal key condition

Set lower limits

LOOKUP

Equal element value

Look up with resulting indicator 3

There is a subtle difference between the %EQUAL and the %FOUND built-in functions as they relate to the SETLL operation. The %FOUND condition means that a record with a key value equal to or less than that specified in Factor 1 has been detected. Whereas the %EQUAL condition is set only when a key with a value equal to that of Factor 1 of the SETLL operation has been detected.

%ERROR (Error Condition Status)

The %ERROR function checks the status of the last operation that specified the E operation extender. If an error condition was set by that operation, %ERROR returns '1'. Otherwise, %ERROR returns '0'. Use %ERROR in place of resulting indicator 2.

%ERROR Syntax Diagram

 boolean value = %ERROR 

See also %FOUND, %EOF, and %STATUS

Any operation code that supports resulting indicator 2 supports the E operation extender. If the E operation extender is specified, %ERROR is set as a result of the operation. If the E operation extender and resulting indicator 2 are not specified, %ERROR is not set and the normal RPG error/exception handling routine is evoked. See Figure 4.12 for an example.

start figure

 .....CSRn01Factor1+++++++OpCode(ex)Factor2+++++++Result++++++++Len++DcHiLoEq      C CustNo            CHAIN(E)  CustMast      C                   SELECT      C                   When      %ERROR      C                   CallP     CheckForLock      C                   When      %EOF      C                   CallP     LastRecord      C                   endSL 

end figure

Figure 4.12: An example of the %ERROR built-in function.

Tip

Remember, %ERROR and %STATUS are set only when the E operation extender is used for the operation. If the E operation extender is not used, the state of %ERROR and %STATUS does not change.

%FIELDS (Identify Fields to Update)

%FIELDS isn't really a built-in function; it is a parameter keyword of the free-format version of the UPDATE and in the future, the WRITE operation codes.

%FIELDS identifies the field names of a database file that should be updated when an UPDATE operation code is performed.

%FIELDS Syntax Diagram

 %FIELDS( field1 {: field2 {: field3...}} ) 

See also: %KDS

%FIELDS can accept any number of field names as parameters. Each field specified must be the name of a field within the database file being updated. When a field name has been renamed within the program, the new, internal name must be used. The following example illustrates the use of the %FIELDS built-in function.

 .....C+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++       /free 0001     chain %kds(Customer : 1) CustRec; 0002     ExFmt EditCust; 0003     if %Found(CustMast); 0004       update CustRec %fields(CustName : Addr1 : City : State: Zip); 0005     endif;       /end-free 

Line 4 contains the free-format UPDATE operation code. The %FIELDS built-in function acts as a parameter to that operation code, controlling which fields are to be updated in the database file.

%FLOAT (Convert to Floating Point Value)

The %FLOAT function converts a numeric value, expression, or variable to floating point.

%FLOAT Syntax Diagram

 floating point value = %FLOAT( numeric expression ) 

Any valid numeric expression or variable can be specified. The returned value is in floating-point notation and can be used in subsequent expressions. Use this built-in function when floating-point notation is required in mathematical expressions, as when a procedure requires a floating-point parameter value. Figure 4.13 shows an example.

start figure

 .....DName+++++++++++EUDSFrom+++To/Len+TDc.Functions+++++++++++++++++++++++++++ 0010 D Amount          S              5P 2 INZ(27.50) 0020 D Term            S              3P 0 INZ(360) 0030 D Due             S              8F .....CSRn01..............OpCode(ex)Extended-factor2+++++++++++++++++++++++++++++ 0040 C                   Eval      Due =%Float(Amount) * %Float(Term) 

end figure

Figure 4.13: An example of the %FLOAT built-in function.

%FOUND (Record/String Found Condition)

The %FOUND function checks the status of the found condition for a file or string-operation code.

%FOUND Syntax Diagram

 boolean indicator = %FOUND[ ( file name ) ] 

See also %EQUAL and %EOF.

The first parameter is optional and can be the name of a file for a previous file operation. The %FOUND function checks for a record-found condition for the CHAIN, DELETE, SETGT, and SETLL operations. If a file name is not specified, %FOUND applies to the most recent file, string, or LOOKUP operation. See Figure 4.14 for an example.

start figure

 .....CSRn01Factor1+++++++OpCode(ex)Factor2+++++++Result++++++++Len++DcHiLoEq      C     ItemNo        CHAIN     ItemMast      C                   IF        %FOUND      C                   CallP     ChangeItem      C                   else      C                   CallP     AddNewItem      C                   endIf      C     Category      LOOKUP    ItemCat                            71  75      C                   IF Not    %FOUND      C                   CallP     BadCategory      C                   endif 

end figure

Figure 4.14: An example of the %FOUND built-in function.

Table 4.4: Use of % EQUAL in Place of Indicator

Operation

Condition Tested

Description

SETLL

Equal key condition.

Set lower limits.

CHAIN

Record found.

Random access a file.

DELETE

Record found.

Delete database record.

SETGT

Record found.

Set greater than.

CHECK

Located alternate data.

Verify string.

CHECKR

Located alternate data.

Verify string reverse.

SCAN

Pattern found.

Scan string.

LOOKUP

Search specification.

Look up array element.

The %FOUND built-in function is used in place of resulting indicators for the file and string operation codes. For the LOOKUP operation, %FOUND is used in conjunction with the resulting indicators that control the LOOKUP operation itself.

%GRAPHIC (Convert to Double-Byte Character Value)

The %GRAPHIC function converts a character value or expression to graphic. %GRAPHIC is defined as DBCS (double-byte character set) data.

%GRAPHIC Syntax Diagram

 graphic value = %GRAPHIC( character expression [: ccsid ]) 

Any valid character expression or variable can be specified. The returned value is in graphic notation. The second parameter is the CCSID code that is used for the return value. Figure 4.15 shows an example.

start figure

 .....DName+++++++++++EUDSFrom+++To/Len+TDc.Functions+++++++++++++++++++++++++++ 0010 D Name            S             12A Inz('www.RPGIV.com') 0020 D uName           S             20G .....CSRn01..............OpCode(ex)Extended-factor2+++++++++++++++++++++++++++++ 0040 C                   Eval      uName = %Graphic( name ) 

end figure

Figure 4.15: An example of the %GRAPHIC built-in function.

%INT (Convert to Integer Value)

The %INT function converts a numeric value, expression, or variable to integer format.

%INT Syntax Diagram

 integer value = %INT( numeric or character expression ) integer value = %INTH( numeric or character expression ) 

See also %UNS.

Any valid numeric or character expression or variable can be specified. The returned value is in integer format and can be used in subsequent expressions. Use these built-in functions when integer notation is required in mathematical expressions, comparisons or assignments. For example, when specifying an array index, an integer is always required. See Figure 4.16.

start figure

 .....DName+++++++++++EUDSFrom+++To/Len+TDc.Functions+++++++++++++++++++++++++++ 00001 D Amount          S              5P 2 INZ(27.50) 0002 D szOption        S             12A   Inz('12') 0003 D Index           S             10I 0 0004 D DiscRate        S              7P 2 Inz(0.15) 0005 D Discount        S              5I 0 .....CSRN01..............OpCode(ex)Extended-factor2+++++++++++++++++++++++++++++ 0006 C                   Eval      Index = %Inz(szOption) 0007 C                   Eval      Discount = %IntH( Amount * DiscRate ) 

end figure

Figure 4.16: Example of %INT built-in function.

%KDS (Use a Data Structure as a Key List)

%KDS isn't really a built-in function; it is a parameter keyword of the free-format version of the CHAIN, DELETE, READE, READPE, SETGT, and SETLL operations.

%KDS identifies a data structure whose subfields will be used as a key list to access the database file.

%KDS Syntax Diagram

 %KDS( dsname { : subfield-count } ) 

See also: %FIELDS

%KDS accepts a data structure name. That data structure's subfields are used as a key list. Normally, key lists are defined using the KLIST and KFLD operation codes. Using %KDS a data structure can be used instead of a key list. %KDS converts the subfields of the data structure into an ad hoc key list.

The second parameter of %KDS is optional and, if specified, indicates the number of subfields to use as the key list. If unspecified, all subfields in the data structure are used for the ad hoc key list. %KDS can be used only with a data structure name.

 .....DName+++++++++++EUDS.......Length+TDc.Functions+++++++++++++++++++ 0001 D Customer      E DS                  ExtName(CustMast) .....C+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 0002  /free 0003     chain %kds(Customer : 2) CustRec; 0004     ExFmt EditCust; 0005     if %Found(CustMast); 0006       update CustRec %fields(CustName : Addr1 : City : State: Zip); 0007     endif; 0008  /end-free 

Line 1 declares an externally described data structure based on the CUSTMAST database file. The first field in the CUSTMAST database file is the CUSTNO field, and the second is the REGION field. The key to the custmast file is a combination of the CUSTNO and REGION field.

Line 3 performs a CHAIN operation (database get-by-key) to the CUSTMAST file. The %KDS built-in function contains the CUSTOMER data structure as its first parameter. This would normally create an ad hoc database key made up of all the subfields of the CUSTOMER data structure. The second parameter, however, contains the number 2, which indicates the number of data structure subfields to use to create the ad hoc key list. Therefore the CUSTNO and REGION fields are used to access the file.

%LEN (Set/Get Length)

The %LEN function retrieves the declared length of a variable or character expression, retrieves the current length of a variable length field, or sets the current length of a variable-length field.

%LEN Syntax Diagram

 resulting-length = %LEN( numeric-expression ) field-length = %LEN( character-field ) field-content-length = %LEN( %Trim(character-field) ) current-length = %LEN( varying-field ) %LEN( variable-field) = integer-expression 

See also %SIZE, %DECPOS, and %ELEM

To retrieve the declared length of a variable, specify the variable within the %LEN built-in function. Any valid character expression or variable can be specified. The returned value is in integer format and can be used in subsequent expressions. Figure 4.17 shows an example.

start figure

 .....DName+++++++++++EUDSFrom+++To/Len+TDc.Functions+++++++++++++++++++++++++++ 0010 D CustName        S             50A   Inz('The Lunar Spacecraft Co.') 0020 D CompName        S             50A   VARYING 0030 D myLength        S              5I 0 0040 D Amount          S              7P 2 .....CSRn01..............OpCode(ex)Extended-factor2+++++++++++++++++++++++++++++ 0050 C                   Eval      myLength =  %Len( Amount)      **   The value of MYLENGTH = 7 0060 C                   Eval      %Len( CompName ) = %Len( %TrimR( Custname ) )      **   The new current length of COMPNAME is 24 

end figure

Figure 4.17: Example of %LEN built-in function.

For variable length fields, %LEN returns the current length of the field (not the declared maximum length). To set the length of a variable-length field, specify %LEN on the left side of the equal sign of the EVAL operations.

%LOOKUPXX (Array Element Lookup [Search]))

The %LOOKUPXX function performs a case-sensitive search of an array for a search value. It returns the index of the array element that matches the search value and search condition.

%LOOKUPXX Syntax Diagram

 index  = %LOOKUP(  search-value : array {: start-index {: num-elems }}) index  = %LOOKUPLT( search-value : array {: start-index {: num-elems }}) index  = %LOOKUPGT( search-value : array {: start-index {: num-elems }}) index  = %LOOKUPLE( search-value : array {: start-index {: num-elems }}) index  = %LOOKUPGE( search-value : array {: start-index {: num-elems }}) 

See also: %TLOOKUPXX

The lookup function returns the array index of the array element that matches the search condition. There are five forms of the %LOOKUP function.

  • %LOOKUP - Search for an element that equals the search value.

  • %LOOKUPLT - Search for an element that is less than the search value.

  • %LOOKUPGT - Search for an element that is greater than the search value.

  • %LOOKUPLE - Search for an element that is less than or equal to the search value.

  • %LOOKUPGE - Search for an element that is greater than or equal to the search value.

The first parameter is the search value. The search is case-sensitive so the search value must be exactly the same as the pattern in the table. The variations of %LOOKUP that contain a Boolean search control will search for relative, or relative or equal matches.

The second parameter is the name of the array being searched (for table searches, use the %TLOOKUP function).

The third parameter is optional, and if specified, must be a numeric field or expression that indicates the first element in the array to begin the search.

The fourth parameter is optional, and if specified, must be a numeric field or expression that indicates the number of array elements to search.

If parameter 3 and parameter 4 are omitted, the entire array is searched beginning with the first element.

%NULLIND (Set/Get Null Indicator Property)

The %NULLIND function retrieves the null indicator property of a null-capable field. The %NULLIND built-in function can only be used when the program is compiled with the allow-null attribute set to ALWNUL (*USRCTL) *USRCTL.

%NULLIND Syntax Diagram

 boolean value  = %NULLIND( null-capable field ) %NULLIND( null-capable field ) = boolean expression 

To retrieve the null indicator, specify the variable within the %NULLIND built-in function (see Figure 4.18). The returned value is a Boolean value that is '1' or '0'.

start figure

 .....DName+++++++++++EUDSFrom+++To/Len+TDc.Functions+++++++++++++++++++++++++++ 0010 D ShipDate        S               D 0020 D DueDate         S               D .....CSRn01..............OpCode(ex)Extended-factor2+++++++++++++++++++++++++++++ .....CSRn01Factor1+++++++OpCode(ex)Factor2+++++++Result++++++++Len++DcHiLoEq 0030 C                   IF        %NULLIND( ShipDate) = *OFF 0040 C     Shipdate      AddDur    15:*Days     DueDate 0050 C                   Else 0060 C                   Eval      %NULLIND( dueDate ) = *ON 0070 C                   Endif 

end figure

Figure 4.18: An example of the %NULLIND built-in function.

To set the null indicator, specify the variable within the %NULLIND built-in function on the left side of the equal sign. Specify a Boolean expression on the right side of the equal sign. The Boolean value (*ON or *OFF can be used) is assigned to the null indicator for the field.

The null indicator is separate from the actual data stored in the field. The field's content is not changed by setting the null indicator.

%OCCUR (Set/Get the Occurrence of a Data Structure)

The %OCCUR function changes the current occurrence of a data structure, or retrieves the current occurrence of a data structure.

%OCCUR Syntax Diagram

 occurrence  = %OCCUR(  data-structure ) %OCCUR(  data-structure ) 

See also: %OCCUR operation

When used on the right-side of the equals sign on an assignment statement, or in a comparison operation, %OCCUR returns the current occurrence of the data structure specified in the first parameter.

When used on the left-side of the equals sign on an assignment statement %OCCUR will set the current occurrence to the value specified on the right-side of the equals sign.

Figure 4.19 illustrates the use of the %OCCUR built-in function.

start figure

 .....DName+++++++++++EUDS.......Length+TDc.Functions+++++++++++++++++++++++ 0001 D MyDS            DS                  Occurs(20) 0002 D  CustNo                        7P 0 0003 D  Company                      30A 0004 D  Address                      25A 0005 D  City                         20A 0006 D nPos            S              5I 0 .....CSRn01..............OpCode(ex)Extended-factor2+++++++++++++++++++++++++ 0007 C                   Eval      nPos = %occur( myDS ) 0008 C                   If        %occur( myDS ) = %size( myDS ) 0009 C                   Eval      %occur( myDS ) = 1 0010 C                   Else 0011 C                   Eval      %occur( myDS ) = %occur( myDS ) + 1 0012 C                   endif 

end figure

Figure 4.19: Multiple occurrence data structure use of %OCCUR function.

%OPEN (Check for File Open Condition)

The %OPEN function returns the current open status of the specified file.

%OPEN Syntax Diagram

 boolean value = %OPEN( file name ) 

A file can be checked for an open or closed status using the %OPEN built-in function. Simply prefix the %OPEN with the NOT operator to check for a closed condition (as shown in Figure 4.20).

start figure

 .....FFileName++IFEASFRlen+LKeylnKFDevice+.Functions++++++++++++++++++++++++++++ 0010 FCustMast  UF A E             DISK    USROPN .....CSRn01..............OpCode(ex)Extended-factor2+++++++++++++++++++++++++++++ 0020 C                   IF        NOT %OPEN(CustMast) 0030 C                   Open      CustMast 0040 C                   EndIf 

end figure

Figure 4.20: An example of the %OPEN built-in function.

The File specification keyword USROPN (line 10) causes the RPG cycle to avoid automatically opening the file when the program is first called. The IF condition (line 20) tests the file to see if it has already been open. If is has not previously been open, the OPEN operation (line 30) opens the file.

%PADDR (Get Procedure Address)

The %PADDR function returns the address for a procedure. A procedure is similar to a subroutine, except that other procedures and programs call procedures, procedures accept parameters, and procedures support local variables.

%PADDR Syntax Diagram

 pointer-to-procedure = %PADDR( 'quoted-literal' ) pointer-to-procedure = %PADDR( procedure-prototype ) 

See also %ADDR and PROCPTR

Specify a quoted character string, a hexadecimal value, or a named constant, or a prototype name for the %PADDR function. The compiler resolves a procedure pointer at compile time and stores it in the compiled object.

Procedure addresses are resolved when program modules are bound together. Therefore, the compiler must be able to resolve a procedure name during the bind phase. This is in contrast to the dynamic CALL operation that resolves program addresses at runtime. Consequently, a field name cannot be specified for the %PADDR function. See Figure 4.21 for an example of the use of the %PADDR built-in function.

click to expand
Figure 4.21: An example of the %PADDR built-in function.

When a prototype name is specified, the prototype must be a prototype for a procedure (not a program) written in a language other than Java.

%PARMS (Get Parameter Count)

The %PARMS function returns the number of parameters passed to the procedure or program. When used in the mainline calcuations section of a program, the value returned for %PARMS is the same value that appears in the *PARMS locations of the program's Status Data Structure (SDS). For subprocedures, however, %PARMS returns the number of parameters passed to the subprocedure.

%PARMS Syntax Diagram

 numeric return variable = %PARMS 

The %PARMS function has no parameters of its own, and %PARMS cannot be used within a definition specification keyword. Specifically, it cannot be used to initialize a field. Figure 4.22 shows an example of its proper use.

click to expand
Figure 4.22: An example of the %PARMS built-in function.

%REM (Integer Division, Return Remainder)

The %REM function performs integer division on the two arguments. The first argument is the numerator and the second is the denominator. The remainder from this division operation is returned.

%REM Syntax Diagram

 integer remainder = %REM( numerator : denominator ) 

See also %DIV

The remainder operation returns an integer (whole number) result value. See Figure 4.23 for an example. The numerator and the denominator must be numeric values with no decimal digits. If numeric variables are used, they cannot contain decimal positions.

start figure

 .....DName+++++++++++EUDS.......Length+TDc.Functions++++++++++++++++++++++++++++ 0010 D Count           S              7S 0 Inz(25) 0020 D Total           S              7P 0 Inz(220) 0030 D Quot            S              5I 0 0040 D Remain          S              5I 0 .....CSRn01..............OpCode(ex)Extended-factor2+++++++++++++++++++++++++++++ 0050 C                   Eval      quot = %DIV( Total : Count ) 0060 C                   Eval      rem  = %REM( Total : Count ) 0070 C                   Eval      msg  = 'Total divided by Count = ' + 0080 C                                %Char(quot) + ' remainder ' + %Char(rem)      ** MSG = 'Total divided by Count = 8 remainder 20' 

end figure

Figure 4.23: An example of the %REM built-in function.

The %REM operation can be specified on the definition specification when the two arguments are constant values that fit within 8-byte integer values (20 digits).

By definition, integer division doesn't perform rounding. Therefore, the half-adjust operation extender is not supported.

%REPLACE (Replace/Insert Character String)

The %REPLACE function returns a character string that is created by replacing or inserting one character string in another.

%REPLACE Syntax Diagram

 verifying-length value = %REPLACE( replacement string : source string                            [: start position [: replacement length ]]) 

See also %SUBST and %SCAN

The first parameter, REPLACEMENT STRING, is the character string that will be inserted into the SOURCE STRING (the second parameter).

The second parameter, SOURCE STRING, is the string that contains the data that is the original or SOURCE STRING for the replacement. This string is modified using the first parameter.

The third parameter, START POSITION, identifies the starting position, within the SOURCE STRING (second parameter), where the insertion or replacement is to occur. If this parameter is not specified, the starting position defaults to position 1.

The fourth parameter, REPLACEMENT LENGTH, indicates the number of characters that are to be deleted from the source string before inserting the replacement string. This value can be 0 through the length of the source string. If not specified, the length of the replacement string is used as the replacement length.

When the replacement length is 0, the function inserts the replacement string into the source string at the start position.

When inserting, the replacement string is inserted into the source string prior to the starting position. When replacing, the replacement string is inserted into the source string, starting with the starting position, and continues for the number of characters specified for the replacement length.

%SCAN (Scan Character String)

The %SCAN function returns the location of the scan pattern, within the scanned data.

%SCAN Syntax Diagram

 found position = %SIZE( scan pattern : scan data [ : start position ] ) 

See also %REPLACE, and SCAN, CHECK, CHECKR, and LOOKUP

The first parameter is the scan pattern that is searched for the value in the second parameter. The second parameter is the scan data that is searched for the scan pattern specified in the first parameter. The third parameter is optional and, if specified, indicates the starting position for the scan, within the scan data. Figure 4.24 shows a code example of %SCAN.

start figure

 .....DName+++++++++++EUDS.......Length+TDc.Functions++++++++++++++++++++++++++++ 0010 D CustName        S              35A Inz('The Lunar Spacecraft Company') 0020 D POS             S               5P 0 .....CSRn01..............OpCode(ex)Extended-factor2+++++++++++++++++++++++++++++ 0050 C                   Eval      POS = %SCAN('craft' : CustName)      **  POS = 16 0060 C                   Eval      POS  = %SCAN('Moon' : CustName)      **  POS = 0 The search pattern data was not found in the CUSTNAME field. 0070 C                   IF        %SCAN('Company' : CustName) >0      **  If CUSTNAME contains the string "Company" the IF condition is true.      C                   EndIf 

end figure

Figure 4.24: An example of the %SCAN built-in function.

%SHTDN (Check for System Shut Down or Job End Request)

The %SHDN function returns *ON if the job running the program has been issued an end request, otherwise the function returns *OFF.

%SHTDN Syntax Diagram

 bool = %shtdn( ) 

The shut down function returns true (i.e., *ON or '1') when the system operator has requested a shutdown of the job running the RPG program.

%SIZE (Get Size in Bytes Used)

This function returns the number of bytes of memory used by the value. For character and zoned numeric values, the value returned is also the length of the field. For packed numeric fields, the value returned is calculated using the packing algorithm.

%SIZE Syntax Diagram

 numeric return value = %SIZE( variable [ : *ALL ] ) 

See also %LEN and %DECPOS

For tables and arrays, or multiple-occurrence data structures, the length of a single element or occurrence is returned unless *ALL is specified for the second argument. *ALL causes the size of the array element or data structure to be multiplied by the number of elements or occurrences. For all other data types, see Table 4.5.

Table 4.5: %SIZE Return Values

Field Type

Length

%SIZE Returns

Char

1 to 65,535

Declared length.

Variable length

Variable

Declared length + 2.

Packed

1 to 30

((Declared length) / 2) + 1.

Zoned

1 to 30

Declared length.

Date

6, 8, or 10

Declared length.

Integer (U or I)

3

1

Integer (U or I)

5

2

Integer (U or I)

10

4

Integer (U or I)

20

8

Float

N/A

8

Binary

4

2

Binary

9

4

Pointer

N/A

16

Graphic

any

Declared length.

Array

any

Number of bytes used by a single array element.

Array : *ALL

any

Number of bytes used by the entire array.

Data structure

any

Number of bytes used by one occurrence of the data structure.

Data Struct:*ALL

any

Number of bytes used by all occurrences of the data structure.

Because %SIZE returns the number of bytes of memory allocated to a variable, the actual length of a field is not necessarily returned (as is the case with packed decimal fields). To determine the declared length of a variable, the %LEN built-in function can be used. Figure 4.25 illustrate the use of %SIZE.

click to expand
Figure 4.25: An example of the %SIZE built-in function.

%SQRT (Compute Square Root)

The %SQRT function calculates the square root of a number and returns that square root.

%SQRT Syntax Diagram

 square-root = %SQRT( expression ) 

See also: SQRT operation

The square root function returns the square root of the expression. The first parameter must be a numeric value, expression, field, or literal value whose square root is calculated by the function.

%STATUS (File or Program Status Code)

The %STATUS function returns the status code for the most recent file operation or the status code for the program. This function is set only when the E operation extender is used.

%STATUS Syntax Diagram

 boolean indicator = %STATUS[ ( file name ) ] 

See also %ERROR.

The first parameter is optional and can be the name of a file for a previous file operation (see Figure 4.26). A separate area for each file declared in the program and an area for the program status code is created. Neither the INFDS nor PSDS is required to retrieve the file or program status. If the file name is not specified, the status code for the most recent file operation is returned. The status area for a file is reset to zero when an operation on that file is encountered that uses the E operation extender.

start figure

 .....CSRn01Factor1+++++++OpCode(ex)Factor2+++++++Result++++++++Len++DcHiLoEq 0010 C     ItemNo        CHAIN(E)  ItemMast 0020 C                   IF        %ERROR 0030 C                   Select 0040 C                   When      %Status = 1211 0050 C                   Exsr      FileNotOpen 0060 C                   When      %Status = 1218 0070 C                   Exsr      RecLocked 0080 C                   endSL 0090 C                   endIF 

end figure

Figure 4.26: An example of the %STATUS built-in function.

File-related status codes are in the range 1000 to 9999. Program-releated status codes are in the range 100 to 999.

Some of the file status codes are listed in the table that follows. For a complete list see Table X.Y.

Table 4.6: Common File Status Error Codes

Status

Description

*FILE

Any file status code

01201

Record mismatch detected on input.

01211

I/O operation to a closed file.

01215

OPEN issued to a file already opened.

01216

Error on an implicit OPEN/CLOSE operation.

01217

Error on an explicit OPEN/CLOSE operation.

01218

Record already locked.

01221

Update operation attempted without a prior read.

01222

Record cannot be allocated due to referential constraint error

01231

Error on SPECIAL file.

01235

Error in PRTCTL space or skip entries.

01241

Record number not found. (Record number specified in record address file is not present in file being processed.)

01299

Other I/O error detected.

Several of the program status codes are listed in the table that follows. For a complete list see Table 4.7.

Table 4.7: Common Program Status Error Codes

Status

Description

00100

Value out of range for string operation.

00101

Negative square root.

00102

Divide by zero.

00103

An intermediate result is not large enough to contain the result.

00104

Float underflow. An intermediate value is too small to be contained in the intermediate result field.

00105

Invalid characters in character to numeric conversion functions.

00112

Invalid Date, Time or Timestamp value.

00113

Date overflow or underflow.

00114

Date mapping errors, where a Date is mapped from a 4-digit year to a 2-digit year, and the date range is not 1940–2039.

00115

Variable-length field has a current length that is not valid.

00120

Table or array out of sequence.

00121

Array index not valid.

00122

OCCUR outside of range.

00123

Reset attempted during initialization step of program.

00202

Called program or procedure failed; halt indicators (H1 to H9) are not on.

00211

Error calling program or procedure.

00222

Pointer or parameter error.

00231

Called program or procedure returned with halt indicator on.

00232

Halt indicator on in this program.

00233

Halt indicator on when RETURN operation run.

00299

RPG IV formatted dump failed.

%STR (Get/Store Null-Terminated C-String)

The %STR function does the following:

  • Returns a normal character string value from a C-language-based, null-terminated string.

  • Allows normal character data to be copied to a C-language, null-terminated string.

%STR Syntax Diagram

 character value = %STR( base-pointer [ : length ] ) %STR( base-pointer : length ) = character value 

The first parameter is required and must contain a variable of type pointer. The pointer must contain the address of a memory location. Normally, the memory location is either the address of a variable in the program or the address of memory allocated with the ALLOC operation.

The second parameter indicates the number of bytes to extract or modify. Effectively, this is the maximum length of the data located at the address stored in the base-pointer (parameter 1). Figure 4.27 shows an example using the %STR built-in function.

start figure

 .....DName+++++++++++EUDS.......Length+TDc.Functions++++++++++++++++++++++++++++ 0010 D pCompany        S               * 0020 D CustName        S             35A   Inz('The Lunar Spacecraft Company') .....CSRn01Factor1+++++++OpCode(ex)Factor2+++++++Result++++++++Len++DcHiLoEq.... 0030 C                   Alloc     100        pCompany 0040 C                   Eval      %STR( pCompany : 100 ) = %trimL(CustName) 

end figure

Figure 4.27: An example of the %STR built-in function.

The result of the example shown in Figure 4.27 is that the value of CUSTNAME is copied to the 100 bytes of storage allocated by the ALLOC operation (line 30). The value is followed immediately by a X'00'. This X'00' is a null-terminator and is used by the C language. The X'00' value is moved to the position following the letter "y" in the word "Company" in the CUSTNAME field.

%SUBDT (Substring Date - Extract a Date or Time Component)

The %SUBDT function extracts a portion of a date, time, or timestamp value and returns that value as an unsigned numeric integer value.

%SUBDT Syntax Diagram

 duration = %SUBDT( dts : duration-code ) 

See also: %DIFF

The substring date operation returns an integer (the duration value) of a valid date, time, or timestamp value.

The first parameter must be a valid date, time, or timestamp datatype. The duration code (parameter 2) is required and indicates the format for the returned value. The value duration codes are as follows:

  • *DAYS, *MONTHS, *YEARS or *D, *M, *Y

  • *MSECONDS, *SECONDS, *MINUTES, *HOURS, or *MS, *S, *MN, *H

The *DAYS and *D duration codes always returns the day of the month, regardless of the date format of the dts (date, time or timestamp) value. The *YEARS and *Y duration codes always return a 4-digit year, regardless of the date format of the dts parameter.

%SUBST (Get/Set a Substring of a Value)

The %SUBST function:

  • Returns a portion of a value or variable.

  • Identifies a portion of a field as the target of an assignment operation.

%SUBST Syntax Diagram

 return value = %SUBST( base-value : start [ : length ] ) %SUBST( base-value : start [ : length ] ) = value to assign 

See also %REPLACE, %SCAN, and SUBS.

The %SUBST function accepts three parameters:

  • The base value to be "substringed."

  • The starting position within the base value.

  • The number of bytes (including the starting position) to be included. This parameter is optional.

If the third parameter is omitted, the implied length is derived from the starting position to the end of the base value. For extraction (the first form of %SUBST), the base value can be any field or literal value. The start location and length can be a literal, a field, or a numeric expression. For assignment (the second form of %SUBST), the base value can be any character field, array, data structure, data structure subfield, or array element.

The %SUBST function is the only built-in function that can be specified on either side of the assignment symbol of the EVAL operation for assignment purposes. Figure 4.28 shows a code example of %SUBST.

click to expand

click to expand
Figure 4.28: Example of %SUBST built-in function.

%TIME (Convert to Time Value)

The %TIME function converts a numeric, character, or timestamp value to a valid time datatype value.

%TIME Syntax Diagram

 time-value = %TIME( { expression {: time-format-code }} ) 

See also: %DATE, %TIMESTAMP

The time function performs two functions: (1) It converts a non-time value into a time value using the optional time-format code, and (2) if no parameters are specified, it returns the current system time.

The time format codes that may be specified in parameter 2 of the %TIME function are as follows:

Format Code

Date Format

*HMS

HH:MM:SS

*ISO

HH.MM.SS

*USA

HH:MM AM

*EUR

HH.MM.SS

*JIS

HH:MM:SS

The time format code may be specified with a separator character when converting from a character value to a time value, to indicate that a separator other than the default separator is used in the character time value. The separator is not allowed when converting from a numeric value. In addition a separator of 0 (zero) may be specified with the time-format code to indicate that the character time value contains no separators.

%TIMESTAMP (Convert to Timestamp Value)

The %TIMESTAMP function converts a numeric, character, or timestamp value to a valid timestamp datatype value.

%TIMESTAMP Syntax Diagram

 time-value = %TIMESTAMP( { expression {: *ISO | *ISO0 }} ) 

See also: %DATE, %TIME

The %TIMESTAMP function performs two functions: (1) It converts a non-timestamp value into a timestamp value using the optional separator formatting code (parameter 2), and (2) if no parameters are specified, it returns the current system timestamp value.

The timestamp format codes that may be specified in parameter 2 of the %TIMESTAMP function are as follows:

Format Code

Date Format

*ISO

YYYY-MM-DD-HH.MM.SS.MMMMMM

*ISO0

YYYYMMDDHHMMSSMMMMMM

The timestamp format code of *ISO or *ISO0 may be specified when converting from a character value to a timestamp value, to indicate that no separator is used; a separator of 0 (zero) may be specified.

%TLOOKUPXX (Table Element Lookup [Search]))

The %TLOOKUPXX function performs a case-sensitive search of a table for a search value. It returns *ON if the search is successful or *OFF is the search fails.

 %TLookUpxx Syntax Diagram bool  = %TLOOKUP(  search-value : table {: alt-table } ) bool  = %TLOOKUPLT( search-value : table {: alt-table } ) bool  = %TLOOKUPGT( search-value : table {{: alt-table } ) bool  = %TLOOKUPLE( search-value : table {{: alt-table } ) bool  = %TLOOKUPGE( search-value : table {: alt-table } ) 

See also: %LOOKUPXX

The table lookup function searches a table for the search-value. If the search is successful, the table's current element is set to the element matching the search condition. If an alt-table (parameter 3) is specified, then its current element is also set to the same element as the first table. There are five forms of the %TLOOKUP function.

  • %TLOOKUP - Search for an element that equals the search value.

  • %TLOOKUPLT - Search for an element that is less than the search value.

  • %TLOOKUPGT - Search for an element that is greater than the search value.

  • %TLOOKUPLE - Search for an element that is less than or equal to the search value.

  • %TLOOKUPGE - Search for an element that is greater than or equal to the search value.

The first parameter is the search value. The search is case-sensitive so the search value must be exactly the same as the pattern in the table. The variations of %TLOOKUP that contain a Boolean search control, will search for relative, or relative or equal matches.

The second parameter is the name of the table being searched (for array searches, use the %LOOKUP function).

The third parameter is optional, and if specified, must be the name of another table whose element is set if the search is successful. In other words, the two tables are set to the same current element or index.

%TRIM, %TRIML, %TRIMR (Trim Leading and/or Trailing Blanks)

The %TRIM, %TRIML, and %TRIMR functions analyze a string value and return a string with its leading or trailing blank characters removed. Typically, these functions are used to concatenate a set of character string values or left justify a value:

  • %TRIML

Removes leading blank characters.

  • %TRIMR

Removes trailing blank characters.

  • %TRIM

Removes both leading and trailing blank characters.

%TRIM Syntax Diagram

 character return value = %TRIMx( base-value ) 

See also %CHAR and %EDITC

The value returned is a character string. It can be assigned to a variable or used in an expression. The base value must be a character value, expression, quoted character string, or variable. Figure 4.29 shows an example.

start figure

 .....DName+++++++++++EUDS.......Length+TDc.Functions++++++++++++++++++++++++++++ 0010 D Lefty           S             25A 0020 D Name            S             25A   INZ 0030 D First           S             20A   INZ('     Bob     ') 0040 D Last            S             20A   INZ('     Cozzi') .....CSRn01..............OpCode(ex)Extended-factor2+++++++++++++++++++++++++++++ 0060 C                   EVAL      Name = %TRIMR(First) + ' ' + %TRIML(Last) 0070 C                   Eval      Lefty = %TrimL(Name) 

end figure

Figure 4.29: An example of the %TRIM built-in function.

In the example shown in Figure 4.29, the interim value of the %TRIMR function is concatenated with the interim value of the %TRIML function (line 60). The blanks from the right side of the FIRST field are trimmed. The blanks from the left side of the LAST field are trimmed.

The trimmed value is copied to the NAME field. Then the blanks from the left side of the NAME field are trimmed, and the value is copied to the LEFTY field. This effectively left justifies the data that is copied to the LEFTY field (see Figure 4.30).

start figure

          1...v....1....v....2....v NAME  = '     Bob Cozzi           ' LEFTY = 'Bob Cozzi                ' 

end figure

Figure 4.30: The result of the %TRIM function shown in Figure 4.29.

%UCS2 (Convert to UCS-2)

The %UCS2 function converts a character string value to a UCS-2 varying length string.

%UCS2 Syntax Diagram

 UCS-2 character value = %UCS2( character value [: ccsid ]) 

See also %CHAR and %EDITC

The first parameter is the character value that is to be converted to the UCS-2 value. The second parameter is optional, and indicates the CCSID code for the resulting converted value.

%UNS (Convert to Unsigned Integer Value)

The %UNS function converts a numeric value, expression, or variable to integer format.

%UNS Syntax Diagram

 unsigned integer value = %UNS( numeric expression ) unsigned integer value with Half adjust = %UNSH( numeric expression ) 

See also %INT.

Any valid numeric expression or variable can be specified. The returned value is an unsigned integer and can be used in subsequent expressions. Use this built-in function when integer notation is required in mathematical expressions or comparisons. Figure 4.31 shows a code example.

start figure

 .....DName+++++++++++EUDSFrom+++To/Len+TDc.Functions+++++++++++++++++++++++++++ 0010 D Amount          S              5P 2 INZ(27.50) 0020 D DiscRate        S              7P 2 0030 D Discount        S              7P 2 Dim(500) .....CSRn01..............OpCode(ex)Extended-factor2+++++++++++++++++++++++++++++ 0040 C                   Eval      DiscRate = Discount( %UNS(Amount) ) 

end figure

Figure 4.31: An example of the %UNS built-in function.

An unsigned integer has a numeric range roughly double that of signed integer values. For example, a 2-byte signed integer has a range of -32,768 to 32,767 whereas an unsigned integer has a range of 0 to 65,535.

%XFOOT (Cross Foot Array Elements)

The %XFOOT function sums all the elements in the specified array and returns the product.

%XFOOT Syntax Diagram

 sum of array elements = %XFOOT( numeric array expression ) 

See also XFOOT

The first parameter is required and can be either of the following:

  • An array name.

  • An array-name expression.

An array-name expression is composed of multiple array names separated by standard arithmetic operations. Figure 4.32 shows a code example of using %XFOOT.

start figure

 .....DName+++++++++++EUDSFrom+++To/Len+TDc.Functions+++++++++++++++++++++++++++ 0010 D RemoteSales     S              7P 2 Dim(12) 0020 D LocalSales      S              5P 2 Dim( %elem(RegSales) ) 0030 D TotSales        S              7P 2 0040 D RemoteTot       S                   Like(TotSales) 0050 D LocalTot        S                   Like(TotSales) .....CSRn01..............OpCode(ex)Extended-factor2+++++++++++++++++++++++++++++ 0060 C                   Eval      LocalTot  = %XFoot( LocalSales ) 0060 C                   Eval      RemoteTot = %XFoot( RemoteSales ) 0060 C                   Eval      TotSales  = %XFoot( LocalSales + RemoteSales ) 

end figure

Figure 4.32: An example of the %XFOOT built-in function.

%XLATE (Translate Characters)

The %XLATE function translates a character value using a translation pattern.

%XLATE Syntax Diagram

 translated-value = %XLATE(from-pattern : to-pattern : base-value                           { : start-pos } ) 

See also: XLATE operation

The translate function translates the base-value using the translation patterns specified in the from-pattern and to-pattern parameters. Each character in the base-value is compared to the characters in the from-pattern. When a match is detected, the character is translated to the character in the corresponding position in the to-pattern value. If no match is detected, the original value is passed through unchanged.

The return value is the translated value; the original base-value is not changed.

The first parameter is a character value containing a list of characters, numbers, and symbols that will be matched against each character in the base-value.

The second parameter is a character value containing a list of characters, numbers and symbols that are inserted into the result value in place of the original characters.

The third parameter is the base character value that is translated using parameters 1 and 2.

The fourth parameter is optional, and if specified, indicates the starting position in the base-value for the translation to begin. Characters prior to start-pos are passed to the result unchanged.

 .....DName+++++++++++EUDS.......Length+TDc.Functions++++++++++++++++++++++++++ 0001 D UPPER           C                   'abcdefghijklmnopqrstuvwxyz' 0002 D lower           C                   'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 0003 D Company         S             30A   Inz('The Lunar Spacecraft Company') 0004 D XComp           S                   Like(Company) 0005 C                  Eval       XComp = %xlate(lower:upper:Company)       ** XCOMP = 'THE LUNAR SPACECRAFT COMPANY' 




The Modern RPG IV Language
The Modern RPG IV Language
ISBN: 1583470646
EAN: 2147483647
Year: 2003
Pages: 156
Authors: Robert Cozzi

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net