Sunteți pe pagina 1din 13

https://sites.google.

com/site/freeformatforrpgle/

RPG FREE FORMAT COMPARED TO FIXED FORMAT

RPGIV/ILE/Free Format Operation Codes:


Some of the more useful opcodes follow, but not all.
Note: Some free format examples only work with V5R1 and higher.
Note: In free format end a line of code with a semicolon (;), all
code within structures are indented, and start a free format program with /FREE
and end the program with /END-FREE
Fixed Format Free Format
READ
/FREE
EXCEPT Heading EXCEPT Heading;
READ Rickfile READ Rickfile;
DOW NOT %EOF DOW NOT %EOF;
EXCEPT Detail EXCEPT Detail;
READ Rickfile READ Rickfile;
ENDDO ENDDO;
/END-FREE
READE
Note: Some free format examples only work with V5R1 and higher.
Note: For free format always use the actual name of the file and not the record format name.
/FREE
KEY SETLL Rickfile SETLL KEY Rickfile;
IF %EQUAL IF %EQUAL;
KEY READE Rickfile READE KEY Rickfile;
DOW NOT %EOF(Rickfile) DOW NOT %EOF(Rickfile);
EXCEPT Detail EXCEPT Detail;
READ Rickfile READ Rickfile;
ENDDO ENDDO;
ELSE ELSE;
EXCEPT NoDetail EXCEPT NoDetail;
ENDIF ENDIF;
/END-FREE
READP
Note: Some free format examples only work with V5R1 and higher.
Note: For free format always use the actual name of the file and not the record format name.
Note: In free format the EVAL operation is not required sometimes.
/FREE
KEY SETGT Rickfile SETGT KEY Rickfile;
READP Rickfile READP KEY Rickfile;
IF NOT %EOF(Rickfile) IF NOT %EOF(Rickfile);
EVAL Data# = Data# + 1 Data# = Data# + 1;
ELSE ELSE;
EXSR Error EXSR Error;
ENDIF ENDIF;
/END-FREE
CHAIN
Note: Some free format examples only work with V5R1 and higher.
Note: For free format always use the actual name of the file and not the record format name.
/FREE
KEY CHAIN Rickfile CHAIN KEY Rickfile;
IF %FOUND(Rickfile) IF %FOUND(Rickfile);
EXSR CustFound EXSR CustFound;
ELSE ELSE;
EXSR NoCust EXSR Error;
ENDIF ENDIF;
/END-FREE

Fixed Format Free Format


EVAL
Note: Some free format examples only work with V5R1 and higher.
Note: In free format the EVAL operation is not required sometimes.
Multiple Examples follow:
/FREE
EVAL Total = A * (B – 1) Total = A * (B – 1);
EVAL Total = Total +1 Total = Total + 1;
Total += 1; //Short for previous example
EVAL Total = Total – Count Total = Total – Count;
Total -= Count; //Short for previous example
EVAL Total = Total * Count Total = Total * Count;
Total *= Count; //Short for previous example
EVAL Total = Total / 7 Total = Total / 7;
Total /= 7; //Short for previous example
Total = Total ** 2; //Exponentiation
Total **= 2; //Exponentiation
//Short for previous example
EVAL(H) Interest = Rate * Amt EVAL(H) Interest = Rate * Amt; //EVALused for half
adjust
EVAL A = %TRIMR(‘Hi ‘) + A = %TRIMR(‘Hi ‘) + %TRIML(Chars);
%TRIML(Chars)
***After the EVAL below, the value of Chars contains ‘ab****ghijklmno’
EVAL %SUBST(Chars:3:4) = ‘****’ %SUBST(Chars:3:4) = ’****’;
/END-FREE
EVALR
Note: The expression is evaluation and the result is placed right-adjusted in the result field.
/FREE
EVALR Name = ‘Jimmie ‘ EVALR Name = ‘Jimmie ‘;
//Name = ‘Jimmie ‘ //Name = ‘Jimmie ‘
EVALR Name = %TRIMR(‘Jimmie ‘) EVALR Name = %TRIMR(‘Jimmie ‘;
//Name = ‘ Jimmie’ //Name = ‘ Jimmie’
/END-FREE

Fixed Format Free Format

ELSEIF
Note: Instead of Nesting Ifs use an ELSEIF or a SELECT/ENDSL below.
In the last stage of the ELSEIF, the ‘ELSE’ part is optional.
/FREE
IF Age >= 20 and Sex = ‘F’ IF Age >= 20 and Sex = ‘F’;
EVAL Code = 5 Code = 5;
ELSEIF Age >= 20 and Sex = ‘M’ ELSEIF Age >= 20 and Sex = ‘M’;
EVAL Code = 4 Code = 4;
ELSEIF Age >= 30 and Sex = ‘F’ ELSEIF Age >= 30 and Sex = ‘F’;
EVAL Code = 10 Code = 10;
ELSEIF Age >= 30 and Sex = ‘M’ ELSEIF Age >= 30 and Sex = ‘M’;
EVAL Code = 9 Code = 9;
ELSE ELSE
EVAL Code = 20 Code = 20;
ENDIF ENDIF;
/END-FREE
SELECT/ENDSL
Note: Instead of Nesting Ifs use a SELECT/ENDSL or an ELSEIF above.
In the last stage of the SELECT, the ‘OTHER’ part is optional.
/FREE
SELECT SELECT;
WHEN Age >= 20 and Sex = ‘F’ WHEN Age >= 20 and Sex = ‘F’;
EVAL Code = 5 Code = 5;
WHEN Age >= 20 and Sex = ‘M’ WHEN Age >= 20 and Sex = ‘M’;
EVAL Code = 4 Code = 4;
WHEN Age >= 30 and Sex = ‘F’ WHEN Age >= 30 and Sex = ‘F’;
EVAL Code = 10 Code = 10;
WHEN Age >= 20 and Sex = ‘M’ WHEN Age >= 30 and Sex = ‘M’;
EVAL Code = 9 Code = 9;
OTHER OTHER;
EVAL Code = 20 Code = 20;
ENDSL ENDSL;
/END-FREE

Fixed Format Free Format


FOR
Note: Controls the number of times a group of operations are processed.
/FREE
EVAL Factor = 1 Factor = 1;
FOR I = 1 to %LEN(Field) FOR I = 1 to %LEN(Field);
EVAL Factor = Factor + 1 Factor = Factor + 1;
ENDFOR ENDFOR;
/END-FREE

%CHAR
Note: Converts the value of the expression from graphic, UCS-2, numeric, date, time,
or timestamp data to type character.
/FREE
EVAL Result = ‘It is ‘ + %CHAR(Time) Result = ‘It is ‘ +%CHAR(Time)
+ ‘ on ‘ + %CHAR(Date) + ‘ on ‘ + %CHAR(Date);
*** Result = ‘It is 12:23:34 on 02/02/1977’
/END-FREE
%EDITC
Note: Returns a character result representing the edited number after applying and edit code.
/FREE
EVAL Sal = ‘The annual salary is ‘ Sal = ‘The annual salary is ‘
+ TRIM(%EDITC(Amt * 12 + TRIM(%EDITC(Amt * 12
:’A’ : *CURSYM)) :’A’: *CURSYM));
*** Sal = ‘The annual salary is $12,000.00’
/END-FREE

ADDDUR
Note: The ADDDUR operation adds the duration specified in factor 2 to a date or time and places the resulting
Date, Time or Timestamp in the result field.
/FREE
BillDate ADDDUR 30:*DAYS DueDate DueDate = BillDate + %DAYS(30);
/END-FREE

SUBDUR
Note: Subtract a duration to establish a new Date, Time or Timestamp.
/FREE
DueDate SUBDUR 30:*DAYS BillDate BillDate = DueDate - %DAYS(30);
/END-FREE
Fixed Format Free Format
EXTRCT
Note: Extracts a portion of a date, time, or timestamp data item.
/FREE
EXTRCT BirthDate:*Y BirthYear BirthYear = %SUBDT(BirthDate:*YEARS);
/END-FREE
%DEC / %DECH / %UNS / %UNSH / %INT / %INTH / %FLOAT
Note: As of V5R2 you can convert character arguments to numeric with all of these functions.
Note: These functions can now be used to support “LEGACY” code.
Note: The sign (+ or -), decimal point (. or ,), are optional.
Note: Invalid numeric data will set %STATUS = 00105.
/FREE
EVAL Chars = ‘-123.56’ Chars = ‘-123.56’;
EVAL Num = %DEC(Chars:5:2) Num = %DEC(Chars:5:2); //Num = -123.56
EVAL Num = %UNSH(Chars) Num = %UNSH(Chars); //Num = 124
/END-FREE
***D Spec:
D ToDate S 8 0 INZ(20021231)
D WorkDate S D
Fixed Format
EVAL ToDate = 20021231
EVAL WorkDate = %DATE(ToDate:*ISO) //WorkDate = D’2002-12-31’
EVAL WorkDate = WorkDate + %DAYS(30) //Add 30 days to WorkDate
EVAL ToDate = %UNS(%CHAR(WorkDate:*ISO)) //ToDate = 20030130
Free Format
/FREE
ToDate = 20021231;
WorkDate = %DATE(ToDate:*ISO); //WorkDate = D’2002-12-31’
WorkDate = WorkDate + %DAYS(30); //Add 30 days to WorkDate
ToDate = %UNS(%CHAR(WorkDate:*ISO)); //ToDate = 20030130
/END-FREE

Fixed Format Free Format

%TIME / %TIMESTAMP
Note: Converts the value of the expression from character, numeric, or |timestamp data to type time. The
converted value remains unchanged, but |is returned as a time.
Note: Available as of V5R2.
/FREE
EVAL String = ’12:34 PM’ String = ’12:34 PM’;
EVAL Time = %TIME(String,*USA) Time = %TIME(String:*USA);
//Time = t’12.34.00’
/END-FREE

Fixed Format Free Format

%DIFF
Note: Used to find the duration between: two dates, two times, two timestamps, a date and the date
portion of a timestamp, and a time and the time portion of a timestamp.
/FREE
EVAL DaysLeft = %DIFF(ExamDate: DaysLeft = %DIFF(ExamDate:Today:*DAYS);
Today:*DAYS) /END-FREE
MONITOR/ENDMON
Note: May be used with V5R1 and later.
Note: Used for error handling routines. ON-ERROR list one or more errors for which it is responsible.
These errors generally correspond to the %STATUS code from 00100 to 09999 or you can use *FILE
for file errors.
/FREE
MONITOR MONITOR;
READ Rickfile READ Rickfile;
DOW NOT %EOF(Rickfile) DOW NOT %EOF(Rickfile);
KEY CHAIN Rickfile2 CHAIN KEY Rickfile2;
EXSR DoSomething EXSR DoSomething;
READ Rickfile READ Rickfile;
ENDDO ENDDO;
ON-ERROR 1211 ON-ERROR 1211;
EXSR NotOpen EXSR NotOpen;
ON-ERROR 1218 ON-ERROR 1218;
EXSR LockedRec EXSR LockedRec;
ON-ERROR *FILE ON-ERROR *FILE;
EXSR FileErr EXSR FileErr;
ON-ERROR 00100 : 00121 ON-ERROR 00100 : 00121;
***Handle string error and array-index error***********************
EXSR STRARY EXSR STRARY;
ON-ERROR ON-ERROR;
***Handle all other errors**************************************
EXSR GenErr EXSR GenErr;
ENDMON ENDMON;
/END-FREE

Fixed Format Free Format

LEAVESR
Note: Used with free format only. Leaves a subroutine.
/FREE
LEAVESR;
/END-FREE
MOVE AND MOVEL
Note: RPGIV and free format provides a smoother process.
OLD RPGIII:
MOVEL FIELD1 FIELDA
MOVE FIELD2 FIELDA
MOVEL FIELDA FIELDB
MOVE FIELD3 FIELDB
NEW RPGIV and free format:
/FREE
EVAL FieldB = Field1 + Field2 + Field3 FieldB = Field1 + Field2 + Field3;
/END-FREE
INDICATOR DATA TYPE
Note: Some free format examples only work with V5R1 and higher.
Note: Some languages refer to this as a Boolean data type. An indicator field is a single-byte field
that can contain only two logical values: ‘1’ or ‘0’. You can also refer to these values using *ON
and *OFF, respectfully. Indicator data is usually used within an RPGIV program to signal a true/false
condition and can be tested on as a true/false condition.
Examples follow:
D Spec:
D IsGood S N INZ(*OFF)
/FREE
EXSR ChkGood EXSR ChkGood;
IF IsGood IF IsGood;
EXSR DoSomething EXSR DoSomthing;
EVAL IsGood = *OFF IsGood = *OFF;
ELSE ELSE;
EXSR GiveErr EXSR GiveErr;
ENDIF ENDIF;
/END-FREE

AID-Generating Keys(For testing if a key has been pressed)


The AID (attention indicator) code identifies to the host system the function being requested from the
keyboard. The AID code is returned by certain input operations when the operator presses an AID-generating
key. The following table lists the AID-generating keys and the AID codes associated with each key for
INFDS.

Note: If you don’t like testing with indicators, try using the INFDS
Note: Try using the File Information Data Structure (INFDS) below:
Note: Example code that is less cryptic than using indicators is on the next page.
F Spec:
F RickDsply CF E WORKSTN
INFDS(WkdSpa)
***File Information Data Structure
D Specs:
D WKDSPA DS
D Fkey 369 369
***Only use the keys you need below in your code
***Keys Pressed Constants
D F1 C CONST(X’31’)
D F2 C CONST(X’32’)
D F3 C CONST(X’33’)
D F4 C CONST(X’34’)
D F5 C CONST(X’35’)
D F6 C CONST(X’36’)
D F7 C CONST(X’37’)
D F8 C CONST(X’38’)
D F9 C CONST(X’39’)
D F10 C CONST(X’3A’)
D F11 C CONST(X’3B’)
D F12 C CONST(X’3C’)
D F13 C CONST(X’B1’)
D F14 C CONST(X’B2’)
D F15 C CONST(X’B3’)
D F16 C CONST(X’B4’)
D F17 C CONST(X’B5’)
D F18 C CONST(X’B6’)
D F19 C CONST(X’B7’)
D F20 C CONST(X’B8’)
D F21 C CONST(X’B9’)
D F22 C CONST(X’BA’)
D F23 C CONST(X’BB’)
D F24 C CONST(X’BC’)
D CLEAR C CONST(X’BD’)
D ENTER C CONST(X’F1’)
D HELP C CONST(X’F3’)
D PAGEUP C CONST(X’F4’)
D PAGEDN C CONST(X’F5’)
D PRINT C CONST(X’F6’)
Fixed Format Free Format
/FREE
IF Fkey = F1 IF Fkey = F1;
EXSR Func1 EXSR Func1;
ELSEIF Fkey = F2 ELSEIF Fkey = F2;
EXSR Func2 EXSR Func2;
ELSEIF Fkey = Enter ELSEIF Fkey = Enter;
EXSR FuncEnter EXSR FuncEnter;
ELSEIF Fkey = PageUp ELSEIF Fkey = PageUp;
EXSR FuncPgUp EXSR FuncPgUp;
ELSEIF Fkey = PageDn ELSEIF Fkey = PageDn;
EXSR FuncPgDn EXSR FuncPgDn;
ENDIF ENDIF;
/END-FREE
OR
Note: If you don’t like testing with indicators, try using the INDDS keyword which lets you associate a data structure name with
the INDARA indicators for a workstation or printer file. This data structure contains the conditioning and response indicators
passed to and from data management for the file, and is called an indicator data structure.
Note: Example code that is less cryptic than using indicators is on the next page.
F Spec:
F RickDsply CF E WORKSTN
INDDS(Indicators)
Example code on next page.
* These indicator variables can be tested on as Boolean Logical Variables.
* ‘IF Exit’ means the same thing as ‘IF Exit = *ON’.
In other words you test by coding ‘IF Exit’ and don’t use ‘If Exit = *ON’ and
code ‘IF NOT Exit’ and don’t use ‘IF Exit = *OFF’.
* To use these indicator types you have to declare the keyword INDARA in you display file (DDS).
D Indicators DS
* For PageDown(Rename PageDown to indicator 21 in subfile definition: PAGEDOWN(21 ‘PageDown’)
D PagDwn 21 21N
* Use for F3=Exit(Rename CF03 to indicator 03 in subfile definition: CF03(03 ‘F3=Exit’)
D Exit 3 3N
* Use for F5=Update(Rename CF05 to indicator 05 in subfile definition: CF05(05 ‘F5=Update’)
D Update 5 5N
* Use for F12=Cancel(Rename CF12 to indicator 12 in subfile definition: CF12(12 ‘F12=Cancel’)
D Cancel 12 12N
* Conditioning indicators for format "DispSflCtl"
D SflDSpctl 41 41N
D SflDsp 42 42N
D SflEnd 43 43N
D SflClr 44 44N
* Set indicators to display the subfile:
Fixed Format Free Format
C /FREE
C EVAL SflDsp = *ON SflDsp = *ON;
C EVAL SflEnd = *OFF SflEnd = *OFF;
C EVAL SflClr = *OFF SflClr = *OFF;
C EXFMT DispSflCtl EXFMT DispSflCtl;
*
* Using indicator variables, we can write more readable programs:
C EXFMT Query EXFMT Query;
C IF Exit or Cancel IF Exit or Cancel;
C RETURN RETURN;
C ELSEIF Update ELSEIF Update;
C EXSR Refresh EXSR Refresh;
C ELSEIF PagDwn ELSEIF PagDwn;
C EXSR LoadSF EXSR LoadSF;
C ENDIF ENDIF;
C /END-FREE

BUILT-IN FUNCTIONS

The original release of RPG IV included a set of built-in functions. These built-in functions were:

%ADDR, %PADDR, %SIZE, %ELEM, %SUBST, %TRIM, %TRIML, %TRIMR


In addition, under OS/400 V3R2 and V3R7 the %PARMS built-in function was introduced. Since then, several built-in functions
have been added to RPG IV. The following table provides the OS/400 Version and Release that the specific built-in functions were
introduced and/or enhanced.

Version Built-in Parameters Return Value Description


Release Function

V3R7 %ABS numeric expression Absolute value of expression


%ADDR variable name Address of variable

V5R1 %ALLOC memory size Pointer to the allocated storage.

V4R2 %CHAR graphic, date, time, timestamp, Value in character data type
V4R4 or numeric expression

V5R1 %CHECK compare-value : data-to- First position in the searched-data that contains a
search { : start-position } character not in the list of the characters in the
compare value.

V5R1 %CHECKR compare-value : data-to- Last position in the searched-data that contains a
search { : start-position } character not in the list of the characters in the
compare value. (Search begins with the right-most
character and proceeds to the left.

V5R1 %DATE { value { : date-format-code } A date data-type value after converting the "value"
to the specified date format. If no value is specified,
the current system date is returned.

V5R1 %DAYS Days A duration value that can be used in an expression


to add a number of days to a date value.

V3R7 %DEC numeric expression {:digits : Value in packed numeric format.


decpos} If digits anddecpos are specified the result value is
formatted to fit in a variable of the number of digits
specified.

V3R7 %DECH numeric expression : digits : Half-adjusted value in packed numeric format. The
decpos length and decimal positions

V3R7 %DECPOS numeric expression Number of decimal digits.

V5R1 %DIFF start-date : end-date : duration- Calculates the difference between two date fields.
code The type of difference returned is specified by the
duration-code.

V4R4 %DIV Numerator : Denominator Performs integer division and returns the quotient
(result) of that division operation.

V3R7 %EDITC non-float numeric expression : String representing edited value.


edit code {:*CURSYM |
*ASTFILL | currency symbol}

V3R7 %EDITFLT numeric expression Character external display representation of float.

V3R7 %EDITW non-float numeric expression : String representing edited value


edit word

%ELEM array, table, or multiple Number of elements or occurrences


occurrence data structure
name

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.

V3R7 %FLOAT numeric expression Value in float format.

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 %GRAPHIC Any character value Converts character data to double-byte character
set value.

V5R1 %HOURS Hours A duration value that can be used in an expression


to add a number of hours to a time value.

V3R7 %INT numeric expression Value in integer format

V3R7 %INTH numeric expression Half-adjusted value in integer format

V3R7 %LEN any expression 1. Returns the length of a variable or


literal value, or the current length of a
varying length field.

1. When used on the left side of


the equal sign, sets the length
of a varying length field.

V5R1 %LOOKUPxx search-data : array { : start- An array index of the element in the array where the
index { : elements to search }} search-data is located.

V5R1 %TLOOKUPxx search-data : searched-table { *ON if the search is successful, otherwise *OFF.
: alternate-table } (NOTE: The indexes of the searched-table and
alternate-table are set to the index of the search-
data if *ON is returned.)

V5R1 %MINUTES Minutes A duration value that can be used in an expression


to add a number of minutes to a time value.

V5R1 %MONTHS Months A duration value that can be used in an expression


to add a number of months to a date value.

V5R1 %MSECONDS milliseconds A duration value that can be used in an expression


to add a number of milliseconds to a time value.

V3R7 %NULLIND null-capable field name Value in indicator format representing the null
indicator setting for the null-capable field.

V5R1 %OCCUR data-structure The current occurrence of the data structure, or sets
the current occurrence of the data structure
V4R2 %OPEN file name '1' if the specified file is open '0' if the specified file
is closed. Consider this built-in to be an 'Is this file
open?" operation.

%PADDR procedure name Address of procedure

V3R2 %PARMS Number of parameters passed to procedure


V3R6

V5R1 %REALLOC pointer : new-size Pointer to the allocated storage.

V4R4 %REM Numerator : Denominator Performs integer division and returns the remainder
from the division operation.

V4R2 %REPLACE replacement string: source String produced by inserting replacement string into
string {:start position {:source source string, starting at start position and replacing
length to replace}} the specified number of characters.

V3R7 %SCAN search argument : string to be First position of search argument in string or zero, if
searched {:start position} not found.

V5R1 %SECONDS seconds A duration value that can be used in an expression


to add a number of seconds to a time value.

V5R1 %SHTDN *ON if the job is being shut down (e.g., when the
PWRDWNSYS command is issued) otherwise
*OFF is returned.

%SIZE variable, data structure, array, Number of bytes used by variable or literal. *ALL
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 expression or value The square root of the expression or value.

V4R2 %STATUS {file name} 0 if no program or file error occurred since the most
recent operation code with extender 'E' specified
most recent value set for any program or file status,
if an error occurred if a file is specified, the value
returned is the most recent status for that file.

V3R7 %STR pointer{:maximum length} Characters addressed by pointer argument up to


but not including the first x'00'.

V5R1 %SUBDT date : duration-code The extracted component of the date value. (The
functional equivalent of the EXTRCT operation
code.)

%SUBST string:start{:length} Substring value. If length is not specified, the


substring begins with start and continues through
the end of the string.

V5R1 %THIS Used for Java integration. Returns an Object


reference.
V5R1 %TIME { value { : time-format-code } A time data-type value after converting the "value"
to the specified time format. If no value is specified,
the current system time is returned.

V5R1 %TIMESTAMP {value { : *ISO | *ISO0 } A timestamp data-type value with or without
separators.

%TRIM string String with left and right blanks trimmed (removed)

%TRIML string String with left blanks trimmed

%TRIMR string String with right blanks trimmed

V4R4 %UCS2 Any character value Returns a varying length value.

V4R2 %UNS numeric expression Value in unsigned format

V4R2 %UNSH numeric expression Half-adjusted value in unsigned format

V5R1 %XLATE from-table : to-table : string-to- The converted string is returned.


convert { : starting-position }

V4R4 %XFOOT Array name Cross foots (totals) all the elements in an array.

INTERNET ADDRESSES FOR SOURCES OF INFORMATION ON RPGIV AND FREE FORMAT


www.iseries.ibm.com
www.redbooks.ibm.com
www.search400.com
www.rpgiv.com
www.mcpressonline.com
www.iseriesnetwork.com
Home page for all versions of RPG releases:
http://publib.boulder.ibm.com/pubs/html/as400/online/homeeng1.htm

S-ar putea să vă placă și