RPG Ile V7.1
RPG Ile V7.1
Version 7.1
IBM i
Version 7.1
Note Before using this information and the product it supports, read the information in Notices on page A-1.
This edition applies to IBM Rational Development Studio for i (product number 5770-WDS) and to all subsequent releases and modifications until otherwise indicated in new editions. This version does not run on all reduced instruction set computer (RISC) models nor does it run on CISC models. This document may contain references to Licensed Internal Code. Licensed Internal Code is Machine Code and is licensed to you under the terms of the IBM License Agreement for Machine Code. Copyright IBM Corporation 1994, 2014. US Government Users Restricted Rights Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
Contents
ILE RPG Reference
About ILE RPG Reference . . . . . . 1-1
Who Should Use This Reference . . Prerequisite and Related Information How to Send Your Comments . . . . . . . . . . . . . . . . 1-1 . 1-1 . 1-1 Defining Conditions . . . . . . . . . /DEFINE . . . . . . . . . . . /UNDEFINE . . . . . . . . . . Predefined Conditions . . . . . . . . Conditions Relating to the Environment Conditions Relating to the Command Being Used . . . . . . . . . . . Conditions Relating to the Target Release Condition Expressions . . . . . . . . Testing Conditions . . . . . . . . . /IF Condition-Expression . . . . . . /ELSEIF Condition-Expression . . . . /ELSE . . . . . . . . . . . . /ENDIF . . . . . . . . . . . . Rules for Testing Conditions . . . . . The /EOF Directive . . . . . . . . . /EOF . . . . . . . . . . . . . Handling of Directives by the RPG Preprocessor . . . . . . . . . . . Procedures and the Program Logic Cycle . . . . Subprocedure Definition . . . . . . . . Procedure Interface Definition . . . . . Return Values . . . . . . . . . . . Scope of Definitions . . . . . . . . . Subprocedures and Subroutines . . . . . Program Flow in RPG Modules: Cycle Versus Linear . . . . . . . . . . . . . . Cycle Module . . . . . . . . . . . Use Caution Exporting Subprocedures in Cycle Modules. . . . . . . . . . Linear Module. . . . . . . . . . . Linear Main Module . . . . . . . . NOMAIN Module . . . . . . . . Module Initialization . . . . . . . . Initialization of Global Data . . . . . RPG Cycle and other implicit Logic. . . . . Program Cycle. . . . . . . . . . . General RPG IV Program Cycle . . . . Detailed RPG IV Program Cycle . . . . Subprocedure Calculations. . . . . . . Implicit Opening of Files and Locking of Data Areas . . . . . . . . . . . . Implicit Closing of Files and Unlocking of Data Areas . . . . . . . . . . . . RPG IV Indicators . . . . . . . . . . . Indicators Defined on RPG IV Specifications Overflow Indicators . . . . . . . . . Record Identifying Indicators . . . . . . Rules for Assigning Record Identifying Indicators . . . . . . . . . . . Control Level Indicators (L1-L9) . . . . . Rules for Control Level Indicators . . . Split Control Field . . . . . . . . Field Indicators . . . . . . . . . . Rules for Assigning Field Indicators . . Resulting Indicators . . . . . . . . . 3-11 3-11 3-11 3-12 3-12 3-12 3-12 3-13 3-13 3-13 3-13 3-14 3-14 3-14 3-14 3-14 3-15 3-16 3-17 3-18 3-19 3-19 3-20 3-21 3-22 3-23 3-24 3-24 3-24 3-25 3-25 3-25 3-25 3-26 3-27 3-37 3-39 3-40 3-40 3-40 3-41 3-41 3-41 3-42 3-43 3-48 3-50 3-51 3-51
iii
| | | | | |
Rules for Assigning Resulting Indicators 3-52 Indicators Not Defined on the RPG IV Specifications . . . . . . . . . . . . 3-52 External Indicators . . . . . . . . . 3-53 Internal Indicators . . . . . . . . . 3-53 First Page Indicator (1P) . . . . . . 3-53 Last Record Indicator (LR) . . . . . . 3-53 Matching Record Indicator (MR). . . . 3-54 Return Indicator (RT) . . . . . . . . 3-54 Using Indicators . . . . . . . . . . . 3-54 File Conditioning . . . . . . . . . . 3-54 Rules for File Conditioning . . . . . 3-55 Field Record Relation Indicators . . . . . 3-55 Assigning Field Record Relation Indicators . . . . . . . . . . . 3-55 Function Key Indicators . . . . . . . 3-57 Halt Indicators (H1-H9). . . . . . . . 3-58 Indicators Conditioning Calculations . . . 3-58 Positions 7 and 8 . . . . . . . . . 3-58 Positions 9-11 . . . . . . . . . . 3-58 Indicators Used in Expressions . . . . . 3-61 Indicators Conditioning Output . . . . . 3-61 Indicators Referred to As Data . . . . . . 3-64 *IN . . . . . . . . . . . . . . 3-64 *INxx . . . . . . . . . . . . . . 3-64 Additional Rules . . . . . . . . . . 3-65 Summary of Indicators . . . . . . . . . 3-65 File and Program Exception/Errors . . . . . . 3-67 File Exception/Errors . . . . . . . . . 3-68 File Information Data Structure . . . . . 3-68 File Feedback Information . . . . . . 3-69 Open Feedback Information . . . . . 3-72 Input/Output Feedback Information . . 3-73 Device Specific Feedback Information 3-74 Get Attributes Feedback Information . . 3-77 Blocking Considerations . . . . . . 3-79 File Status Codes . . . . . . . . . 3-80 File Exception/Error Subroutine (INFSR) 3-82 Program Exception/Errors . . . . . . . . 3-84 Program Status Data Structure . . . . . 3-85 Program Status Codes . . . . . . . 3-89 PSDS Example . . . . . . . . . . 3-91 Program Exception/Error Subroutine . . . 3-93 General File Considerations . . . . . . . . 3-93 Rules for File Names . . . . . . . . . 3-94 File devices . . . . . . . . . . . . . 3-94 File device types . . . . . . . . . . 3-94 Global and Local Files . . . . . . . . . 3-95 Open Access Files . . . . . . . . . . 3-95 Locating an Open Access Handler . . . . 3-95 Open Access Handlers . . . . . . . . 3-95 Example of an Open Access Handler . . 3-97 File Parameters . . . . . . . . . . . 3-105 Variables Associated with Files . . . . . . 3-105 Example of passing a file and passing a data structure with the associated variables. 3-106 Full Procedural Files . . . . . . . . . 3-108 Primary/Secondary Multi-file Processing 3-108 Multi-file Processing with No Match Fields 3-108 Multi-file Processing with Match Fields 3-108 Assigning Match Field Values (M1-M9) 3-109
Processing Matching Records File Translation . . . . . . . Specifying File Translation . . Translating One File or All Files Translating More Than One File Specifying the Files . . . . Specifying the Table . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
Definitions . . . . . . . . . . . . . 4-1
Defining Data and Prototypes . . . . . . . General Considerations . . . . . . . . Scope of Definitions . . . . . . . . Storage of Definitions . . . . . . . . Standalone Fields . . . . . . . . . . Variable Initialization . . . . . . . . Constants . . . . . . . . . . . . . Literals . . . . . . . . . . . . Example of Defining Literals . . . . Example of Using Literals with Zero Length . . . . . . . . . . . . Named Constants . . . . . . . . . Figurative Constants . . . . . . . . Rules for Figurative Constants . . . Data Structures . . . . . . . . . . Qualifying Data Structure Names . . . Array Data Structures . . . . . . . Defining Data Structure Parameters in a Prototype or Procedure Interface. . . . Defining Data Structure Subfields . . . Specifying Subfield Length . . . . Aligning Data Structure Subfields . . Initialization of Nested Data Structures Special Data Structures . . . . . . . Data Area Data Structure . . . . . File Information Data Structure . . . Program-Status Data Structure . . . Indicator Data Structure . . . . . Data Structure Examples . . . . . . Prototypes and Parameters . . . . . . Prototypes . . . . . . . . . . . Prototyped Parameters . . . . . . . Procedure Interface . . . . . . . . Using Arrays and Tables . . . . . . . . Arrays . . . . . . . . . . . . . Array Name and Index . . . . . . . The Essential Array Specifications . . . Coding a Run-Time Array . . . . . . Loading a Run-Time Array . . . . . Loading a Run-Time Array by Reading One Record from a File . . . . . . Loading a Run-Time Array by Reading Several Records from A File . . . . Loading an Array from Identical Externally-Described Fields . . . . Sequencing Run-Time Arrays . . . . Coding a Compile-Time Array . . . . Loading a Compile-Time Array . . . . Rules for Array Source Records . . . Coding a Prerun-Time Array . . . . . Example of Coding Arrays. . . . . . Loading a Prerun-Time Array. . . . . . . . . . . . . . 4-1 4-1 4-2 4-3 4-3 4-3 4-4 4-4 4-7
. 4-8 . 4-8 . 4-9 . 4-10 . 4-10 . 4-11 . 4-12 . . . . . . . . . . . . . . . . . . . . 4-13 4-13 4-14 4-14 4-15 4-15 4-15 4-16 4-16 4-16 4-16 4-27 4-27 4-28 4-30 4-31 4-32 4-32 4-32 4-32 4-33
. 4-33 . 4-34 . . . . . . . . 4-34 4-35 4-36 4-36 4-36 4-37 4-38 4-38
iv
Sequence Checking for Character Arrays Initializing Arrays . . . . . . . . . . Run-Time Arrays . . . . . . . . . . Compile-Time and Prerun-Time Arrays . . Defining Related Arrays . . . . . . . . Searching Arrays . . . . . . . . . . . Searching an Array Without an Index . . . Searching an Array Data Structure . . . . # Searching an Array with an Index . . . . Using Arrays . . . . . . . . . . . . Specifying an Array in Calculations. . . . Sorting Arrays . . . . . . . . . . . . Sorting using part of the array as a key . . Sorting an Array Data Structure . . . . . # Array Output . . . . . . . . . . . . Editing Entire Arrays . . . . . . . . Using Dynamically-Sized Arrays. . . . . . Tables . . . . . . . . . . . . . . LOOKUP with One Table . . . . . . . LOOKUP with Two Tables . . . . . . . Specifying the Table Element Found in a LOOKUP Operation . . . . . . . . . Data Types and Data Formats . . . . . . . Internal and External Formats . . . . . . Internal Format . . . . . . . . . . External Format . . . . . . . . . . Specifying an External Format for a Numeric Field . . . . . . . . . . Specifying an External Format for a Character, Graphic, or UCS-2 Field . . . Specifying an External Format for a Date-Time Field . . . . . . . . . Character Data Type . . . . . . . . . . Character Format . . . . . . . . . . Indicator Format . . . . . . . . . . Graphic Format . . . . . . . . . . UCS-2 Format . . . . . . . . . . . Variable-Length Character, Graphic and UCS-2 Formats . . . . . . . . . . Size of the Length-Prefix for a Varying Length Item . . . . . . . . . . Rules for Variable-Length Character, Graphic, and UCS-2 Formats . . . . . Using Variable-Length Fields . . . . . CVTOPT(*VARCHAR) and CVTOPT(*VARGRAPHIC) . . . . . . Conversion between Character, Graphic and UCS-2 Data . . . . . . . . . . . . CCSIDs of Data . . . . . . . . . Conversions . . . . . . . . . . Alternate Collating Sequence . . . . . . Changing the Collating Sequence . . . Using an External Collating Sequence Specifying an Alternate Collating Sequence in Your Source . . . . . . Formatting the Alternate Collating Sequence Records. . . . . . . . . Numeric Data Type . . . . . . . . . . Binary-Decimal Format . . . . . . . . Processing of a Program-Described Binary Input Field . . . . . . . .
4-38 4-39 4-39 4-39 4-39 4-41 4-41 4-42 4-42 4-43 4-43 4-44 4-44 4-45 4-45 4-45 4-45 4-46 4-47 4-47 4-48 4-48 4-49 4-49 4-49 4-50 4-50 4-51 4-51 4-51 4-52 4-52 4-53 4-54 4-55 4-55 4-57 4-59 4-62 4-62 4-63 4-63 4-63 4-63 4-64 4-64 4-65 4-65 4-65
Processing of an Externally Described Binary Input Field . . . . . . . . 4-66 Float Format . . . . . . . . . . . 4-66 External Display Representation of a Floating-Point Field . . . . . . . . 4-67 Integer Format. . . . . . . . . . . 4-67 Packed-Decimal Format. . . . . . . . 4-68 Determining the Digit Length of a Packed-Decimal Field . . . . . . . 4-68 Unsigned Format . . . . . . . . . . 4-69 Zoned-Decimal Format . . . . . . . . 4-70 Considerations for Using Numeric Formats 4-70 Guidelines for Choosing the Numeric Format for a Field . . . . . . . . 4-71 Representation of Numeric Formats . . . 4-71 Date Data Type . . . . . . . . . . . 4-73 Separators . . . . . . . . . . . . 4-75 Initialization . . . . . . . . . . . 4-75 Time Data Type . . . . . . . . . . . 4-75 Separators . . . . . . . . . . . . 4-76 Initialization . . . . . . . . . . . 4-76 *JOBRUN . . . . . . . . . . . . 4-77 Timestamp Data Type . . . . . . . . . 4-77 Separators . . . . . . . . . . . . 4-77 Initialization . . . . . . . . . . . 4-77 Object Data Type . . . . . . . . . . . 4-77 Where You Can Specify an Object Field . . 4-78 Basing Pointer Data Type . . . . . . . . 4-79 Setting a Basing Pointer . . . . . . . 4-80 Examples . . . . . . . . . . . . 4-81 Procedure Pointer Data Type . . . . . . . 4-85 Database Null Value Support . . . . . . . 4-86 User Controlled Support for Null-Capable Fields and Key Fields . . . . . . . . 4-87 Null-capable fields in externally-described data structures. . . 4-87 Input of Null-Capable Fields . . . . . 4-88 Output of Null-Capable Fields . . . . 4-88 Keyed Operations . . . . . . . . 4-89 Input-Only Support for Null-Capable Fields 4-92 ALWNULL(*NO) . . . . . . . . . . 4-92 Error Handling for Database Data Mapping Errors. . . . . . . . . . . . . . . 4-92 Editing Numeric Fields . . . . . . . . . . 4-92 Edit Codes . . . . . . . . . . . . . 4-93 Simple Edit Codes . . . . . . . . . 4-93 Combination Edit Codes . . . . . . . 4-93 User-Defined Edit Codes . . . . . . . 4-95 Editing Considerations . . . . . . . . 4-95 Summary of Edit Codes . . . . . . . 4-95 Edit Words . . . . . . . . . . . . . 4-98 How to Code an Edit Word . . . . . . 4-99 Parts of an Edit Word . . . . . . . . 4-99 Forming the Body of an Edit Word 4-100 Forming the Status of an Edit Word 4-102 Formatting the Expansion of an Edit Word . . . . . . . . . . . . 4-103 Summary of Coding Rules for Edit Words 4-103 Editing Externally Described Files . . . . . 4-103
Contents
Specifications . . . . . . . . . . . 5-1
About Specifications . . . . . . . . . . . 5-1 RPG IV Specification Types . . . . . . . . 5-1 Main Source Section Specifications . . . . 5-2 Subprocedure Specifications . . . . . . 5-3 Program Data . . . . . . . . . . . 5-3 Free-Form Statements . . . . . . . . . . 5-3 | Conditional Directives Within a Free-Form | Statement . . . . . . . . . . . . . 5-4 | Differences between fixed-form and free-form | to be aware of . . . . . . . . . . . 5-4 | Common Entries . . . . . . . . . . . 5-6 Syntax of Keywords . . . . . . . . . 5-6 Continuation Rules . . . . . . . . . 5-7 Control Specification Keyword Field . . . 5-9 File Description Specification Keyword Field . . . . . . . . . . . . . 5-9 Definition Specification Keyword Field . . 5-9 Calculation Specification Extended Factor-2 . . . . . . . . . . . . 5-10 Free-Form Specification . . . . . . . 5-10 Output Specification Constant/Editword Field . . . . . . . . . . . . . 5-11 Definition and Procedure Specification Name Field . . . . . . . . . . . 5-11 Control Specifications . . . . . . . . . . 5-12 Using a Data Area as a Control Specification 5-13 Free-Form Control Statement . . . . . . . 5-14 | Traditional Control-Specification Statement . . 5-15 Position 6 (Form Type) . . . . . . . . 5-15 Positions 7-80 (Keywords) . . . . . . . 5-15 Control-Specification Keywords . . . . . . 5-15 ALLOC(*STGMDL | *TERASPACE | # *SNGLVL) . . . . . . . . . . . . 5-16 # ACTGRP(*STGMDL | *NEW | *CALLER | 'activation-group-name') . . . . . . . 5-16 ALTSEQ{(*NONE | *SRC | *EXT)} . . . . 5-17 ALWNULL(*NO | *INPUTONLY | *USRCTL) . . . . . . . . . . . . 5-17 AUT(*LIBRCRTAUT | *ALL | *CHANGE | *USE | *EXCLUDE | 'authorization-listname') . . . . . . . . . . . . . 5-18 BNDDIR('binding-directory-name' {:'binding-directory-name'...}) . . . . . . 5-18 CCSID(*GRAPH : parameter | *UCS2 : number | *CHAR : *JOBRUN) . . . . . 5-19 CCSIDCVT(*EXCP | *LIST) . . . . . . 5-19 | COPYNEST(number) . . . . . . . . 5-21 COPYRIGHT('copyright string') . . . . . 5-21 CURSYM('sym') . . . . . . . . . . 5-21 CVTOPT(*{NO}DATETIME *{NO}GRAPHIC *{NO}VARCHAR *{NO}VARGRAPHIC) . . 5-22 DATEDIT(fmt{separator}) . . . . . . . 5-23 DATFMT(fmt{separator}) . . . . . . . 5-23 DEBUG{(*INPUT | *DUMP | *XMLSAX | *NO | *YES)} . . . . . . . . . . . 5-23 DECEDIT(*JOBRUN | 'value') . . . . . 5-24 DECPREC(30|31|63) . . . . . . . . 5-24 DFTACTGRP(*YES | *NO) . . . . . . 5-25 DFTNAME(rpg_name) . . . . . . . . 5-26 ENBPFRCOL(*PEP | *ENTRYEXIT | *FULL) 5-26
EXPROPTS(*MAXDIGITS | *RESDECPOS) EXTBININT{(*NO | *YES)} . . . . . . FIXNBR(*{NO}ZONED *{NO}INPUTPACKED) . . . . . . . . FLTDIV{(*NO | *YES)} . . . . . . . . FORMSALIGN{(*NO | *YES)} . . . . . FTRANS{(*NONE | *SRC)} . . . . . . GENLVL(number) . . . . . . . . . INDENT(*NONE | 'character-value') . . . INTPREC(10 | 20) . . . . . . . . . LANGID(*JOBRUN | *JOB | 'language-identifier') . . . . . . . . . MAIN(main_procedure_name) . . . . . NOMAIN . . . . . . . . . . . . OPENOPT (*NOINZOFL | *INZOFL) . . . OPTIMIZE(*NONE | *BASIC | *FULL) . . OPTION(*{NO}XREF *{NO}GEN *{NO}SECLVL *{NO}SHOWCPY *{NO}EXPDDS *{NO}EXT *{NO}SHOWSKP) *{NO}SRCSTMT) *{NO}DEBUGIO) *{NO}UNREF . . . . . . . . . . . PGMINFO(*PCML | *NO { : *MODULE } ) Examples . . . . . . . . . . . PRFDTA(*NOCOL | *COL) . . . . . . SRTSEQ(*HEX | *JOB | *JOBRUN | *LANGIDUNQ | *LANGIDSHR | 'sort-table-name') . . . . . . . . . . STGMDL(*INHERIT | *SNGLVL | # *TERASPACE) . . . . . . . . . . . # TEXT(*SRCMBRTXT | *BLANK | 'description') . . . . . . . . . . . THREAD(*CONCURRENT | *SERIALIZE) THREAD(*CONCURRENT) . . . . . THREAD(*SERIALIZE) . . . . . . . General thread considerations . . . . TIMFMT(fmt{separator}) . . . . . . . TRUNCNBR(*YES | *NO) . . . . . . . USRPRF(*USER | *OWNER) . . . . . . VALIDATE(*NODATETIME) . . . . . . | File Description Specifications . . . . . . . Free-Form File Definition Statement . . . . | Equivalent Free-form Coding for Fixed-Form | File Entries . . . . . . . . . . . . | Device-type Keywords . . . . . . . . | Defining the File Usage in Free-Form . . . | Traditional File Description Specification Statement . . . . . . . . . . . . . File-Description Keyword Continuation Line Position 6 (Form Type) . . . . . . . . Positions 7-16 (File Name) . . . . . . . Program-Described File . . . . . . . Externally-Described File . . . . . . Position 17 (File Type) . . . . . . . . Input Files . . . . . . . . . . . Output Files . . . . . . . . . . Update Files . . . . . . . . . . Combined Files . . . . . . . . . Position 18 (File Designation) . . . . . . Primary File . . . . . . . . . . Secondary File . . . . . . . . . . Record Address File (RAF). . . . . .
5-26 5-26 5-27 5-27 5-27 5-28 5-28 5-28 5-28 5-28 5-29 5-30 5-31 5-31
5-33 5-33 5-34 5-34 5-35 5-35 5-35 5-35 5-36 5-36 5-36 5-37 5-38 5-39 5-39 5-39 5-40 5-40 5-41 5-41 5-41 5-41 5-42 5-42 5-42 5-42 5-42 5-42 5-42 5-43 5-43
vi
| |
Array or Table File . . . . . . . Full Procedural File . . . . . . . Position 19 (End of File) . . . . . . Position 20 (File Addition) . . . . . . Position 21 (Sequence) . . . . . . . Position 22 (File Format) . . . . . . Positions 23-27 (Record Length) . . . . Position 28 (Limits Processing) . . . . Positions 29-33 (Length of Key or Record Address). . . . . . . . . . . . Position 34 (Record Address Type) . . . Blank=Non-keyed Processing . . . . A=Character Keys . . . . . . . P=Packed Keys . . . . . . . . G=Graphic Keys . . . . . . . . K=Key . . . . . . . . . . . D=Date Keys . . . . . . . . . T=Time Keys . . . . . . . . . Z=Timestamp Keys . . . . . . . F=Float Keys . . . . . . . . . Position 35 (File Organization) . . . . Blank=Non-keyed Program-Described File . . . . . . . . . . . . I=Indexed File . . . . . . . . . T=Record Address File . . . . . . Positions 36-42 (Device). . . . . . . File device types . . . . . . . . Position 43 (Reserved) . . . . . . . Positions 44-80 (Keywords) . . . . . File-Description Keywords. . . . . . . ALIAS . . . . . . . . . . . . BLOCK(*YES |*NO) . . . . . . . . COMMIT{(rpg_name)} . . . . . . . DATFMT(format{separator}) . . . . . DEVID(fieldname) . . . . . . . . DISK{(*EXT | record-length)} . . . . . EXTDESC(external-filename) . . . . . EXTFILE(filename | *EXTDESC). . . . EXTIND(*INUx) . . . . . . . . . EXTMBR(membername) . . . . . . FORMLEN(number) . . . . . . . . FORMOFL(number) . . . . . . . . HANDLER(program-or-procedure { : communication-area)}) . . . . . . . IGNORE(recformat{:recformat...}) . . . INCLUDE(recformat{:recformat...}) . . . INDDS(data_structure_name) . . . . . INFDS(DSname) . . . . . . . . . INFSR(SUBRname) . . . . . . . . KEYED{(*CHAR : key-length)} . . . . KEYLOC(number) . . . . . . . . LIKEFILE(parent-filename) . . . . . Rules for the LIKEFILE keyword: . . MAXDEV(*ONLY | *FILE) . . . . . OFLIND(indicator) . . . . . . . . PASS(*NOIND) . . . . . . . . . PGMNAME(program_name) . . . . . PLIST(Plist_name) . . . . . . . . PREFIX(prefix{:nbr_of_char_replaced}) . . PRINTER{(*EXT | record-length)} . . . PRTCTL(data_struct{:*COMPAT}) . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5-43 5-43 5-43 5-44 5-44 5-45 5-45 5-46 5-46 5-47 5-47 5-47 5-48 5-48 5-48 5-48 5-48 5-48 5-48 5-48 5-49 5-49 5-49 5-49 5-49 5-50 5-50 5-50 5-50 5-51 5-52 5-52 5-52 5-53 5-53 5-54 5-55 5-56 5-56 5-56 5-56 5-58 5-58 5-59 5-59 5-59 5-59 5-60 5-60 5-60 5-63 5-64 5-64 5-64 5-64 5-65 5-66 5-67
| |
| | | | | | | | | | | | | | | | | | | | | | | | | |
Extended Length PRTCTL Data Structure *COMPAT PRTCTL Data Structure . . . QUALIFIED . . . . . . . . . . . Rules for the QUALIFIED keyword: . . RAFDATA(filename) . . . . . . . . . RECNO(fieldname) . . . . . . . . . RENAME(Ext_format:Int_format) . . . . SAVEDS(DSname) . . . . . . . . . SAVEIND(number) . . . . . . . . . SEQ{(*EXT | record-length)} . . . . . . SFILE(recformat:rrnfield) . . . . . . . SLN(number) . . . . . . . . . . . SPECIAL{(*EXT | record-length)} . . . . STATIC . . . . . . . . . . . . . Rules for the STATIC keyword: . . . . TEMPLATE . . . . . . . . . . . . Rules for the TEMPLATE keyword: . . . TIMFMT(format{separator}) . . . . . . USAGE(*INPUT *OUTPUT *UPDATE *DELETE) . . . . . . . . . . . . USROPN . . . . . . . . . . . . WORKSTN{(*EXT | record-length)}. . . . File Types and Processing Methods . . . . . Definition Specifications . . . . . . . . . Free-Form Definition Statement . . . . . . Data-type Keywords . . . . . . . . . Keyword differences between fixed form and free form definitions . . . . . . . Free-Form Named Constant Definition. . . Free-Form Standalone Field Definition . . . Equivalent Free-form Coding for Standalone Field Entries . . . . . . Free-Form Data Structure Definition . . . Equivalent Free-form Coding for Data Structure Entries . . . . . . . . . Free-Form Subfield Definition . . . . . Equivalent Free-form Coding for Subfield Entries . . . . . . . . . . . . Free-Form Prototype Definition . . . . . Equivalent Free-form Coding for Prototype Entries . . . . . . . . . Free-Form Procedure Interface Definition Equivalent Free-form Coding for Procedure Interface Entries . . . . . Free-Form Parameter Definition . . . . . Equivalent Free-form Coding for Parameter Entries. . . . . . . . . Traditional Definition Specification Statement Definition Specification Keyword Continuation Line . . . . . . . . . Definition Specification Continued Name Line . . . . . . . . . . . . . . Position 6 (Form Type) . . . . . . . . Positions 7-21 (Name) . . . . . . . . Position 22 (External Description) . . . . Position 23 (Type of Data Structure) . . . Positions 24-25 (Definition Type). . . . . Positions 26-32 (From Position) . . . . . Positions 33-39 (To Position / Length) . . . Position 40 (Internal Data Type) . . . . . Positions 41-42 (Decimal Positions) . . . .
Contents
5-67 5-67 5-67 5-68 5-68 5-68 5-69 5-69 5-69 5-69 5-70 5-70 5-70 5-71 5-71 5-71 5-72 5-72 5-72 5-72 5-73 5-73 5-74 5-74 5-76 5-77 5-77 5-78 5-78 5-78 5-81 5-82 5-82 5-83 5-84 5-84 5-86 5-86 5-86 5-86 5-87 5-87 5-87 5-88 5-88 5-89 5-89 5-90 5-90 5-91 5-92
vii
| |
| | | | |
| | | | | |
Position 43 (Reserved) . . . . . . . . 5-92 Positions 44-80 (Keywords) . . . . . . 5-92 Definition-Specification Keywords . . . . . 5-92 ALIAS . . . . . . . . . . . . . 5-93 ALIGN . . . . . . . . . . . . . 5-94 ALT(array_name) . . . . . . . . . . 5-94 ALTSEQ(*NONE) . . . . . . . . . . 5-95 ASCEND . . . . . . . . . . . . 5-95 BASED(basing_pointer_name) . . . . . 5-95 BINDEC(digits {: decimal-positions}) . . . 5-96 CCSID(number | *DFT) . . . . . . . 5-96 CHAR(length) . . . . . . . . . . . 5-96 CLASS(*JAVA:class-name) . . . . . . . 5-97 CONST{(constant)} . . . . . . . . . 5-97 CTDATA . . . . . . . . . . . . 5-98 DATE{(format{separator})} . . . . . . . 5-98 DATFMT(format{separator}) . . . . . . 5-98 DESCEND . . . . . . . . . . . . 5-98 DIM(numeric_constant) . . . . . . . . 5-99 DTAARA keyword . . . . . . . . . 5-99 Free-form DTAARA keyword for a field or subfield. . . . . . . . . . . 5-100 Free-form DTAARA keyword for a data structure . . . . . . . . . . . 5-101 Fixed-form DTAARA keyword . . . . 5-102 EXPORT{(external_name)} . . . . . . 5-102 EXT . . . . . . . . . . . . . . 5-103 EXTFLD{(field_name)} . . . . . . . . 5-103 EXTFMT(code) . . . . . . . . . . 5-104 EXTNAME(file-name{:format-name}{:*ALL| *INPUT|*OUTPUT|*KEY}) . . . . . . 5-105 EXTPGM{(name)} . . . . . . . . . 5-106 EXTPROC({*CL|*CWIDEN|*CNOWIDEN| {*JAVA:class-name:}}name) . . . . . . 5-106 Specifying *DCLCASE as the External Name . . . . . . . . . . . . 5-111 FLOAT(bytes). . . . . . . . . . . 5-111 FROMFILE(file_name) . . . . . . . . 5-112 GRAPH(length) . . . . . . . . . . 5-112 IMPORT{(external_name)} . . . . . . 5-112 INT(digits). . . . . . . . . . . . 5-113 IND . . . . . . . . . . . . . . 5-113 INZ{(initial value)} . . . . . . . . . 5-114 LEN(length) . . . . . . . . . . . 5-115 Rules for the LEN keyword: . . . . . 5-115 LIKE(name {: length-adjustment}) . . . . 5-116 LIKE(object-name) . . . . . . . . 5-117 LIKEDS(data_structure_name) . . . . . 5-117 LIKEFILE(filename). . . . . . . . . 5-119 Rules for the LIKEFILE keyword for prototyped parameters: . . . . . . 5-119 LIKEREC(intrecname{:*ALL|*INPUT|*OUTPUT |*KEY}) . . . . . . . . . . . . 5-120 NOOPT . . . . . . . . . . . . 5-121 OBJECT{(*JAVA:class-name)}. . . . . . 5-122 OCCURS(numeric_constant) . . . . . . 5-122 OPDESC . . . . . . . . . . . . 5-123 OPTIONS(*NOPASS *OMIT *VARSIZE *STRING *TRIM *RIGHTADJ *NULLIND) . 5-123 OVERLAY(name{:start_pos | *NEXT}) 5-134 PACKED(digits {: decimal-positions}) . . . 5-136
PACKEVEN . . . . . . . . . . PERRCD(numeric_constant) . . . . . POINTER{(*PROC)} . . . . . . . | POS(starting-position) . . . . . . . | PREFIX(prefix{:nbr_of_char_replaced}) PROCPTR . . . . . . . . . . . PSDS . . . . . . . . . . . . | QUALIFIED . . . . . . . . . . RTNPARM . . . . . . . . . . # STATIC{(*ALLTHREAD)} . . . . . . Additional Considerations for STATIC(*ALLTHREAD) . . . . . TEMPLATE . . . . . . . . . . Rules for the TEMPLATE keyword for Definition specifications: . . . . . TIME{(format{separator})} . . . . . | TIMESTAMP . . . . . . . . . . | TIMFMT(format{separator}) . . . . . TOFILE(file_name) . . . . . . . . UCS2(length) . . . . . . . . . . | UNS(digits) . . . . . . . . . . | VALUE . . . . . . . . . . . . VARCHAR(length {:2 | 4}) . . . . . | VARGRAPH(length {:2 | 4}) . . . . . | VARUCS2(length {:2 | 4}). . . . . . | VARYING{(2 | 4)} . . . . . . . . ZONED(digits {: decimal-positions}) . . | Summary According to Definition Specification Type . . . . . . . . . Input Specifications. . . . . . . . . . Input Specification Statement . . . . . Program Described . . . . . . . . Externally Described . . . . . . . Program Described Files . . . . . . . Position 6 (Form Type) . . . . . . Record Identification Entries. . . . . . Positions 7-16 (File Name) . . . . . Positions 16-18 (Logical Relationship). . Positions 17-18 (Sequence) . . . . . Alphabetic Entries . . . . . . . Numeric Entries . . . . . . . . Position 19 (Number) . . . . . . . Position 20 (Option) . . . . . . . Positions 21-22 (Record Identifying Indicator, or **) . . . . . . . . . Indicators . . . . . . . . . . Lookahead Fields . . . . . . . Positions 23-46 (Record Identification Codes) . . . . . . . . . . . . Positions 23-27, 31-35, and 39-43 (Position) . . . . . . . . . . Positions 28, 36, and 44 (Not) . . . Positions 29, 37, and 45 (Code Part) Positions 30, 38, and 46 (Character) AND Relationship . . . . . . . OR Relationship . . . . . . . . Field Description Entries . . . . . . . Position 6 (Form Type) . . . . . . Positions 7-30 (Reserved) . . . . . . Positions 31-34 (Data Attributes) . . . Position 35 (Date/Time Separator) . . .
. . . . . . . . .
5-136 5-137 5-137 5-137 5-138 5-139 5-139 5-139 5-139 5-143
. 5-144 . 5-144 . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-144 5-145 5-145 5-145 5-146 5-146 5-146 5-147 5-147 5-147 5-148 5-148 5-149 5-149 5-153 5-154 5-154 5-154 5-154 5-154 5-154 5-155 5-155 5-155 5-155 5-155 5-156 5-156
. 5-156 . 5-156 . 5-157 . 5-157 . 5-158 . 5-158 5-158 5-159 . 5-159 . 5-159 . 5-159 . 5-159 . 5-159 . 5-159 . 5-160
viii
Position 36 (Data Format). . . . . . . Positions 37-46 (Field Location) . . . . . Positions 47-48 (Decimal Positions) . . . Positions 49-62 (Field Name) . . . . . Positions 63-64 (Control Level) . . . . . Positions 65-66 (Matching Fields) . . . . Positions 67-68 (Field Record Relation) Positions 69-74 (Field Indicators) . . . . Externally Described Files . . . . . . . Position 6 (Form Type) . . . . . . . Record Identification Entries. . . . . . . Positions 7-16 (Record Name) . . . . . Positions 17-20 (Reserved) . . . . . . Positions 21-22 (Record Identifying Indicator) . . . . . . . . . . . . Positions 23-80 (Reserved) . . . . . . Field Description Entries . . . . . . . . Positions 7-20 (Reserved) . . . . . . . Positions 21-30 (External Field Name) . . Positions 31-48 (Reserved) . . . . . . Positions 49-62 (Field Name) . . . . . Positions 63-64 (Control Level) . . . . . Positions 65-66 (Matching Fields) . . . . Positions 67-68 (Reserved) . . . . . . Positions 69-74 (Field Indicators) . . . . Positions 75-80 (Reserved) . . . . . . Calculation Specifications. . . . . . . . . Traditional Syntax . . . . . . . . . . Calculation Specification Extended Factor-2 Continuation Line . . . . . . . . . Position 6 (Form Type) . . . . . . . Positions 7-8 (Control Level). . . . . . Control Level Indicators . . . . . . Last Record Indicator . . . . . . . Subroutine Identifier . . . . . . . AND/OR Lines Identifier . . . . . Positions 9-11 (Indicators) . . . . . . Positions 12-25 (Factor 1) . . . . . . . Positions 26-35 (Operation and Extender) Operation Extender. . . . . . . . Positions 36-49 (Factor 2) . . . . . . . Positions 50-63 (Result Field) . . . . . Positions 64-68 (Field Length) . . . . . Positions 69-70 (Decimal Positions) . . . Positions 71-76 (Resulting Indicators) . . . Extended Factor 2 Syntax . . . . . . . . Positions 7-8 (Control Level). . . . . . Positions 9-11 (Indicators) . . . . . . Positions 12-25 (Factor 1) . . . . . . . Positions 26-35 (Operation and Extender) Operation Extender. . . . . . . . Positions 36-80 (Extended Factor 2) . . . Free-Form Calculation Statement . . . . . Positions 8-80 (Free-form Operations). . . Output Specifications . . . . . . . . . . Output Specification Statement . . . . . . Program Described . . . . . . . . . Externally Described . . . . . . . . Program Described Files . . . . . . . . Position 6 (Form Type) . . . . . . . Record Identification and Control Entries
5-160 5-160 5-161 5-161 5-162 5-162 5-163 5-163 5-164 5-164 5-164 5-164 5-164 5-164 5-164 5-164 5-165 5-165 5-165 5-165 5-165 5-165 5-165 5-166 5-166 5-166 5-167 5-167 5-167 5-167 5-168 5-168 5-168 5-168 5-169 5-169 5-169 5-169 5-170 5-170 5-171 5-171 5-171 5-172 5-172 5-172 5-172 5-172 5-172 5-173 5-173 5-175 5-175 5-175 5-175 5-176 5-176 5-176 5-176
Positions 7-16 (File Name) . . . . . . Positions 16-18 ( Logical Relationship) Position 17 (Type) . . . . . . . . . Positions 18-20 (Record Addition/Deletion) Position 18 (Fetch Overflow/Release) . . . Fetch Overflow . . . . . . . . . Release . . . . . . . . . . . . Positions 21-29 (Output Conditioning Indicators) . . . . . . . . . . . . Positions 30-39 (EXCEPT Name) . . . . Positions 40-51 (Space and Skip) . . . . Positions 40-42 (Space Before) . . . . . Positions 43-45 (Space After). . . . . . Positions 46-48 (Skip Before). . . . . . Positions 49-51 (Skip After) . . . . . . Field Description and Control Entries. . . . Positions 21-29 (Output Indicators) . . . Positions 30-43 (Field Name) . . . . . Field Names, Blanks, Tables and Arrays PAGE, PAGE1-PAGE7 . . . . . . . *PLACE . . . . . . . . . . . User Date Reserved Words . . . . . *IN, *INxx, *IN(xx) . . . . . . . . Position 44 (Edit Codes) . . . . . . . Position 45 (Blank After) . . . . . . . Positions 47-51 (End Position) . . . . . Position 52 (Data Format). . . . . . . Positions 53-80 (Constant, Edit Word, Data Attributes, Format Name) . . . . . . Constants . . . . . . . . . . . Edit Words . . . . . . . . . . Data Attributes . . . . . . . . . Record Format Name . . . . . . . Externally Described Files . . . . . . . Position 6 (Form Type) . . . . . . . Record Identification and Control Entries Positions 7-16 (Record Name) . . . . . Positions 16-18 ( Logical Relationship) Position 17 (Type) . . . . . . . . . Position 18 (Release) . . . . . . . . Positions 18-20 (Record Addition) . . . . Positions 21-29 (Output Indicators) . . . Positions 30-39 (EXCEPT Name) . . . . Field Description and Control Entries. . . . Positions 21-29 (Output Indicators) . . . Positions 30-43 (Field Name) . . . . . Position 45 (Blank After) . . . . . . . Procedure Specifications . . . . . . . . . Free-Form Procedure Statement. . . . . . Traditional Procedure Specification Statement Procedure Specification Keyword Continuation Line . . . . . . . . . Procedure Specification Continued Name Line . . . . . . . . . . . . . . Position 6 (Form Type) . . . . . . . Positions 7-21 (Name) . . . . . . . . Position 24 (Begin/End Procedure) . . . Positions 44-80 (Keywords) . . . . . . Procedure-Specification Keywords . . . . . EXPORT . . . . . . . . . . . . SERIALIZE . . . . . . . . . . .
Contents
5-176 5-176 5-177 5-177 5-178 5-178 5-179 5-179 5-180 5-180 5-181 5-181 5-181 5-181 5-181 5-181 5-181 5-182 5-182 5-182 5-182 5-182 5-182 5-183 5-183 5-184 5-185 5-185 5-186 5-186 5-186 5-186 5-186 5-186 5-186 5-186 5-187 5-187 5-187 5-187 5-187 5-187 5-187 5-187 5-188 5-188 5-189 5-190 5-190 5-190 5-191 5-191 5-191 5-192 5-192 5-192 5-192
ix
For the ** operator: . . . . . . . . 6-58 Precision Rules for Numeric Operations . . . 6-58 Using the Default Precision Rules . . . . 6-59 Precision of Intermediate Results . . . . 6-60 Example of Default Precision Rules . . . . 6-60 Using the "Result Decimal Position" Precision Rules . . . . . . . . . . 6-62 Example of "Result Decimal Position" Precision Rules . . . . . . . . . . 6-62 Short Circuit Evaluation . . . . . . . . 6-63 Order of Evaluation . . . . . . . . . . 6-64 Built-in Functions. . . . . . . . . . . . 6-64 %ABS (Absolute Value of Expression) . . . . 6-64 %ADDR (Get Address of Variable) . . . . . 6-65 %ALLOC (Allocate Storage) . . . . . . . 6-67 %BITAND (Bitwise AND Operation) . . . . 6-67 %BITNOT (Invert Bits) . . . . . . . . . 6-68 %BITOR (Bitwise OR Operation). . . . . . 6-68 %BITXOR (Bitwise Exclusive-OR Operation) 6-69 Examples of Bit Operations . . . . . . 6-70 %CHAR (Convert to Character Data) . . . . 6-72 %CHECK (Check Characters) . . . . . . . 6-73 %CHECKR (Check Reverse) . . . . . . . 6-75 %DATE (Convert to Date) . . . . . . . . 6-76 %DAYS (Number of Days). . . . . . . . 6-77 %DEC (Convert to Packed Decimal Format) 6-77 Numeric or character expression . . . . . 6-77 Date, time or timestamp expression. . . . 6-77 %DECH (Convert to Packed Decimal Format with Half Adjust) . . . . . . . . . . . 6-78 %DECH Examples . . . . . . . . . 6-79 %DECPOS (Get Number of Decimal Positions) 6-79 %DIFF (Difference Between Two Date, Time, or Timestamp Values) . . . . . . . . . . 6-80 %DIV (Return Integer Portion of Quotient) . . 6-82 %EDITC (Edit Value Using an Editcode) . . . 6-82 %EDITFLT (Convert to Float External Representation) . . . . . . . . . . . 6-84 %EDITW (Edit Value Using an Editword) . . 6-85 %ELEM (Get Number of Elements) . . . . . 6-85 %EOF (Return End or Beginning of File Condition) . . . . . . . . . . . . . 6-86 %EQUAL (Return Exact Match Condition) . . 6-87 %ERROR (Return Error Condition) . . . . . 6-89 %FIELDS (Fields to update) . . . . . . . 6-89 %FLOAT (Convert to Floating Format) . . . 6-90 %FOUND (Return Found Condition) . . . . 6-90 %GRAPH (Convert to Graphic Value) . . . . 6-92 %HANDLER (handlingProcedure : communicationArea ) . . . . . . . . . 6-93 %HOURS (Number of Hours) . . . . . . 6-96 %INT (Convert to Integer Format) . . . . . 6-97 %INTH (Convert to Integer Format with Half Adjust) . . . . . . . . . . . 6-97 %KDS (Search Arguments in Data Structure) 6-98 %LEN (Get or Set Length) . . . . . . . . 6-98 %LEN Used for its Value . . . . . . . 6-99 %LEN Used to Set the Length of Variable-Length Fields . . . . . . . . 6-100 %LEN Used to Get the Maximum Length # of Varying-Length Expressions . . . . . 6-100 #
%LOOKUPxx (Look Up an Array Element) Sequenced arrays that are not in the correct sequence . . . . . . . . . . . . %MINUTES (Number of Minutes) . . . . . %MONTHS (Number of Months) . . . . . %MSECONDS (Number of Microseconds) %NULLIND (Query or Set Null Indicator) %OCCUR (Set/Get Occurrence of a Data Structure) . . . . . . . . . . . . . %OPEN (Return File Open Condition) . . . %PADDR (Get Procedure Address) . . . . %PADDR Used with a Prototype . . . . %PARMS (Return Number of Parameters) %PARMNUM (Return Parameter Number) # %REALLOC (Reallocate Storage) . . . . . %REM (Return Integer Remainder) . . . . %REPLACE (Replace Character String) . . . %SCAN (Scan for Characters) . . . . . . %SCANRPL (Scan and Replace Characters) # %SECONDS (Number of Seconds) . . . . . %SHTDN (Shut Down) . . . . . . . . %SIZE (Get Size in Bytes). . . . . . . . %SQRT (Square Root of Expression) . . . . %STATUS (Return File or Program Status) %STR (Get or Store Null-Terminated String) %STR Used to Get Null-Terminated String %STR Used to Store Null-Terminated String %SUBARR (Set/Get Portion of an Array) %SUBDT (Extract a Portion of a Date, Time, or Timestamp) . . . . . . . . . . . . %SUBST (Get Substring) . . . . . . . . %SUBST Used for its Value . . . . . . %SUBST Used as the Result of an Assignment . . . . . . . . . . . %THIS (Return Class Instance for Native Method) . . . . . . . . . . . . . %TIME (Convert to Time) . . . . . . . %TIMESTAMP (Convert to Timestamp) . . . %TLOOKUPxx (Look Up a Table Element) %TRIM (Trim Characters at Edges) . . . . %TRIML (Trim Leading Characters) . . . . %TRIMR (Trim Trailing Characters) . . . . %UCS2 (Convert to UCS-2 Value) . . . . . %UNS (Convert to Unsigned Format) . . . %UNSH (Convert to Unsigned Format with Half Adjust) . . . . . . . . . . . %XFOOT (Sum Array Expression Elements) %XLATE (Translate) . . . . . . . . . %XML (xmlDocument {:options}) . . . . . %YEARS (Number of Years) . . . . . . . Operation Codes . . . . . . . . . . . ACQ (Acquire) . . . . . . . . . . . ADD (Add) . . . . . . . . . . . . ADDDUR (Add Duration) . . . . . . . ALLOC (Allocate Storage) . . . . . . . ANDxx (And) . . . . . . . . . . . BEGSR (Beginning of Subroutine) . . . . . BITOFF (Set Bits Off) . . . . . . . . . BITON (Set Bits On) . . . . . . . . . CABxx (Compare and Branch) . . . . . . CALL (Call a Program) . . . . . . . .
6-101 6-104 6-104 6-104 6-105 6-105 6-106 6-106 6-107 6-108 6-109 6-111 6-112 6-113 6-114 6-115 6-116 6-118 6-118 6-119 6-120 6-121 6-123 6-124 6-125 6-125 6-128 6-129 6-129 6-130 6-130 6-131 6-132 6-132 6-133 6-134 6-135 6-136 6-137 6-137 6-138 6-138 6-139 6-140 6-140 6-140 6-141 6-141 6-143 6-144 6-145 6-145 6-146 6-149 6-150
CALLB (Call a Bound Procedure) . . . . . CALLP (Call a Prototyped Procedure or Program) . . . . . . . . . . . . . CASxx (Conditionally Invoke Subroutine) CAT (Concatenate Two Strings). . . . . . CHAIN (Random Retrieval from a File) . . . CHECK (Check Characters) . . . . . . . CHECKR (Check Reverse) . . . . . . . CLEAR (Clear) . . . . . . . . . . . Clearing Variables . . . . . . . . . Clearing Record Formats . . . . . . . CLEAR Examples . . . . . . . . . CLOSE (Close Files) . . . . . . . . . COMMIT (Commit) . . . . . . . . . COMP (Compare) . . . . . . . . . . DEALLOC (Free Storage) . . . . . . . . DEFINE (Field Definition) . . . . . . . *LIKE DEFINE . . . . . . . . . . *DTAARA DEFINE . . . . . . . . . DELETE (Delete Record) . . . . . . . . DIV (Divide) . . . . . . . . . . . . DO (Do) . . . . . . . . . . . . . DOU (Do Until) . . . . . . . . . . . DOUxx (Do Until) . . . . . . . . . . DOW (Do While) . . . . . . . . . . DOWxx (Do While). . . . . . . . . . DSPLY (Display Message) . . . . . . . DUMP (Program Dump) . . . . . . . . ELSE (Else) . . . . . . . . . . . . ELSEIF (Else If) . . . . . . . . . . . ENDyy (End a Structured Group) . . . . . ENDSR (End of Subroutine) . . . . . . . EVAL (Evaluate expression) . . . . . . . EVALR (Evaluate expression, right adjust) EVAL-CORR (Assign corresponding subfields) Examples of the EVAL-CORR operation EXCEPT (Calculation Time Output) . . . . EXFMT (Write/Then Read Format) . . . . EXSR (Invoke Subroutine) . . . . . . . EXTRCT (Extract Date/Time/Timestamp) FEOD (Force End of Data) . . . . . . . FOR (For) . . . . . . . . . . . . . FORCE (Force a Certain File to Be Read Next Cycle) . . . . . . . . . . . . . . GOTO (Go To) . . . . . . . . . . . IF (If) . . . . . . . . . . . . . . IFxx (If). . . . . . . . . . . . . . IN (Retrieve a Data Area). . . . . . . . ITER (Iterate) . . . . . . . . . . . . KFLD (Define Parts of a Key) . . . . . . KLIST (Define a Composite Key) . . . . . LEAVE (Leave a Do/For Group) . . . . . LEAVESR (Leave a Subroutine) . . . . . . LOOKUP (Look Up a Table or Array Element) MHHZO (Move High to High Zone) . . . . MHLZO (Move High to Low Zone) . . . . MLHZO (Move Low to High Zone) . . . . MLLZO (Move Low to Low Zone) . . . . MONITOR (Begin a Monitor Group) . . . . MOVE (Move) . . . . . . . . . . . MOVEA (Move Array). . . . . . . . .
Contents
6-151 6-152 6-156 6-157 6-159 6-162 6-164 6-166 6-167 6-167 6-168 6-170 6-170 6-171 6-172 6-173 6-174 6-175 6-176 6-177 6-178 6-180 6-180 6-182 6-183 6-185 6-187 6-188 6-189 6-189 6-190 6-191 6-193 6-194 6-197 6-200 6-201 6-203 6-203 6-205 6-206 6-208 6-209 6-210 6-211 6-212 6-214 6-215 6-216 6-218 6-219 6-220 6-223 6-223 6-224 6-224 6-224 6-226 6-239
xi
Character, graphic, and UCS-2 MOVEA Operations . . . . . . . . . Numeric MOVEA Operations . . . General MOVEA Operations. . . . MOVEL (Move Left) . . . . . . . MULT (Multiply) . . . . . . . . MVR (Move Remainder) . . . . . . NEXT (Next) . . . . . . . . . . OCCUR (Set/Get Occurrence of a Data Structure) . . . . . . . . . . . ON-ERROR (On Error) . . . . . . OPEN (Open File for Processing) . . . ORxx (Or) . . . . . . . . . . . OTHER (Otherwise Select) . . . . . OUT (Write a Data Area) . . . . . . PARM (Identify Parameters) . . . . . PLIST (Identify a Parameter List) . . . POST (Post) . . . . . . . . . . READ (Read a Record) . . . . . . READC (Read Next Changed Record) . READE (Read Equal Key) . . . . . READP (Read Prior Record) . . . . . READPE (Read Prior Equal) . . . . . REALLOC (Reallocate Storage with New Length) . . . . . . . . . . . . REL (Release). . . . . . . . . . RESET (Reset) . . . . . . . . . Resetting Variables . . . . . . . Resetting Record Formats. . . . . Additional Considerations . . . . RESET Examples . . . . . . . RETURN (Return to Caller) . . . . . ROLBK (Roll Back) . . . . . . . . SCAN (Scan String). . . . . . . . SELECT (Begin a Select Group) . . . . SETGT (Set Greater Than) . . . . . SETLL (Set Lower Limit) . . . . . . SETOFF (Set Indicator Off) . . . . . SETON (Set Indicator On) . . . . . SHTDN (Shut Down) . . . . . . . SORTA (Sort an Array) . . . . . . SQRT (Square Root) . . . . . . . SUB (Subtract) . . . . . . . . . SUBDUR (Subtract Duration) . . . . Subtract a duration . . . . . . . Calculate a duration . . . . . . Possible error situations . . . . . SUBDUR Examples . . . . . . . SUBST (Substring) . . . . . . . . TAG (Tag) . . . . . . . . . . . TEST (Test Date/Time/Timestamp) . . TESTB (Test Bit) . . . . . . . . . TESTN (Test Numeric). . . . . . . TESTZ (Test Zone) . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6-240 6-240 6-240 6-245 6-254 6-255 6-255 6-256 6-260 6-261 6-262 6-263 6-264 6-265 6-267 6-268 6-270 6-272 6-273 6-276 6-277 6-280 6-281 6-282 6-282 6-283 6-283 6-284 6-288 6-291 6-292 6-294 6-295 6-298 6-301 6-302 6-302 6-303 6-307 6-308 6-308 6-309 6-310 6-310 6-311 6-311 6-313 6-314 6-316 6-318 6-319
# # | |
TIME (Retrieve Time and Date). . . . . . UNLOCK (Unlock a Data Area or Release a Record) . . . . . . . . . . . . . . Unlocking data areas . . . . . . . . Releasing record locks . . . . . . . . UPDATE (Modify Existing Record) . . . . WHEN (When True Then Select) . . . . . WHENxx (When True Then Select) . . . . WRITE (Create New Records) . . . . . . XFOOT (Summing the Elements of an Array) XLATE (Translate) . . . . . . . . . . XML-INTO (Parse an XML Document into a Variable) . . . . . . . . . . . . . %XML options for the XML-INTO operation code . . . . . . . . . . doc (default string) . . . . . . . . ccsid (default best) . . . . . . . . path . . . . . . . . . . . . . case (default lower) . . . . . . . . trim (default all) . . . . . . . . . allowmissing (default no) . . . . . . allowextra (default no) . . . . . . . datasubf . . . . . . . . . . . countprefix . . . . . . . . . . ns (default keep) . . . . . . . . . nsprefix . . . . . . . . . . . Expected format of XML data . . . . . Rules for transferring XML data to RPG variables . . . . . . . . . . . . Examples of the XML-INTO operation XML-SAX (Parse an XML Document). . . . %XML options for the XML-SAX operation code . . . . . . . . . . . . . . XML-SAX event-handling procedure . . . XML events . . . . . . . . . . . Examples of the XML-SAX operation . . . Z-ADD (Zero and Add) . . . . . . . . Z-SUB (Zero and Subtract) . . . . . . .
6-320 6-321 6-322 6-322 6-323 6-324 6-325 6-327 6-328 6-329 6-330 6-334 6-334 6-335 6-336 6-338 6-342 6-343 6-345 6-348 6-350 6-353 6-354 6-355 6-359 6-361 6-363 6-364 6-365 6-366 6-372 6-377 6-378
Appendixes . . . . . . . . . . . . 7-1
Appendix A. RPG IV Restrictions . . . . Appendix B. EBCDIC Collating Sequence . . . . . . 7-1 . 7-2
Bibliography
Notices . . . . . . . . . . . . . . A-1
Programming interface information . Trademarks . . . . . . . . . Terms and conditions . . . . . . . . . . . . . . . . . . A-3 . A-3 . A-3
Index . . . . . . . . . . . . . . . X-1
xii
| The IBM i Information Center contains new and updated system information, such as software | installation, Linux, WebSphere, Java, high availability, database, logical partitions, CL commands, and | system application programming interfaces (APIs). In addition, it provides advisors and finders to assist | in planning, troubleshooting, and configuring your system hardware and software. For a list of related publications, see the Bibliography.
1-1
[email protected] Be sure to include the following: v The name of the book. v The publication number of the book. v The page number or topic to which your comment applies.
1-2
What's New
New and changed features in each release of the ILE RPG compiler since V3R1 There have been several releases of RPG IV since the first V3R1 release. The following is a list of enhancements made for each release since V3R1 to the current release: | v What's New since 7.1? # v What's New in 7.1? on page 2-7 v v v v v v What's What's What's What's What's What's New New New New New New in in in in in in 6.1? on page 2-10 V5R4? on page 2-14 V5R3? on page 2-18 V5R2? on page 2-22 V5R1? on page 2-24 V4R4? on page 2-29
v What's New in V4R2? on page 2-32 v What's New in V3R7? on page 2-36 v What's New in V3R6/V3R2? on page 2-39 You can use this section to link to and learn about new RPG IV functions. # # # # | | | | | | | | | | | | | | | | | | | | | Note: The information for this product is up-to-date with the 7.1 release of RPG IV. If you are using a previous release of the compiler, you will need to determine what functions are supported on your system. For example, if you are using a V5R1 system, the functions new to the 7.1 release will not be supported.
v Free-form File definition statements begin with DCL-F and end with a semicolon. See Free-Form File Definition Statement on page 5-38. The following statements define three files 1. An externally-described DISK file opened for input and update. 2. An externally-described WORKSTN file opened for input and output. 3. A program-described PRINTER file with record-length 132.
DCL-F custFile usage(*update) extfile(custFilename); DCL-F screen workstn; DCL-F qprint printer(132) oflind(qprintOflow);
v Free-form data definition statements begin with DCL-C, DCL-DS, DCL-PI, DCL-PR, or DCL-S, and end with a semicolon. See Free-Form Definition Statement on page 5-74. The following statements define several items 1. A named constant MAX_ELEMS. 2. A standalone varying length character field fullName.
Copyright IBM Corp. 1994, 2014
2-1
What's New
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | 3. A qualified data structure with an integer subfield num and a UCS-2 subfield address. 4. A prototype for the procedure 'Qp0lRenameUnlink'.
DCL-C MAX_ELEMS 1000; DCL-S fullName VARCHAR(50) INZ(Unknown name); DCL-DS ds1 QUALIFIED; num INT(10); address UCS2(100); END-DS; DCL-PR Qp0lRenameUnlink INT(10) EXTPROC(*DCLCASE); oldName POINTER VALUE OPTIONS(*STRING); newName POINTER VALUE OPTIONS(*STRING); END-PR;
v Free-form Procedure definition statements begin with DCL-PROC and end with a semicolon. The END-PROC statement is used to end a procedure. See Free-Form Procedure Statement on page 5-189. The following example shows a free-form subprocedure definition.
DCL-PROC getCurrentUserName EXPORT; DCL-PI *n CHAR(10) END-PI; DCL-S curUser CHAR(10) INZ(*USER); RETURN curUser; END-PROC;
v The /FREE and /END-FREE directives are no longer required. The compiler will ignore them. v Free-form statements and fixed-form statements may be intermixed.
C IF endDate < beginDate; GOTO internalError ENDIF; duration = %DIFF(endDate : beginDate : *days); . . . internalError TAG
Tip: See Differences between fixed-form and free-form to be aware of on page 5-4.
| Open Access files An Open Access file is a file which has all its operations handled by a user-written program or | procedure, rather than by the operating system. This program or procedure is called an "Open | Access Handler" or simply a "handler". The HANDLER keyword specifies the handler. See Open | Access Files on page 3-95. | | New XML-INTO options v XML namespaces are supported by the "ns" and "nsprefix" options. See ns option and nsprefix | option. | v XML names with characters that are not supported by RPG for subfield names are supported | by the "case=convert" option. See case option. | | Support for CCSID conversions that cause a loss of data when a source character does not exist in the | target character set Control-specification keyword CCSIDCVT(*EXCP : *LIST). See CCSIDCVT(*EXCP | *LIST) on | page 5-19. | v Use CCSIDCVT(*EXCP) to get an exception if a CCSID conversion loses data due to the source | character not having a match in the target character set. | v Use CCSIDCVT(*LIST) to get a listing of every CCSID conversion in the module, with a | diagnostic message indicating whether the conversion has the potential of losing data. | | VALIDATE(*NODATETIME) to allow the RPG compiler to skip the validation step when working | with date, time and timestamp data |
2-2
What's New
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
EXPORT and IMPORT keywords EXTNAME keyword EXTFLD keyword
Use Control-specification keyword VALIDATE(*NODATETIME) to allow the RPG compiler to treat date, time, and timestamp data as character data, without performing the checks for validity. See VALIDATE(*NODATETIME) on page 5-36. This may improve the performance of some date, time, and timestamp operations. Note: Skipping the validation step can lead to serious data corruption problems. You should only use this feature when you are certain that your date, time, and timestamp data is always valid.
Table 2-1. Changed Language Elements Since 7.1: Control specification keywords Element DFTACTGRP keyword Description DFTACTGRP(*NO) is assumed if there are any free-form Control specifications, and if at least one of the ACTGRP, BNDDIR, or STGMDL keyword is used. See DFTACTGRP(*YES | *NO) on page 5-25.
Table 2-2. Changed Language Elements Since 7.1: Directives Element /FREE and /END-FREE directives Description These directives are no longer necessary to indicate the beginning and ending of free-form code. They are ignored by the compiler. See /FREE... /END-FREE on page 3-8.
Table 2-3. Changed Language Elements Since 7.1: Definition-specification keywords Element DTAARA keyword Description In a free-form definition: v *VAR is not used. If the name is specified without quotes, it is assumed to be the name of a variable or named constant. v For a data structure, *AUTO is used to specify that it is a Data Area Data Structure. *USRCTL is used to specify that the data area can be manipulated using IN, OUT and UNLOCK operations. See DTAARA keyword on page 5-99. In a free-form subfield definition v The parameter is optional v If the parameter is specified without quotes, it is assumed to be the name of a previously-defined named constant. See EXTFLD{(field_name)} on page 5-103. In a free-form data structure definition v If the file-name or format-name parameter is specified without quotes, it is assumed to be the name of a previously-defined named constant. See EXTNAME(file-name{:format-name}{:*ALL| *INPUT|*OUTPUT|*KEY}) on page 5-105. In a free-form definition v *DCLCASE may be specified for the external name indicating that the external name is identical to the way the stand-alone field or data structure is specified, with the same mixed case letters. See EXPORT{(external_name)} on page 5-102 and IMPORT{(external_name)} on page 5-112.
What's New
2-3
What's New
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
DCL-PI END-DS DCL-SUBF DCL-DS DCL-C DCL-F CLASS, DATFMT, PROCPTR, TIMFMT, and VARYING keywords FROMFILE, PACKEVEN, and TOFILE keywords OVERLAY keyword Table 2-3. Changed Language Elements Since 7.1: Definition-specification keywords (continued) Element EXTPROC keyword Description In a free-form prototype definition or a procedure-interface definition v *DCLCASE may be specified for the external procedure or method name indicating that the external name is identical to the way the prototype or procedure interface is specified, with the same mixed case letters. v If the procedure interface name is specified as *N, the external name is taken from the DCL-PROC statement. See EXTPROC({*CL|*CWIDEN|*CNOWIDEN| {*JAVA:class-name:}}name) on page 5-106. These keywords are not used in a free-form definition. The information specified by these keywords is specified as part of the related data-type keywords.
The parameter cannot be the name of the data structure for a free-form subfield definition. The POS keyword is used instead. See POS(starting-position) on page 5-137.
Table 2-4. Changed Language Elements Since 7.1: Order of statements Element File and Definition statements Description File and Definition statements can be intermixed. See RPG IV Specification Types on page 5-1.
Table 2-5. New Language Elements Since 7.1: Free-form statements Element CTL-OPT Description Begins a free-form Control statement See Free-Form Control Statement on page 5-14. Begins a free-form File definition See Free-Form File Definition Statement on page 5-38. Begins a free-form Named Constant definition See Free-Form Named Constant Definition on page 5-77. Begins a free-form Data Structure definition See Free-Form Data Structure Definition on page 5-78. Begins a free-form Subfield definition. Specifying "DCL-SUBF" is optional unless the subfield name is the same as an operation code allowed in free-form calculations. See Free-Form Subfield Definition on page 5-82. Ends a free-form Data Structure definition. If there are no subfields, it can be specified after the last keyword of the DCL-DS statement. See Free-Form Data Structure Definition on page 5-78. Begins a free-form Procedure Interface definition See Free-Form Procedure Interface Definition on page 5-84.
2-4
What's New
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
DISK{(*EXT | record-length)} PRINTER{(*EXT | record-length)} SEQ{(*EXT | record-length)} SPECIAL{(*EXT | record-length)} WORKSTN{(*EXT | record-length)} USAGE(*INPUT *OUTPUT *UPDATE *DELETE) KEYED{(*CHAR : key-length)} Specifies the usage of the file in a free-form file definition. See USAGE(*INPUT *OUTPUT *UPDATE *DELETE) on page 5-72. Indicates that the file is keyed in a free-form file definition. See KEYED{(*CHAR : key-length)} on page 5-59. END-PROC DCL-PROC DCL-S END-PR END-PI DCL-PARM Table 2-5. New Language Elements Since 7.1: Free-form statements (continued) Element DCL-PR Description Begins a free-form Prototype definition See Free-Form Prototype Definition on page 5-83. Begins a free-form Parameter definition. Specifying "DCL-PARM" is optional unless the parameter name is the same as an operation code allowed in free-form calculations See Free-Form Parameter Definition on page 5-86.. Ends a free-form Procedure Interface definition. If there are no parameters, it can be specified after the last keyword of the DCL-PI statement. See Free-Form Procedure Interface Definition on page 5-84. Ends a free-form Prototype definition. If there are no parameters, it can be specified after the last keyword of the DCL-PR statement. See Free-Form Prototype Definition on page 5-83. Begins a free-form Standalone Field definition See Free-Form Standalone Field Definition on page 5-78. Begins a free-form Procedure definition See Free-Form Procedure Statement on page 5-189. Ends a free-form Procedure definition See Free-Form Procedure Statement on page 5-189. Table 2-6. New Language Elements Since 7.1: File definition keywords Element HANDLER Description Specifies that the file is an Open Access file. See HANDLER(program-or-procedure { : communication-area)}) on page 5-56. Device keywords to specify the device type of a free-form File definition. v The default device type is DISK. v The default parameter for each device-type keyword is *EXT, indicating that it is an externally-described file. See File devices on page 3-94.
What's New
2-5
What's New
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
POINTER{(*PROC)} TIMESTAMP TIME{(format)} DATE{(format)} PACKED(digits {:decimals}) ZONED(digits {:decimals}) BINDEC(digits {:decimals}) FLOAT(size) UNS(digits) INT(digits) VARUCS2(length {:prefix-size}) IND VARGRAPH(length {:prefix-size}) UCS2(length) VARCHAR(length {:prefix-size}) GRAPH(length) Table 2-7. New Language Elements Since 7.1: Free-form data-type keywords Element CHAR(length) Description Fixed-length alphanumeric data type See CHAR(length) on page 5-96. Varying-length alphanumeric data type See VARCHAR(length {:2 | 4}) on page 5-147. Fixed-length Graphic data type See GRAPH(length) on page 5-112. Varying-length Graphic data type See VARGRAPH(length {:2 | 4}) on page 5-147. Fixed-length UCS-2 data type See UCS2(length) on page 5-146. Varying-length UCS-2 data type See VARUCS2(length {:2 | 4}) on page 5-148. Indicator data type See IND on page 5-113. Integer data type See INT(digits) on page 5-113. Unsigned integer data type See UNS(digits) on page 5-146. Packed decimal data type See PACKED(digits {: decimal-positions}) on page 5-136. Zoned decimal data type See ZONED(digits {: decimal-positions}) on page 5-149. Binary decimal data type See BINDEC(digits {: decimal-positions}) on page 5-96. Float data type See FLOAT(bytes) on page 5-111. Date data type See DATE{(format{separator})} on page 5-98. Time data type See TIME{(format{separator})} on page 5-145. Timestamp data type See TIMESTAMP on page 5-145. Pointer data type. The optional parameter *PROC indicates that it is a procedure pointer. See POINTER{(*PROC)} on page 5-137.
2-6
What's New
| | | | | | | | | | | | | | | | | | #
Table 2-7. New Language Elements Since 7.1: Free-form data-type keywords (continued) Element OBJECT{(*JAVA : class-name)} Description Object data type. The parameters are optional if it is defining the return type of a Java constructor. See OBJECT{(*JAVA:class-name)} on page 5-122. Table 2-8. New Language Elements Since 7.1: Free-form data definition keywords Element EXT Description Indicates that a data structure is externally described. This keyword is optional if the EXTNAME keyword is specified as the first keyword for a data structure definition. See EXT on page 5-103. Specifies the starting position of a subfield in the data structure. See POS(starting-position) on page 5-137. Specifies that the data structure is a Program Status Data Structure. See PSDS on page 5-139.
POS(subfield-startposition) PSDS
# This section describes the enhancements made to ILE RPG in 7.1. # Sort and search data structure arrays # # # # # # # Data structure arrays can be sorted and searched using one of the subfields as a key.
// Sort the custDs array by the amount_owing subfield SORTA custDs(*).amount_owing; // Search for an element in the custDs array where the // account_status subfield is "K" elem = %LOOKUP("K" : custDs(*).account_status);
# Sort an array either ascending or descending # # # # An array can be sorted ascending using SORTA(A) and descending using SORTA(D). The array cannot be a sequenced array (ASCEND or DESCEND keyword).
// Sort the salary array in descending order SORTA(D) salary;
# New built-in function %SCANRPL (scan and replace) # # # # # # The %SCANRPL built-in function scans for all occurrences of a value within a string and replaces them with another value.
// Replace NAME with Tom string1 = See NAME. See NAME run. Run NAME run.; string2 = %ScanRpl(NAME : Tom : string1); // string2 = See Tom. See Tom run. Run Tom run.
# %LEN(varying : *MAX) # # The %LEN builtin function can be used to obtain the maximum number of characters for a varying-length character, UCS-2 or Graphic field.
# Use ALIAS names in externally-described data structures # # # # Use the ALIAS keyword on a Definition specification to indicate that you want to use the alternate names for the subfields of externally-described data structures. Use the ALIAS keyword on a File specification to indicate that you want to use the alternate names for LIKEREC data structures defined from the records of the file.
What's New
2-7
What's New
# # # # # # # # # # #
A A A A R CUSTREC CUSTNM CUSTAD ID
ALIAS(CUSTOMER_NAME) ALIAS(CUSTOMER_ADDRESS)
D custDs e ds ALIAS D QUALIFIED EXTNAME(custFile) /free custDs.customer_name = John Smith; custDs.customer_address = 123 Mockingbird Lane; custDs.id = 12345;
# Faster return values # # # # # # # # # # A procedure defined with the RTNPARM keyword handles the return value as a hidden parameter. When a procedure is prototyped to return a very large value, especially a very large varying value, the performance for calling the procedure can be significantly improved by defining the procedure with the RTNPARM keyword.
D getFileData pr a varying len(1000000) D rtnparm D file a const varying len(500) D data S a varying len(1000) /free data = getFileData (/home/mydir/myfile.txt);
# %PARMNUM built-in function # # # # # # # # # # # The %PARMNUM(parameter_name) built-in function returns the ordinal number of the parameter within the parameter list. It is especially important to use this built-in function when a procedure is coded with the RTNPARM keyword.
D D D D D pi name id errorInfo 100a const varying 10i 0 value likeds(errs_t) options(*nopass)
/free // Check if the "errorInfo" parameter was passed if %parms >= %parmnum(errorInfo);
# Optional prototypes # # # # # # # # If a program or procedure is not called by another RPG module, it is optional to specify the prototype. The prototype may be omitted for the following types of programs and procedures: v A program that is only intended to be used as an exit program or as the command-processing program for a command v A program that is only intended to be called from a different programming language v A procedure that is not exported from the module v A procedure that is exported from the module but only intended to be called from a different programming language
# Pass any type of string parameter Implicit conversion will be done for string parameters passed by value or by read-only reference. # For example, a procedure can be prototyped to have a CONST UCS-2 parameter, and character # expression can be passed as a parameter on a call to the procedure. This enables you to write a # single procedure with the parameters and return value prototyped with the UCS-2 type. To call # that procedure, you can pass any type of string parameter, and assign the return value to any # type of string variable. # // The makeTitle procedure upper-cases the value # // and centers it within the provided length # alphaTitle = makeTitle(alphaValue : 50); # ucs2Title = makeTitle(ucs2Value : 50); # dbcsTitle = makeTitle(dbcsValue : 50); #
2-8
What's New
# Two new options for XML-INTO # v The datasubf option allows you to name a subfield that will receive the text data for an XML # element that also has attributes. # v The countprefix option reduces the need for you to specify the allowmissing=yes option. It # specifies the prefix for the names of the additional subfields that receive the number of RPG # array elements or non-array subfields set by the XML-INTO operation. # These options are also available through a PTF for 6.1.
# Teraspace storage model | | | | | # # # # # # # # RPG modules and programs can be created to use the teraspace storage model or to inherit the storage model of their caller. With the teraspace storage model, the system limits regarding automatic storage are significantly higher than those for the single-level storage model. There are limits for the amount of automatic storage for a single procedure and for the total automatic storage of all the procedures on the call stack. Use the storage model (STGMDL) parameter on the CRTRPGMOD or CRTBNDRPG command, or use the STGMDL keyword on the Control specification. *TERASPACE The program or module uses the teraspace storage model. *SNGLVL The program or module uses the single-level storage model. *INHERIT The program or module inherits the storage model of its caller.
# Change to the ACTGRP parameter of the CRTBNDRPG command and the ACTGRP keyword on the # Control specification # # # # # # # # The default value of the ACTGRP parameter and keyword is changed from QILE to *STGMDL. ACTGRP(*STGMDL) specifies that the activation group depends on the storage model of the program. When the storage model is *TERASPACE, ACTGRP(*STGMDL) is the same as ACTGRP(QILETS). Otherwise, ACTGRP(*STGMDL) is the same as ACTGRP(QILE). Note: The change to the ACTGRP parameter and keyword does not affect the default way the activation group is assigned to the program. The default value for the STGMDL parameter and keyword is *SNGLVL, so when the ACTGRP parameter or keyword is not specified, the activation group of the program will default to QILE as it did in prior releases.
# Allocate teraspace storage # # # # Use the ALLOC keyword on the Control specification to specify whether the RPG storage-management operations in the module will use teraspace storage or single-level storage. The maximum size of a teraspace storage allocation is significantly larger than the maximum size of a single-level storage allocation.
# Encrypted listing debug view # # # # # When a module's listing debug view is encrypted, the listing view can only be viewed during a debug session when the person doing the debugging knows the encryption key. This enables you to send debuggable programs to your customers without enabling your customers to see your source code through the listing view. Use the DBGENCKEY parameter on the CRTRPGMOD, CRTBNDRPG, or CRTSQLRPGI command.
What's New
2-9
What's New
# Table 2-9. Changed Language Elements Since 6.1 # Language Unit # Control specification keywords # # # # # # Built-in functions # # # Operation codes # # # # # # Language Unit # Control specification keywords # # # # # # File specification keywords # # # Definition specification keywords # # # # # # Built-in functions # # # # # XML-INTO options # # # # # # # # #
Element ACTGRP(*STGMDL) Description *STGMDL is the new default for the ACTGRP keyword and command parameter. If the program uses the teraspace storage module, the activation group is QILETS. Otherwise it is QILE. Can now be used to obtain the maximum number of characters of a varying-length field. The SORTA operation code now allows the A and D operation extenders indicating whether the array should be sorted ascending (A) or descending (D).
%LEN(varying-field : *MAX)
SORTA(A | D)
ALLOC(*STGMDL | *TERASPACE | Controls the storage model for the *SNGLVL) storage-managent operations %ALLOC, %REALLOC, DEALLOC, ALLOC, REALLOC ALIAS Use the alternate field names for the subfields of data structures defined with the LIKEREC keyword Use the alternate field names for the subfields of the externally-described data structure Specifies that the return value for the procedure should be handled as a hidden parameter Returns the ordinal number of the parameter in the parameter list Scans for all occurrences of a value within a string and replaces them with another value Name a subfield that will receive the text data for an XML element that also has attributes Specifies the prefix for the names of the additional subfields that receive the number of RPG array elements or non-array subfields set by the XML-INTO operation
ALIAS
RTNPARM
%PARMNUM %SCANRPL
datasubf
countprefix
2-10
What's New
When THREAD(*CONCURRENT) is specified on the Control specification of a module, it provides ability to run concurrently in multiple threads: v Multiple threads can run in the module at the same time. v By default, static variables will be defined so that each thread will have its own copy of the static variable. v Individual variables can be defined to be shared by all threads using STATIC(*ALLTHREAD). v Individual procedures can be serialized so that only one thread can run them at one time, by specifying SERIALIZE on the Procedure-Begin specification. Ability to define a main procedure which does not use the RPG cycle Using the MAIN keyword on the Control specification, a subprocedure can be identified as the program entry procedure. This allows an RPG application to be developed where none of the modules uses the RPG cycle. Files defined in subprocedures Files can be defined locally in subprocedures. I/O to local files can only be done with data structures; I and O specifications are not allowed in subprocedures, and the compiler does not generate I and O specifications for externally described files. By default, the storage associated with local files is automatic; the file is closed when the subprocedure returns. The STATIC keyword can be used to indicate that the storage associated with the file is static, so that all invocations of the subprocedure will use the same file, and if the file is open when the subprocedure returns, it will remain open for the next call to the subprocedure. Qualified record formats When a file is defined with the QUALIFIED keyword, the record formats must be qualified by the file name, MYFILE.MYFMT. Qualified files do not have I and O specifications generated by the compiler; I/O can only be done through data structures. Files defined like other files Using the LIKEFILE keyword, a file can be defined to use the same settings as another File specification, which is important when passing a file as a parameter. If the file is externally-described, the QUALIFIED keyword is implied. I/O to the new file can only be done through data structures. Files passed as parameters A prototyped parameter can be defined as a File parameter using the LIKEFILE keyword. Any file related through the same LIKEFILE definition may be passed as a parameter to the procedure. Within the called procedure or program, all supported operations can be done on the file; I/O can only be done through data structures. EXTDESC keyword and EXTFILE(*EXTDESC) The EXTDESC keyword identifies the file to be used by the compiler at compile time to obtain the external decription of the file; the filename is specified as a literal in one of the forms 'LIBNAME/FILENAME' or 'FILENAME'. This removes the need to provide a compile-time override for the file. The EXTFILE keyword is enhanced to allow the special value *EXTDESC, indicating that the file specified by EXTDESC is also to be used at runtime. EXTNAME to specify the library for the externally-described data structure The EXTNAME keyword is enhanced to allow a literal to specify the library for the external file. EXTNAME('LIBNAME/FILENAME') or EXTNAME('FILENAME') are supported. This removes the need to provide a compile-time override for the file. EXFMT allows a result data structure
What's New
2-11
What's New
The EXFMT operation is enhanced to allow a data structure to be specified in the result field. The data structure must be defined with usage type *ALL, either as an externally-described data structure for the record format (EXTNAME(file:fmt:*ALL), or using LIKEREC of the record format (LIKEREC(fmt:*ALL). Larger limits for data structures, and character, UCS-2 and graphic variables v Data structures can have a size up to 16,773,104. v Character definitions can have a length up to 16,773,104. (The limit is 4 less for variable length character definitions.) v Character definitions can have a length up to 16,773,104. (The limit is 4 less for variable length character definitions.) v UCS-2 definitions can have a length up to 8,386,552 UCS-2 characters. (The limit is 2 less for variable length UCS-2 definitions.) v Graphic definitions can have a length up to 8,386,552 DBCS characters. (The limit is 2 less for variable length graphic definitions.) v The VARYING keyword allows a parameter of either 2 or 4 indicating the number of bytes used to hold the length prefix. %ADDR(varying : *DATA) The %ADDR built-in function is enhanced to allow *DATA as the second parameter to obtain the address of the data part of a variable length field. Larger limit for DIM and OCCURS An array or multiple-occurrence data structure can have up to 16,773,104 elements, provided that the total size is not greater than 16,773,104. Larger limits for character, UCS-2 and DBCS literals v Character literals can now have a length up to 16380 characters. v UCS-2 literals can now have a length up to 8190 UCS-2 characters. v Graphic literals can now have a length up to 16379 DBCS characters. TEMPLATE keyword for files and definitions The TEMPLATE keyword can be coded for file and variable definitions to indicate that the name will only be used with the LIKEFILE, LIKE, or LIKEDS keyword to define other files or variables. Template definitions are useful when defining types for prototyped calls, since the compiler only uses them at compile time to help define other files and variables, and does not generate any code related to them. Template data structures can have the INZ keyword coded for the data structure and its subfields, which will ease the use of INZ(*LIKEDS). Relaxation of some UCS-2 rules The compiler will perform some implicit conversion between character, UCS-2 and graphic values, making it unnecessary to code %CHAR, %UCS2 or %GRAPH in many cases. This enhancement is also available through PTFs for V5R3 and V5R4. Implicit conversion is now supported for v Assignment using EVAL and EVALR. v Comparison operations in expressions. v Comparison using fixed form operations IFxx, DOUxx, DOWxx, WHxx, CASxx, CABxx, COMP. v Note that implicit conversion was already supported for the conversion operations MOVE and MOVEL. UCS-2 variables can now be initialized with character or graphic literals without using the %UCS2 built-in function.
2-12
What's New
Eliminate unused variables from the compiled object New values *UNREF and *NOUNREF are added to the OPTION keyword for the CRTBNDRPG and CRTRPGMOD commands, and for the OPTION keyword on the Control specification. The default is *UNREF. *NOUNREF indicates that unreferenced variables should not be generated into the RPG module. This can reduce program size, and if imported variables are not referenced, it can reduce the time taken to bind a module to a program or service program. PCML can now be stored in the module Program Call Markup Language (PCML) can now be stored in the module as well as in a stream file. By using combinations of the PGMINFO command parameter and/or the new PGMINFO keyword for the Control specification, the RPG programmer can choose where the PCML information should go. If the PCML information is placed in the module, it can later be retrieved using the QBNRPII API. This enhancement is also available through PTFs for V5R4, but only through the Control specification keyword.
Table 2-11. Changed Language Elements Since V5R4 Language Unit Control specification keywords Element OPTION(*UNREF | *NOUNREF) Description Specifies that unused variables should not be generated into the module. New parameter *CONCURRENT allows running concurrently in multiple threads. Specifies that the value of the EXTDESC keyword is also to be used for the EXTFILE keyword. Can now be used to obtain the address of the data portion of a varying-length variable. An array can have up to 16773104 elements. Allows a literal for the file name. The literal can include the library for the file. A multiple-occurrence data structure can have up to 16773104 elements. Can now take a parameter indicating the number of bytes for the length prefix. Can be up to 9999999 for Data Structures, and definitions of type A, C or G. (To define a longer item, the LEN keyword must be used.) Can be up to 99999 for alphanumeric fields, and up to 99998 for UCS-2 and Graphic fields. Can be up to 99999 for alphanumeric fields. Can have a data structure in the result entry.
THREAD(*CONCURRENT)
EXTFILE(*EXTDESC)
Built-in functions
%ADDR(varying-field : *DATA)
DIM(16773104) EXTNAME('LIB/FILE')
OCCURS(16773104) VARYING{(2|4)}
Definition specifications
Length entry
Input specifications
Length entry
What's New
2-13
What's New
Table 2-12. New Language Elements Since V5R4 Language Unit Element MAIN(subprocedure-name) PGMINFO(*NO | *PCML { : *MODULE } ) File specification keywords STATIC Description Specifies the program-entry procedure for the program. Indicates whether Program Information is to be placed directly in the module. Indicates that a local file retains its program state across calls to a subprocedure. Indicates that the record format names of the file are qualified by the file name, FILE.FMT. Indicates that the file is defined the same as another file. Indicates that the file is only to be used for later LIKEFILE definitions. Specifies the external file used at compile time for the external definitions. Indicates that the same instance of the static variable is used by all threads running in the module. Indicates that the parameter is a file. Indicates that the definition is only to be used for LIKE or LIKEDS definitions. Specifies the length of a data structure, or a definition of type A, C or G. Indicates that the procedure can be run by only one thread at a time.
QUALIFIED
STATIC(*ALLTHREAD)
LIKEFILE(filename) TEMPLATE
LEN(length)
SERIALIZE
New operation code EVAL-CORR assigns data and null-indicators from the subfields of the source data structure to the subfields of the target data structure. The subfields that are assigned are the subfields that have the same name and compatible data type in both data structures. For example, if data structure DS1 has character subfields A, B, and C, and data structure DS2 has character subfields B, C, and D, statement EVAL-CORR DS1 = DS2; will assign data from subfields DS2.B and DS2.C to DS1.B and DS1.C. Null-capable subfields in the target data structure that are affected by the EVAL-CORR operation will also have their null-indicators assigned from the null-indicators of the source data structure's subfields, or set to *OFF, if the source subfield is not null-capable.
// // // DS1 subfields s1 character s2 character DS2 subfields s1 packed s2 character
2-14
What's New
// s3 numeric // s4 date s4 date // s5 character EVAL-CORR ds1 = ds2; // This EVAL-CORR operation is equivalent to the following EVAL operations // EVAL ds1.s2 = ds2.s2 // EVAL ds1.s4 = ds2.s4 // Other subfields either appear in only one data structure (S3 and S5) // or have incompatible types (S1).
EVAL-CORR makes it easier to use result data structures for I/O operations to externally-described files and record formats, allowing the automatic transfer of data between the data structures of different record formats, when the record formats have differences in layout or minor differences in the types of the subfields. New prototyped parameter option OPTIONS(*NULLIND) When OPTIONS(*NULLIND) is specified for a parameter, the null-byte map is passed with the parameter, giving the called procedure direct access to the null-byte map of the caller's parameter. New builtin function %XML
%XML (xmldocument { : options } )
The %XML builtin function describes an XML document and specifies options to control how the document should be parsed. The xmldocument parameter can be a character or UCS-2 expression, and the value may be an XML document or the name of an IFS file containing an XML document. If the value of the xmldocument parameter has the name of a file, the "doc=file" option must be specified. New builtin function %HANDLER
%HANDLER (handlingProcedure : communicationArea )
%HANDLER is used to identify a procedure to handle an event or a series of events. %HANDLER does not return a value, and it can only be specified as the first operand of XML-SAX and XML-INTO. The first operand, handlingProcedure, specifies the prototype of the handling procedure. The return value and parameters specified by the prototype must match the parameters required for the handling procedure; the requirements are determined by the operation that %HANDLER is specified for. The second operand, communicationArea, specifies a variable to be passed as a parameter on every call to the handling procedure. The operand must be an exact match for the first prototyped parameter of the handling procedure, according to the same rules that are used for checking prototyped parameters passed by reference. The communication-area parameter can be any type, including arrays and data structures. New operation code XML-SAX
XML-SAX{ (e) } %HANDLER(eventHandler : commArea ) %XML(xmldoc { : options } );
XML-SAX initiates a SAX parse for the XML document specified by the %XML builtin function. The XML-SAX operation begins by calling an XML parser which begins to parse the document. When the parser discovers an event such as finding the start of an element, finding an attribute name, finding the end of an element etc., the parser calls the eventHandler with parameters describing the event. The commArea operand is a variable that is passed as a parameter to the eventHandler providing a way for the XML-SAX operation code to communicate with the handling procedure. When the eventHandler returns, the parser continues to parse until it finds the next event and calls the eventHandler again. New operation code XML-INTO
What's New
2-15
What's New
XML-INTO{ (EH) } variable %XML(xmlDoc { : options }); XML-INTO{ (EH) } %HANDLER(handler : commArea ) %XML(xmlDoc { : options });
XML-INTO reads the data from an XML document in one of two ways: v directly into a variable v gradually into an array parameter that it passes to the procedure specified by %HANDLER. Various options may be specified to control the operation. The first operand specifies the target of the parsed data. It can contain a variable name or the % HANDLER built-in function. The second operand contains the %XML builtin function specifying the source of the XML document and any options to control how the document is parsed. It can contain XML data or it can contain the location of the XML data. The doc option is used to indicate what this operand specifies.
// Data structure "copyInfo" has two subfields, "from" // and "to". Each of these subfields has two subfields // "name" and "lib". // File cpyA.xml contains the following XML document // <copyinfo> // <from><name>MASTFILE</name><lib>CUSTLIB</lib></from> // <to><name>MYFILE</name><lib>*LIBL</lib> // <copyinfo> xml-into copyInfo %XML(cpyA.xml : doc=file); // After the XML-INTO operation, the following // copyInfo.from .name = MASTFILE .lib = CUSTLIB // copyInfo.to .name = MYFILE .lib = *LIBL
Use the PREFIX keyword to remove characters from the beginning of field names
PREFIX( : number_of_characters)
When an empty character literal (two single quotes specified with no intervening characters) is specified as the first parameter of the PREFIX keyword for File and Definition specifications, the specified number of characters is removed from the field names. For example if a file has fields XRNAME, XRIDNUM, and XRAMOUNT, specifying PREFIX(:2)on the File specification will cause the internal field names to be NAME, IDNUM, and AMOUNT. If you have two files whose subfields have the same names other than a file-specific prefix, you can use this feature to remove the prefix from the names of the subfields of externally-described data structures defined from those files. This would enable you to use EVAL-CORR to assign the same-named subfields from one data structure to the other. For example, if file FILE1 has a field F1NAME and file FILE2 has a field F2NAME, and PREFIX(:2) is specified for externally-described data structures DS1 for FILE1 and DS2 for FILE2, then the subfields F1NAME and F2NAME will both become NAME. An EVAL-CORR operation between data structures DS1 and DS2 will assign the NAME subfield. New values for the DEBUG keyword
DEBUG { ( *INPUT *DUMP *XMLSAX *NO *YES ) }
The DEBUG keyword determines what debugging aids are generated into the module. *NO and *YES are existing values. *INPUT, *DUMP and *XMLSAX provide more granularity than *YES. | | *INPUT Fields that are in Input specifications but are not used anywhere else in the module are read into the program fields during input operations. *DUMP DUMP operations without the (A) extender are performed.
2-16
What's New
*XMLSAX An array of SAX event names is generated into the module to be used while debugging a SAX event handler. *NO Indicates that no debugging aids are to be generated into the module. Specifying DEBUG(*NO) is the same as omitting the DEBUG keyword. *YES This value is kept for compatibility purposes. Specifying DEBUG(*YES) is the same as specifying DEBUG without parameters, or DEBUG(*INPUT : *DUMP). Syntax-checking for free-form calculations In SEU, free-form statements are now checked for correct syntax. Improved debugging support for null-capable subfields of a qualified data structure When debugging qualified data structures with null-capable subfields, the null-indicators are now organized as a similar data structure with an indicator subfield for every null-capable subfield. The name of the data structure is _QRNU_NULL_data_structure_name, for example _QRNU_NULL_MYDS. If a subfield of the data structure is itself a data structure with null-capable subfields, the nullindicator data structure will similarly have a data structure subfield with indicator subfields. For example, if data structure DS1 has null-capable subfields DS1.FLD1, DS1.FLD2, and DS1.SUB.FLD3, you can display all the null-indicators in the entire data structure using the debug instruction.
===> EVAL _QRNU_NULL_DS > EVAL _QRNU_NULL_DS1 _QRNU_NULL_DS1.FLD1 = 1 _QRNU_NULL_DS1.FLD2 = 0 _QRNU_NULL_DS1.SUB.FLD3 = 1 ===> EVAL _QRNU_NULL_DS.FLD2 _QRNU_NULL_DS1.FLD2 = 0 ===> EVAL _QRNU_NULL_DS.FLD2 = 1 ===> EVAL DSARR(1).FLD2 DSARR(1).FLD2 = abcde ===> EVAL _QRNU_NULL_DSARR(1).FLD2 _QRNU_NULL_DSARR(1).FLD2 = 0
Change to end-of-file behaviour with shared files If a module performs a keyed sequential input operation to a shared file and it results in an EOF condition, and a different module sets the file cursor using a positioning operation such as SETLL, a subsequent sequential input operation by the first module may be successfully done. Before this change, the first RPG module ignored the fact that the other module had repositioned the shared file. This change in behaviour is available with PTFs for releases V5R2M0 (SI13932) and V5R3M0 (SI14185).
Table 2-13. Changed Language Elements Since V5R3 Language Unit Control specification keywords Element DEBUG(*INPUT|*DUMP *XMLSAX|*NO|*YES) PREFIX(:2) Description New parameters *INPUT, *DUMP and *XMLSAX give more options for debugging aids. An empty literal may be specified as the first parameter of the PREFIX keyword, allowing characters to be removed from the beginning of names.
What's New
2-17
What's New
Table 2-13. Changed Language Elements Since V5R3 (continued) Language Unit Definition specification keywords Element OPTIONS(*NULLIND) PREFIX(:2) Description Indicates that the null indicator is passed with the parameter. An empty literal may be specified as the first parameter of the PREFIX keyword, allowing characters to be removed from the beginning of names.
Table 2-14. New Language Elements Since V5R3 Language Unit Built-in functions Element %HANDLER(prototype: parameter) %XML(document{:options}) Description Specifies a handling procedure for an event. Specifies an XML document and options to control the way it is parsed. Assigns data and null-indicators from the subfields of the source data structure to the subfields of the target data structure. Reads the data from an XML document directly into a program variable. Initiates a SAX parse of an XML document.
Operation codes
EVAL-CORR
XML-INTO
XML-SAX
v The SORTA operation code is enhanced to allow sorting of partial arrays. When %SUBARR is specified in factor 2, the sort only affects the partial array indicated by the %SUBARR builtin function. v Direct conversion of date/time/timestamp to numeric, using %DEC:
2-18
What's New
%DEC is enhanced to allow the first parameter to be a date, time or timestamp, and the optional second parameter to specify the format of the resulting numeric value. Example:
D numDdMmYy s 6p 0 D date s d date = D2003-08-21; numDdMmYy = %dec(date : *dmy); datfmt(*jul) // now numDdMmYy = 210803
v Control specification CCSID(*CHAR : *JOBRUN) for correct conversion of character data at runtime: The Control specification CCSID keyword is enhanced to allow a first parameter of *CHAR. When the first parameter is *CHAR, the second parameter must be *JOBRUN. CCSID(*CHAR : *JOBRUN) controls the way character data is converted to UCS-2 at runtime. When CCSID(*CHAR:*JOBRUN) is specified, character data will be assumed to be in the job CCSID; when CCSID(*CHAR : *JOBRUN) is not specified, character data will be assumed to be in the mixed-byte CCSID related to the job CCSID. v Second parameter for %TRIM, %TRIMR and %TRIML indicating what characters to trim: %TRIM is enhanced to allow an optional second parameter giving the list of characters to be trimmed. Example:
trimchars = *-.; data = ***a-b-c-. result = %trim(data : trimchars); // now result = a-b-c. All * - and . were trimmed from the ends of the data
v New prototype option OPTIONS(*TRIM) to pass a trimmed parameter: When OPTIONS(*TRIM) is specified on a prototyped parameter, the data that is passed be trimmed of leading and trailing blanks. OPTIONS(*TRIM) is valid for character, UCS-2 and graphic parameters defined with CONST or VALUE. It is also valid for pointer parameters defined with OPTIONS(*STRING). With OPTIONS(*STRING : *TRIM), the passed data will be trimmed even if a pointer is passed on the call. Example:
D D D D D D D D D proc parm1 parm2 parm3 parm4 parm5 ptr data fld1 /free data = rst + x00; ptr = %addr(data); proc ( xyz // the called // parm1 = // parm2 = // parm3 = // parm4 = // parm5 = : @#$ procedure xyz @#$ 123 a pointer a pointer : 123 : abc : ptr); receives the following parameters pr 5a 5a 5a * * * 10a 5a const const const value value options(*trim) options(*trim : *rightadj) varying options(*trim) options(*string : *trim) options(*string : *trim)
s s s
v Support for 63 digit packed and zoned decimal values Packed and zoned data can be defined with up to 63 digits and 63 decimal positions. The previous limit was 31 digits. v Relaxation of the rules for using a result data structure for I/O to externally-described files and record formats The result data structure for I/O to a record format may be an externally-described data structure. A data structure may be specified in the result field for I/O to an externally-described file name for operation codes CHAIN, READ, READE, READP and READPE.
What's New
2-19
What's New
Examples: 1. The following program writes to a record format using from an externally-described data structure.
Foutfile o e k disk D outrecDs e ds /free O_FLD1 = ABCDE; O_FLD2 = 7; write outrec outrecDs; *inlr = *on; /end-free extname(outfile) prefix(O_)
2. The following program reads from a multi-format logical file into data structure INPUT which contains two overlapping subfields holding the fields of the respective record formats.
Flog if e k disk D infds ds D recname 261 270 D input ds D rec1 D rec2 /free read log input; dow not %eof(log); dsply recname; if recname = REC1; // handle rec1 elseif recname = REC2; // handle rec2 endif; read log input; enddo; *inlr = *on; /end-free infds(infds) qualified likerec(rec1) overlay(input) likerec(rec2) overlay(input)
v If a program/module performs a keyed sequential input operation to a shared file and it results in an EOF condition, a subsequent sequential input operation by the same program/module may be attempted. An input request is sent data base and if a record is available for input, the data is moved into the program/module and the EOF condition is set off. v Support for new environment variables for use with RPG programs calling Java methods QIBM_RPG_JAVA_PROPERTIES allows RPG users to explicitly set the java properties used to start the JVM This environment variable must be set before any RPG program calls a Java method in a job. This environment variable has contains Java options, separated and terminated by some character that does not appear in any of the option strings. Semicolon is usually a good choice. Examples: 1. Specifying only one option: If the system's default JDK is 1.3, and you want your RPG programs to use JDK 1.4, set environment variable QIBM_RPG_JAVA_PROPERTIES to
-Djava.version=1.4;
Note that even with just one option, a terminating character is required. This example uses the semicolon. 2. Specifying more than one option: If you also want to set the os400.stdout option to a different value than the default, you could set the environment variable to the following value:
-Djava.version=1.4!-Dos400.stdout=file:mystdout.txt!
This example uses the exclamation mark as the separator/terminator. Note: This support is also available in V5R1 and V5R2 with PTFs. V5R1: SI10069, V5R2: SI10101. QIBM_RPG_JAVA_EXCP_TRACE allows RPG users to get the exception trace when an RPG call to a Java method ends with an exception
2-20
What's New
This environment variable can be set, changed, or removed at any time. If this environment variable contains the value 'Y', then when a Java exception occurs during a Java method call from RPG, or a called Java method throws an exception to its caller, the Java trace for the exception will be printed. By default, it will be printed to the screen, and may not be possible to read. To get it printed to a file, set the Java option os400.stderr. (This would have to be done in a new job; it could be done by setting the QIBM_RPG_JAVA_PROPERTIES environment variable to
-Dos400.stderr=file:stderr.txt;
v An RPG preprocessor enabling the SQL preprocessor to handle conditional compilation and nested /COPY When the RPG compiler is called with a value other than *NONE for parameter PPGENOPT, it will behave as an RPG preprocessor. It will generate a new source file rather than generating a program. The new source file will contain the original source lines that are accepted by the conditional compilation directives such as /DEFINE and /IF. It will also have the source lines from files included by /COPY statements, and optionally it will have the source lines included by /INCLUDE statements. The new source file will have the comments from the original source file if PPGENOPT(*DFT) or PPGENOPT(*NORMVCOMMENT) is specified.When the SQL precompiler is called with a value other than *NONE for new parameter RPGPPOPT, the precompiler will use this RPG preprocessor to handle /COPY, the conditional compilation directives and possibly the /INCLUDE directive. This will allow SQLRPGLE source to have nested /COPY statements, and conditionally used statements.
Table 2-15. Changed Language Elements Since V5R2 Language Unit Control specification keywords Element CCSID(*GRAPH:parameter| *UCS2:number| *CHAR:*JOBRUN) %DEC(expression {format}) %TRIM(expression:expression) Description Can now take a first parameter of *CHAR, with a second parameter of *JOBRUN, to control how character data is treated at runtime. Can now take a parameter of type Date, Time or Timestamp Can now take a second parameter indicating the set of characters to be trimmed Indicates that blanks are to be trimmed from passed parameters The length and number of decimal places can be 63 for packed and zoned fields. The length can be 32 for packed fields and 63 for zoned fields. The number of decimal places can be 63 for packed and zoned fields. The length and number of decimal places can be 63 for packed and zoned fields. Allow a data structure to be specified in the result field when Factor 2 is the name of an externally-described file. Allow an externally-described data structure to be specified in the result field when Factor 2 is the name of an externally-described record format. Now has an extended Factor 2, allowing %SUBARR to be specified.
Built-in Functions
Input specifications
Calculation specifications
CHAIN, READ, READE, READP, AND READPE operations CHAIN, READ, READC, READE, READP, READPE, WRITE, UPDATE operations
SORTA operation
What's New
2-21
What's New
Table 2-16. New Language Elements Since V5R2 Language Unit Built-in Functions Element %SUBARR(array:starting element {:number of elements}) Description Returns a section of the array, or allows a section of the array to be modified.
In addition, data structures can be defined the same as a record format, using the new LIKEREC keyword. v Enhanced externally-described data structures Externally-described data structures can hold the programmer's choice of input, output, both, key or all fields. Currently, externally-described data structures can only hold input fields. v Enhancments to keyed I/O Programmers can specify search arguments in keyed Input/Output operations in /FREE calculations in two new ways: 1. By specifying the search arguments (which can be expressions) in a list. 2. By specifying a data structure which contains the search arguments.
Examples: D custkeyDS e ds extname(custfile:*key) /free CHAIN (keyA : keyB : key3) custrec; CHAIN %KDS(custkeyDS) custrec;
v Data-structure result for externally-described files A data structure can be specified in the result field when using I/O operations for externally-described files. This was available only for program-described files prior to V5R2. Using a data structure can improve performance if there are many fields in the file. v UPDATE operation to update only selected fields A list of fields to be updated can be specified with an UPDATE operation. Tthis could only be done by using exception output prior to V5R2. Example: update record %fields(salary:status). v 31 digit support Supports packed and zoned numeric data with up to 31 digits and decimal places. This is the maximum length supported by DDS. Only 30 digits and decimal places were supported prior to V5R2. v Performance option for FEOD
2-22
What's New
The FEOD operation is enhanced by supporting an extender N which indicates that the operation should simply write out the blocked buffers locally, without forcing a costly write to disk. v Enhanced data area access The DTAARA keyword is enhanced to allow the name and library of the data area to be determined at runtime v New assignment operators The new assignment operators +=, -=, *=, /=, **= allow a variable to be modified based on its old value in a more concise manner.
Example: totals(current_customer) += count;
This statement adds "count" to the value currently in "totals(current_customer)" without having to code "totals(current_customer)" twice. v IFS source files The ILE RPG compiler can compile both main source files and /COPY files from the IFS. The /COPY and /INCLUDE directives are enhanced to support IFS file names. v Program Call Markup Language (PCML) generation The ILE RPG compiler will generate an IFS file containing the PCML, representing the parameters to the program (CRTBNDRPG) or to the exported procedures (CRTRPGMOD).
Table 2-17. Changed Language Elements Since V5R1 Language Unit Built-in functions Element %DEC(expression) %DECH(expression) %FLOAT(expression) %INT(expression) %INTH(expression) %UNS(expression) %UNSH(expression) Definition specification keywords DTAARA({*VAR:}data-area-name) The data area name can be a name, a character literal specifying 'LIBRARY/NAME' or a character variable which will determine the actual data area at runtime. Allowed for data structure specifications. Allowed for subfield specifications. The optional "type" parameter controls which type of field is extracted for the externally-described data structure. The length and number of decimal places can be 31 for packed and zoned fields. In free-form operations, Factor 1 can be a list of key values. When used with externally-described files or record formats, a data structure may be specified in the result field. In free-form calculations, the final argument can contain a list of the fields to be updated. Operation extender N is allowed. This indicates that the unwritten buffers must be made available to the database, but not necessarily be written to disk. Description Can now take parameters of type character.
DIM LIKEDS EXTNAME(filename{:extrecname} {:*ALL|*INPUT|*OUTPUT|*KEY} ) Definition Specifications Operation codes Length and decimal place entries CHAIN, DELETE, READE, READPE, SETGT, SETLL CHAIN, READ, READC, READE, READP, READPE, UPDATE, WRITE UPDATE FEOD
What's New
2-23
What's New
Table 2-17. Changed Language Elements Since V5R1 (continued) Language Unit Calculation specifications Element Length and decimal place entries Description The length and number of decimal places can be 31 for packed and zoned fields.
Table 2-18. New Language Elements Since V5R1 Language Unit Expressions Element Assignment Operators += -= *= /= **= DECPREC(30|31) Description When these assignment operators are used, the target of the operation is also the first operand of the operation. Controls the precision of decimal intermediate values for presentation, for example, for %EDITC and %EDITW Defines a data structure whose subfields are the same as a record format. Returns a result whose bits are on if the corresponding bits of the operands are both on. Returns a result whose bits are the inverse of the bits in the argument. Returns a result whose bits are on if either of the corresponding bits of the operands is on. Returns a result whose bits are on if exactly one of the corresponding bits of the operands is on. Used in free-form "UPDATE to specify the fields to be updated. Used in free-form keyed operation codes CHAIN, SETLL, SETGT, READE and READPE, to indicate that the keys for the operation are in the data structure.
LIKEREC(intrecname{:*ALL| *INPUT|*OUTPUT|*KEY}) %BITAND(expression : expression) %BITNOT(expression) %BITOR(expression : expression) %BITXOR(expression : expression) %FIELDS(name{:name...}) %KDS(data structure)
2-24
What's New
The %DIFF function, for subtracting one date, time, or timestamp value from another. Functions for converting a character string (or date or timestamp) into a date, time, or timestamp: %DATE, %TIME, and %TIMESTAMP. The %SUBDT function, for extracting a subset of a date, time, or timestamp. Functions for allocating or reallocating storage: %ALLOC and %REALLOC. Functions for finding an element in an array: %LOOKUP, %LOOKUPGT, %LOOKUPGE, %LOOKUPLT, and %LOOKUPLE. Functions for finding an element in a table: %TLOOKUP, %TLOOKUPGT, %TLOOKUPGE, %TLOOKUPLT, and %TLOOKUPLE. Functions for verifying that a string contains only specified characters (or finding the first or last exception to this rule): %CHECK and %CHECKR The %XLATE function, for translating a string based on a list of from-characters and to-characters. The %OCCUR function, for getting or setting the current occurrence in a multiple-occurrence data structure. The %SHTDN function, for determining if the operator has requested shutdown. The %SQRT function, for calculating the square root of a number. v A new free-form syntax for calculation specifications. A block of free-form calculation specifcations is delimited by the compiler directives /FREE and /END-FREE. | Note: These directives are no longer needed. See /FREE... /END-FREE on page 3-8. v You can specify the EXTFILE and EXTMBR keywords on the file specification to control which external file is used when a file is opened. v Support for qualified names in data structures: A new definition specification keyword: QUALIFIED. This keyword specifies that subfield names will be qualified with the data structure name. A new definition specification keyword: LIKEDS. This keyword specifies that subfields are replicated from another data structure. The subfield names will be qualified with the new data structure name. LIKEDS is allowed for prototyped parameters; it allows the parameter's subfields to be used directly in the called procedure. The INZ definition specification keyword has been extended to allow a data structure to be initialized based on its parent data structure. v Enhanced error handling: Three new operation codes (MONITOR, ON-ERROR, and ENDMON) allow you to define a group of operations with conditional error handling based on the status code. Other enhancements have been made to this release as well. These include: v You can specify parentheses on a procedure call that has no parameters. v You can specify that a procedure uses ILE C or ILE CL calling conventions, on the EXTPROC definition specification keyword. v The following /DEFINE names are predefined: *VnRnMn, *ILERPG, *CRTBNDRPG, and *CRTRPGMOD. v The search string in a %SCAN operation can now be longer than string being searched. (The string will not be found, but this will no longer generate an error condition.) v The parameter to the DIM, OCCURS, and PERRCD keywords no longer needs to be previously defined. v The %PADDR built-in function can now take either a prototype name or an entry point name as its argument. v A new operation code, ELSEIF, combines the ELSE and IF operation codes without requiring an additional ENDIF.
What's New
2-25
What's New
v The DUMP operation code now supports the A extender, which means that a dump is always produced - even if DEBUG(*NO) was specified. v A new directive, /INCLUDE, is equivalent to /COPY except that /INCLUDE is not expanded by the SQL preprocessor. Included files cannot contain embedded SQL or host variables. v The OFLIND file-specification keyword can now take any indicator, including a named indicator, as an argument. v The LICOPT (licensed internal code options) keyword is now available on the CRTRPGMOD and CRTBNDRPG commands. v The PREFIX file description keyword can now take an uppercase character literal as an argument. The literal can end in a period, which allows the file to be used with qualified subfields. v The PREFIX definition specification keyword can also take an uppercase character literal as an argument. This literal cannot end in a period. The following tables summarize the changed and new language elements, based on the part of the language affected.
Table 2-19. Changed Language Elements Since V4R4 Language Unit Built-in functions Element %CHAR(expression{:format}) Description The optional second parameter specifies the desired format for a date, time, or timestamp. The result uses the format and separators of the specified format, not the format and separators of the input. This function can now take either a prototype name or an entry point name as its argument. Specifies that a Java method is called. Specifies a procedure that uses ILE CL conventions for return values. Specifies a procedure that uses ILE C conventions with parameter widening. Specifies a procedure that uses ILE C conventions without parameter widening. Specifies that a data structure defined with the LIKEDS keyword inherits the initialization from its parent data structure. Specifies that an object has the same class as another object. Prefixes the subfields with the specified character literal, optionally replacing the specified number of characters. This keyword can now take any named indicator as a parameter. Prefixes the subfields with the specified character literal, optionally replacing the specified number of characters. This operation code can now take the A extender, which causes a dump to be produced even if DEBUG(*NO) was specified.
LIKE(object-name) PREFIX(character-literal{:number})
OFLIND(name) PREFIX(character-literal{:number})
Operation codes
DUMP (A)
2-26
What's New
Table 2-20. New Language Elements Since V4R4 Language Unit Data types Compiler directives Element Object /FREE ... /END-FREE /INCLUDE Description Used for Java objects The /FREE... /END-FREE compiler directives denote a free-form calculation specifications block. Equivalent to /COPY, except that it is not expanded by the SQL preprocessor. Can be used to inlcude nested files that are within the copied file. The copied file cannot have embedded SQlL or host variables. Specifies the class for an object. Specifies that a data structure, prototyped parameter, or return value inherits the subfields of another data strucutre. Specifies that the subfield names in a data structure are qualified with the data structure name. Specifies which file is opened. The value can be a literal or a variable. The default file name is the name specified in position 7 of the file specification. The default library is *LIBL. Specifies which member is opened. The value can be a literal or a variable. The default is *FIRST.
CLASS(*JAVA:class-name) LIKEDS(dsname)
QUALIFIED
EXTFILE(filename)
EXTMBR(membername)
What's New
2-27
What's New
Table 2-20. New Language Elements Since V4R4 (continued) Language Unit Built-in functions Element %ALLOC(num) %CHECK(comparator:base{:start}) %CHECKR(comparator:base{:start}) %DATE(expression{:date-format}) %DAYS(num) %DIFF(op1:op2:unit) Description Allocates the specified amount of storage. Finds the first character in the base string that is not in the comparator. Finds the last character in the base string that is not in the comparator. Converts the expression to a date. Converts the number to a duration, in days. Calculates the difference (duration) between two date, time, or timestamp values in the specified units. Converts the number to a duration, in hours. Finds the specified argument, or the specified type of near-match, in the specified array. Converts the number to a duration, in minutes. Converts the number to a duration, in months. Converts the number to a duration, in microseconds. Sets or gets the current position of a multiple-occurrence data structure. Reallocates the specified amount of storage for the specified pointer. Converts the number to a duration, in seconds. Checks if the system operator has requested shutdown. Calculates the square root of the specified number. Extracts the specified portion of a date, time, or timestamp value. Returns an Object value that contains a reference to the class instance on whose behalf the native method is being called. Converts the expression to a time. Converts the expression to a timestamp. Finds the specified argument, or the specified type of near-match, in the specified table. Translates the specified string, based on the from-string and to-string. Converts the number to a duration, in years.
%HOURS(num) %LOOKUPxx(arg:array{:startindex {:numelems}}) %MINUTES(num) %MONTHS(num) %MSECONDS(num) %OCCUR(dsn-name) %REALLOC(pointer:number) %SECONDS(num) %SHTDN %SQRT(numeric-expression) %SUBDT(value:unit) %THIS
2-28
What's New
Table 2-20. New Language Elements Since V4R4 (continued) Language Unit Operation codes Element MONITOR ON-ERROR ENDMON ELSEIF CRTBNDRPG and LICOPT(options) CRTRPGMOD keywords Description Begins a group of operations with conditional error handling. Performs conditional error handling, based on the status code. Ends a group of operations with conditional error handling. Equivalent to an ELSE operation code followed by an IF operation code. Specifies Licensed Internal Code options.
What's New
2-29
What's New
*SRCSTMT allows you to assign statement numbers for debugging from the source IDs and SEU sequence numbers in the compiler listing. (The statement number is used to identify errors in the compiler listing by the debugger, and to identify the statement where a run-time error occurs.) *NOSRCSTMT specifies that statement numbers are associated with the Line Numbers of the listing and the numbers are assigned sequentially. Now you can choose not to generate breakpoints for input and output specifications in the debug view with *NODEBUGIO. If this option is selected, a STEP on a READ statement in the debugger will step to the next calculation, rather than stepping through the input specifications. v New special words for the INZ definition specification keyword: INZ(*EXTDFT) allows you to use the default values in the DDS for initializing externally described data structure subfields. Character variables initialized by INZ(*USER) are initialized to the name of the current user profile. v The new %XFOOT built-in function sums all elements of a specified array expression. v The new EVALR operation code evaluates expressions and assigns the result to a fixed-length character or graphic result. The assignment right-adjusts the data within the result. v The new FOR operation code performs an iterative loop and allows free-form expressions for the initial, increment, and limit values. v The new LEAVESR operation code can be used to exit from any point within a subroutine. v The new *NEXT parameter on the OVERLAY(name:*NEXT) keyword indicates that a subfield overlays another subfield at the next available position. v The new *START and *END values for the SETLL operation code position to the beginning or end of the file. v The ability to use hexadecimal literals with integer and unsigned integer fields in initialization and free-form operations, such as EVAL, IF, etc. v New control specification keyword OPENOPT{(*NOINZOFL | *INZOFL)} to indicate whether the overflow indicators should be reset to *OFF when a file is opened. v Ability to tolerate pointers in teraspace a memory model that allows more than 16 megabytes of contiguous storage in one allocation. The following tables summarize the changed and new language elements, based on the part of the language affected.
Table 2-21. Changed Language Elements Since V4R2 Language Unit Control specification keywords Element OPTION(*{NO}SRCSTMT) Description *SRCSTMT allows you to request that the compiler use SEU sequence numbers and source IDs when generating statement numbers for debugging. Otherwise, statement numbers are associated with the Line Numbers of the listing and the numbers are assigned sequentially. *{NO}DEBUGIO, determines if breakpoints are generated for input and output specifications.
OPTION(*{NO}DEBUGIO)
2-30
What's New
Table 2-21. Changed Language Elements Since V4R2 (continued) Language Unit Definition specification keywords Element INZ(*EXTDFT) Description All externally described data structure subfields can now be initialized to the default values specified in the DDS. Any character field or subfield can be initialized to the name of the current user profile. The special value *NEXT indicates that the subfield is to be positioned at the next available position within the overlayed field. The new OPTIONS(*RIGHTADJ) specified on a value or constant parameter in a function prototype indicates that the character, graphic, or UCS-2 value passed as a parameter is to be right adjusted before being passed on the procedure call. Added to the list of allowed values for internal data types to support 1-byte and 8-byte integer and unsigned data. Added to the list of allowed internal data types on the definition specifications. The UCS-2 (Unicode) character set can encode the characters for many written languages. The field is a character field whose characters are two bytes long. UCS-2 format added to the list of allowed data formats on the input and output specifications for program described files. *NOSRCSTMT, *SRCSTMT, *NODEBUGIO, and *DEBUGIO have been added to the OPTION parameter on the CRTBNDRPG and CRTRPGMOD commands.
INZ(*USER) OVERLAY(name:*NEXT)
3 and 20 digits allowed for I and U data types C (UCS-2 fixed or variable-length format)
Data format
Command parameter
Table 2-22. New Language Elements Since V4R2 Language Unit Control specification keywords Element Description
CCSID(*GRAPH: *IGNORE | *SRC | Sets the default graphic CCSID for the module. number) This setting is used for literals, compile-time data and program-described input and output fields and definitions. The default is *IGNORE. CCSID(*UCS2: number) Sets the default UCS-2 CCSID for the module. This setting is used for literals, compile-time data and program-described input and output fields and definitions. The default is 13488. Specifies the decimal precision of integer and unsigned intermediate values in binary arithmetic operations in expressions. The default, INTPREC(10), indicates that 10-digit precision is to be used. Indicates whether the overflow indicators should be reset to *OFF when a file is opened. Indicates that the module is enabled to run in a multithreaded environment. Access to the procedures in the module is to be serialized.
What's New
INTPREC(10 | 20)
2-31
What's New
Table 2-22. New Language Elements Since V4R2 (continued) Language Unit Definition specification keywords Built-in functions Element CCSID(number | *DFT) %DIV(n:m) Description Sets the graphic and UCS-2 CCSID for the definition. Performs integer division on the two operands n and m; the result is the integer portion of n/m. The operands must be numeric values with zero decimal positions. Converts to graphic data from single-byte character, graphic, or UCS-2 data. Performs the integer remainder operation on two operands n and m; the result is the remainder of n/m. The operands must be numeric values with zero decimal positions. Converts to UCS-2 data from single-byte character, graphic, or UCS-2 data. Produces the sum of all the elements in the specified numeric array expression. Evaluates an assignment statement of the form result=expression. The result will be right-justified. Begins a group of operations and indicates the number of times the group is to be processed. The initial, increment, and limit values can be free-form expressions. ENDFOR ends a group of operations started by a FOR operation. Used to exit from anywhere within a subroutine.
FOR
ENDFOR LEAVESR
2-32
What's New
Compile options, specified through the CRTBNDRPG and CRTRPGMOD commands, can now be specified through the control specification keywords. These compile options will be used on every compile of the program. In addition, the following new function has been added: v Support for import and export of procedures and variables with mixed case names v Ability to dynamically set the DECEDIT value at runtime v Built-in functions %CHAR and %REPLACE have been added to make string manipulation easier v New support for externally defined *CMDY, *CDMY, and *LONGJUL date data formats v An extended range for century date formats Ability to define indicator variables Ability to specify the current data structure name as the parameter for the OVERLAY keyword New status code 115 has been added to indicate variable-length field errors Support for application profiling Ability to handle packed-decimal data that is not valid when it is retrieved from files using FIXNBR(*INPUTPACKED) v Ability to specify the BNDDIR command parameter on the CRTRPGMOD command. v v v v v The following tables summarize the changed and new language elements, based on the part of the language affected.
Table 2-23. Changed Language Elements Since V3R7 Language Unit Control specification keywords Definition specification keywords Element DECEDIT(*JOBRUN | 'value') Description The decimal edit value can now be determined dynamically at runtime from the job or system value. Users can now access logical data areas. The external name of the variable being exported can now be specified as a parameter for this keyword. The external name of the variable being imported can now be specified as a parameter for this keyword. The name parameter can now be the name of the current data structure. The valid values for the century character 'c' are now: c Years ----------------------0 1900-1999 1 2000-2099 . . . . . . 9 2800-2899 Internal data type N (Indicator format) Added to the list of allowed internal data types on the definition specifications. Defines character data in the indicator format. Indicator format added to the list of allowed data formats on the input and output specifications for program described files.
IMPORT {(external_name)}
Data format
N (Indicator format)
What's New
2-33
What's New
Table 2-23. Changed Language Elements Since V3R7 (continued) Language Unit Data Attribute Element *VAR Description Added to the list of allowed data attributes on the input and output specifications for program described files. It is used to specify variable-length fields. The *INPUTPACKED parameter has been added to handle packed-decimal data that is not valid.
Command parameter
FIXNBR
Table 2-24. New Language Elements Since V3R7 Language Unit Control specification keywords New ACTGRP(*NEW | *CALLER | 'activation- group-name') ALWNULL(*NO | *INPUTONLY | *USRCTL) AUT(*LIBRCRTAUT | *ALL | *CHANGE | *USE | *EXCLUDE | 'authorization-list-name') Description The ACTGRP keyword allows you to specify the activation group the program is associated with when it is called. The ALWNULL keyword specifies how you will use records containing null-capable fields from externally described database files. The AUT keyword specifies the authority given to users who do not have specific authority to the object, who are not on the authorization list, and whose user group has no specific authority to the object. The BNDDIR keyword specifies the list of binding directories that are used in symbol resolution. The CVTOPT keyword is used to determine how the ILE RPG compiler handles date, time, timestamp, graphic data types, and variable-length data types that are retrieved from externally described database files. The DFTACTGRP keyword specifies the activation group in which the created program will run when it is called. The ENBPFRCOL keyword specifies whether performance collection is enabled. The FIXNBR keyword specifies whether decimal data that is not valid is fixed by the compiler. The GENLVL keyword controls the creation of the object. The INDENT keyword specifies whether structured operations should be indented in the source listing for enhanced readability. The LANGID keyword indicates which language identifier is to be used when the sort sequence is *LANGIDUNQ or *LANGIDSHR. The OPTIMIZE keyword specifies the level of optimization, if any, of the object. The OPTION keyword specifies the options to use when the source member is compiled.
DFTACTGRP(*YES | *NO)
LANGID(*JOBRUN | *JOB | 'language-identifier') OPTIMIZE(*NONE | *BASIC | *FULL) OPTION(*{NO}XREF *{NO}GEN *{NO}SECLVL *{NO}SHOWCPY *{NO}EXPDDS *{NO}EXT *{NO}SHOWSKP) PRFDTA(*NOCOL | *COL)
The PRFDTA keyword specifies whether the collection of profiling data is enabled.
2-34
What's New
Table 2-24. New Language Elements Since V3R7 (continued) Language Unit New SRTSEQ(*HEX | *JOB | *JOBRUN | *LANGIDUNQ | *LANGIDSHR | 'sort-table-name') TEXT(*SRCMBRTXT | *BLANK | 'description') TRUNCNBR(*YES | *NO) Description The SRTSEQ keyword specifies the sort sequence table that is to be used in the ILE RPG source program. The TEXT keyword allows you to enter text that briefly describes the object and its function. The TRUNCNBR keyword specifies if the truncated value is moved to the result field or if an error is generated when numeric overflow occurs while running the object. The USRPRF keyword specifies the user profile that will run the created program object. The INDDS keyword lets you associate a data structure name with the INDARA indicators for a workstation or printer file. Defines variable-length fields when specified on character data or graphic data. Returns the value in a character data type. Returns '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; otherwise, it returns '0'. Returns '1' if the most recent SETLL (for a particular file, if specified) or LOOKUP operation found an exact match; otherwise, it returns '0'. Returns '1' if the most recent operation code with extender 'E' specified resulted in an error; otherwise, it returns '0'. Returns '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 and SCAN); otherwise, it returns '0'. Returns '1' if the specified file is open and '0' if the specified file is closed. Returns the string produced by inserting a replacement string into a source string, starting at the start position and replacing the specified number of characters. If no program or file error occurred since the most recent operation code with extender 'E' specified, it returns 0. If an error occurred, it returns the most recent value set for any program or file status. If a file is specified, the value returned is the most recent status for that file. Allows for error handling using the %ERROR and %STATUS built-in functions on the CALLP operation and all operations that allow error indicators.
USRPRF(*USER | *OWNER) File Description Specification keywords Definition specification keywords Built-in functions INDDS( data_structure_name)
%EQUAL{file name}
%ERROR
%FOUND{file name}
%OPEN(file name) %REPLACE(replacement string: source string {:start position {:source length to replace}}) %STATUS{file name}
What's New
2-35
What's New
Table 2-24. New Language Elements Since V3R7 (continued) Language Unit New century formats New *CMDY (cmm/dd/yy) *CDMY (cdd/mm/yy) New 4-digit year format Command parameters *LONGJUL (yyyy/ddd) PRFDTA BNDDIR Description To be used by the MOVE, MOVEL, and TEST operations. To be used by the MOVE, MOVEL, and TEST operations. To be used by the MOVE, MOVEL, and TEST operations. The PRFDTA parameter specifies whether the collection of profiling data is enabled. The BNDDIR parameter was previously only allowed on the CRTBNDRPG command and not on the CRTRPGMOD command, now it is allowed on both commands.
2-36
What's New
A number of new built-in functions have been added to the language which improve the following language facilities: editing (%EDITW, %EDITC, %EDITFLT) scanning strings (%SCAN) type conversions (%INT, %FLOAT, %DEC, %UNS) type conversions with half-adjust (%INTH, %DECH, %UNSH) precision of intermediate results for decimal expressions (%DEC) length and decimals of variables and expressions (%LEN, %DECPOS) absolute value (%ABS) set and test null-capable fields (%NULLIND) handle null terminated strings (%STR) v Conditional compilation RPG IV has been extended to support conditional compilation. This support will include the following: defining conditions (/DEFINE, /UNDEFINE), testing conditions (/IF, /ELSEIF, /ELSE, /ENDIF) stop reading current source file (/EOF) a new command option (DEFINE) to define up to 32 conditions on the CRTBNDRPG and CRTRPGMOD commands. v Date enhancements Several enhancements have been made to improve date handling operations. The TIME operation code is extended to support Date, Time or Timestamp fields in the result field. Moving dates or times from and to character fields no longer requires separator characters. Moving UDATE and *DATE fields no longer requires a format code to be specified. Date fields can be initialized to the system (*SYS) or job (*JOB) date on the definition specifications. v Character comparisons with alternate collating sequence Specific character variables can be defined so that the alternate collating sequence is not used in comparisons. v Nested /COPY members You can now nest /COPY directives. That is, a /COPY member may contain one (or more) /COPY directives which can contain further /COPY directives and so on. v Storage management You can now use the new storage management operation codes to allocate, reallocate and deallocate storage dynamically. v Status codes for storage management and float underflow errors. Two status codes 425 and 426 have been added to indicate storage management errors. Status code 104 was added to indicate that an intermediate float result is too small. The following tables summarize the changed and new language elements, based on the part of the language affected.
Table 2-25. Changed Language Elements Since V3R6 Language Unit Definition specification keywords Element ALIGN Description ALIGN can now be used to align float subfields along with the previously supported integer and unsigned alignment. The *STRING option allows you to pass a character value as a null-terminated string.
What's New
2-37
What's New
Table 2-25. Changed Language Elements Since V3R6 (continued) Language Unit Record address type Element F (Float format) Description Added to the list of allowed record address types on the file description specifications. Signals float processing for a program described file. Added to the list of allowed internal data types on the definition specifications. Defines a floating point standalone field, parameter, or data structure subfield. Added to the list of allowed data formats on the input and output specifications for program described files.
F (Float format)
Data format
F (Float format)
Table 2-26. New Language Elements Since V3R6 Language Unit Control specification keywords New COPYNEST('1-2048') EXPROPTS(*MAXDIGITS | *RESDECPOS) FLTDIV{(*NO | *YES)} Definition specification keywords Built-in functions ALTSEQ(*NONE) Description Specifies the maximum depth for nesting of /COPY directives. Expression options for type of precision (default or "Result Decimal Position" precision rules) Indicates that all divide operations in expressions are computed in floating point. Forces the normal collating sequence to be used for character comparison even when an alternate collating sequence is specified. Returns the absolute value of the numeric expression specified as the parameter. Converts the value of the numeric expression to decimal (packed) format with the number of digits and decimal positions specified as parameters. %DECH is the same as %DEC, but with a half adjust applied. Returns the number of decimal positions of the numeric variable or expression. The value returned is a constant, and may be used where a constant is expected. This function returns a character result representing the numeric value edited according to the edit code. Converts the value of the numeric expression to the character external display representation of float. This function returns a character result representing the numeric value edited according to the edit word. Converts the value of the numeric expression to float format. Converts the value of the numeric expression to integer. Any decimal digits are truncated with %INT and rounded with %INTH. Returns the number of digits or characters of the variable expression.
%DECPOS
%EDITC
%EDITFLT
%EDITW
%LEN
2-38
What's New
Table 2-26. New Language Elements Since V3R6 (continued) Language Unit New %NULLIND %SCAN %STR Description Used to query or set the null indicator for null-capable fields. Returns the first position of the search argument in the source string, or 0 if it was not found. Used to create or use null-terminated strings, which are very commonly used in C and C++ applications. Converts the value of the numeric expression to unsigned format. Any decimal digits are truncated with %UNS and rounded with %UNSH. Sets pointer to *NULL after successful DEALLOC Default precision rules No intermediate value will have fewer decimal positions than the result ("Result Decimal Position" precision rules) Used to allocate storage dynamically. Used to deallocate storage dynamically. Used to reallocate storage dynamically.
N M R
Operation codes
What's New
2-39
What's New
The run-time behavior of the main procedure in a module is the same as that of a V3R1 procedure. The run-time behavior of any subsequent procedures differs somewhat from a V3R1 program, most notably in the areas of procedure end and exception handling. These differences arise because there is no cycle code that is generated for these procedures. Other enhancements have been made to for this release as well. These include: v Support for two new integer data types: signed integer (I), and unsigned integer (U) The use of the integer data types provides you with a greater range of values than the binary data type. Integer data types can also improve performance of integer computations. v *CYMD support for the MOVE, MOVEL, and TEST operations You can now use the *CYMD date format in certain operations to work with system values that are already in this data format. v Ability to copyright your programs and modules by using the COPYRIGHT keyword on the control specification The copyright information that is specified using this keyword becomes part of the DSPMOD, DSPPGM, or DSPSRVPGM information. v User control of record blocking using keyword BLOCK You can request record blocking of DISK or SEQ files to be done even when SETLL, SETGT, or CHAIN operations are used on the file. You can also request that blocking not be done. Use of blocking in these cases may significantly improve runtime performance. v Improved PREFIX capability Changes to the PREFIX keyword for either file-description and definition specifications allow you to replace characters in the existing field name with the prefix string. v Status codes for trigger program errors Two status codes 1223 and 1224 have been added to indicate trigger program errors. The following tables summarize the changed and new language elements, based on the part of the language affected.
Table 2-27. Changed Language Elements Since V3R1 Language Unit File description specification keywords Definition specification keywords Element PREFIX(prefix_string {:nbr_of_char_ replaced}) CONST{(constant)} Description Allows prefixing of string to a field name or a partial rename of the field name Specifies the value of a named constant, or indicates that a prototyped parameter that is passed by reference has a constant value Allows prefixing of string to a field name or a partial rename of the field name Returns control to the caller, and returns a value, if specified
Table 2-28. New Language Elements Since V3R1 Language Unit Control specification keywords New COPYRIGHT('copyright string') EXTBININT{(*NO | *YES)} Description Allows you to associate copyright information with modules and programs Specifies that binary fields in externally-described files be assigned an integer format during program processing Indicates that the module has only subprocedures
NOMAIN
2-40
What's New
Table 2-28. New Language Elements Since V3R1 (continued) Language Unit File description specification keywords Definition specification keywords New BLOCK(*YES |*NO) ALIGN EXTPGM(name) EXTPROC(name) OPDESC OPTIONS(*NOPASS *OMIT *VARSIZE) STATIC VALUE Built-in functions Operation codes Specification type Definition type %PARMS CALLP Procedure specification PR PI blank in positions 24-25 Description Allows you to control whether record blocking occurs (assuming other conditions are met) Specifies whether integer or unsigned fields should be aligned Indicates the external name of the prototyped program Indicates the external name of the prototyped procedure Indicates whether operational descriptors are to be passed for the prototyped bound call Specifies various options for prototyped parameters Specifies that the local variable is to use static storage Specifies that the prototyped parameter is to be passed by value Returns the number of parameters passed on a call Calls a prototyped program or procedure Signals the beginning and end of a subprocedure definition Signals the beginning of a prototype definition Signals the beginning of a procedure interface definition Defines a prototyped parameter
What's New
2-41
What's New
2-42
RPG IV Concepts
General concepts for RPG IV This section describes some of the basics of RPG IV: v v v v v v v Symbolic names Compiler directives RPG IV program cycle Indicators Error Handling Subprocedures General file considerations
Symbolic Names
A symbolic name is a name that uniquely identifies a specific entity in a program or procedure. In the RPG IV language, symbolic names are used for the following: v Arrays (see Array Names on page 3-2) v Conditional compile names (see Conditional Compile Names on page 3-2) v v v v v v v Data structures (see Data Structure Names on page 3-2) Exception output records (see EXCEPT Names on page 3-2) Fields (see Field Names on page 3-2) Key field lists (see KLIST Names on page 3-2) Labels (see Labels on page 3-2) Named constants (see Named Constants on page 4-8) Parameter lists (see PLIST Names on page 3-2)
v Prototype names (see Prototype Names on page 3-3) v Record names (see Record Names on page 3-3) v Subroutines (see Subroutine Names on page 3-3) v Tables (see Table Names on page 3-3). The following rules apply to all symbolic names except for deviations noted in the description of each symbolic name: v The first character of the name must be alphabetic. This includes the characters $, #, and @.
Copyright IBM Corp. 1994, 2014
3-1
Symbolic Names
v The remaining characters must be alphabetic or numeric. This includes the underscore (_). v The name must be left-adjusted in the entry on the specification form except in fields which allow the name to float (definition specification, keyword fields, and the extended factor 2 field). v A symbolic name cannot be an RPG IV reserved word. v A symbolic name can be from 1 to 4096 characters. The practical limits are determined by the size of the entry used for defining the name. A name that is up to 15 characters can be specified in the Name entry of the definition or procedure specification. For names longer than 15 characters, use a continuation specification. For more information, see About Specifications on page 5-1. v A symbolic name must be unique within the procedure in which it is defined.
Array Names
The following additional rule applies to array names: v An array name in a standalone field cannot begin with the letters TAB. Array names may begin with TAB if they are either prototyped parameters or data structures defined with the DIM keyword.
EXCEPT Names
An EXCEPT name is a symbolic name assigned to an exception output record. The following additional rule applies to EXCEPT names: v The same EXCEPT name can be assigned to more than one output record.
Field Names
The following additional rules apply to field names: v A field name can be defined more than once if each definition using that name has the same data type, the same length, and the same number of decimal positions. All definitions using the same name refer to a single field (that is, the same area in storage). However, it can be defined only once on the definition specification. v A field can be defined as a data structure subfield only once unless the data structure is qualified (defined with QUALIFIED or LIKEDS). In this case, when the subfield is used, it must be qualified (specified in the form dsname.subfieldname). v A subfield name cannot be specified as the result field on an *ENTRY PLIST parameter.
KLIST Names
A KLIST name is a symbolic name assigned to a list of key fields.
Labels
A label is a symbolic name that identifies a specific location in a program (for example, the name assigned to a TAG or ENDSR operation).
Named Constants
A named constant is a symbolic name assigned to a constant.
PLIST Names
A PLIST name is a symbolic name assigned to a list of parameters.
3-2
Symbolic Names
Prototype Names
# # # # A prototype name is a symbolic name assigned to a prototype definition. This name must be used when calling a prototyped procedure or program. A prototype maybe explicitly specified, or it may be implicitly generated by the compiler from the procedure interface when the procedure is defined in the same module as the call.
Record Names
A record name is a symbolic name assigned to a record format in an externally described file. The following additional rules apply to record names in an RPG IV program: v If the file is qualified, due to the QUALIFIED or LIKEFILE keyword on the File specification, the record name is specified as a qualified name in the form FILENAME.FMTNAME. The record name must be unique within the other record names of the file. v If the file is not qualified, the record name is specified without qualification in the form FMTNAME. If the file is a global file, the record name must be unique within the other global names. If the file is a local file in a subprocedure, the record name must be unique within the other local names. Note: See RENAME(Ext_format:Int_format) on page 5-69 for information on how to handle the situation where the record name conflicts with other names in your RPG program.
Subroutine Names
The name is defined in factor 1 of the BEGSR (begin subroutine) operation.
Table Names
The following additional rules apply to table names: v A table name can contain from 3 to 10 characters. v A table name must begin with the letters TAB. v A table cannot be defined in a subprocedure.
3-3
3-4
RPG IV Concepts
3-5
Note that the DATEDIT keyword also controls the format of the Y edit code. If this keyword is not specified, the default is *MDY. v For an interactive job or batch program, the user date special words are set to the value of the job date when the program starts running in the system. The value of the user date special words are not updated during program processing, even if the program runs past midnight or if the job date is changed. Use the TIME operation code to obtain the time and date while the program is running. v UMONTH, *MONTH, UDAY, *DAY, and UYEAR when specified in positions 30 through 43 of the output specifications, print a 2-position numeric date field. *YEAR can be used to print a 4-position numeric date field. Use UMONTH or *MONTH to print the month only, UDAY or *DAY to print the day only, and UYEAR or *YEAR to print the year only. v UDATE and *DATE can be edited when they are written if the Y edit code is specified in position 44 of the output specifications. The DATEDIT(fmt{separator}) on page 5-23 keyword on the control specification determines the format and the separator character to be inserted; for example, 12/31/88, 31.12.88., 12/31/1988. v UMONTH, *MONTH, UDAY, *DAY, UYEAR and *YEAR cannot be edited by the Y edit code in position 44 of the output specifications. v The user date fields cannot be modified. This means they cannot be used: In the result field of calculations As factor 1 of PARM operations As the factor 2 index of LOOKUP operations With blank after in output specifications As input fields v The user date special words can be used in factor 1 or factor 2 of the calculation specifications for operation codes that use numeric fields. v User date fields are not date data type fields but are numeric fields.
PAGE, PAGE1-PAGE7
PAGE is used to number the pages of a report, to serially number the output records in a file, or to sequentially number output fields. It does not cause a page eject. The eight possible PAGE fields (PAGE, PAGE1, PAGE2, PAGE3, PAGE4, PAGE5, PAGE6, and PAGE7) may be needed for numbering different types of output pages or for numbering pages for different printer files. PAGE fields can be specified in positions 30 through 43 of the output specifications or in the input or calculation specifications.
3-6
PAGE, PAGE1-PAGE7
*...1....+....2....+....3....+....4....+....5....+....6....+....7... IFilename++SqNORiPos1+NCCPos2+NCCPos3+NCC................................ I........................Fmt+SPFrom+To+++DcField+++++++++L1M1FrPlMnZr.... IINPUT PG 50 1 CP I 2 5 0PAGE Figure 3-1. Page Record Description
*...1....+....2....+....3....+....4....+....5....+....6....+....7... OFilename++DF..N01N02N03Excnam++++B++A++Sb+Sa+........................... O..............N01N02N03Field+++++++++YB.End++PConstant/editword/DTformat O* When indicator 15 is on, the PAGE field is set to zero and 1 is O* added before the field is printed. When indicator 15 is off, 1 O* is added to the contents of the PAGE field before it is printed. OPRINT H L1 01 O 15 PAGE 1 75 Figure 3-2. Resetting the PAGE Fields to Zero
Compiler Directives
The compiler directive statements /TITLE, /EJECT, /SPACE, /COPY, and /INCLUDE allow you to specify heading information for the compiler listing, to control the spacing of the compiler listing, and to insert records from other file members during a compile. The conditional compilation directive statements /DEFINE, /UNDEFINE, /IF, /ELSEIF, /ELSE, /ENDIF, and /EOF allow you to select or omit source records. The compiler directive statements must precede any compile-time array or table records, translation records, and alternate collating sequence records (that is, ** records). Note: The compiler directive statements /FREE and /END-FREE are no longer used. If you specify them, they will be ignored. See /FREE... /END-FREE on page 3-8.
RPG IV Concepts
3-7
PAGE, PAGE1-PAGE7
Directives can begin in column 7 or later. | All directives can be specified within a single fixed-form statement, and between any statements. | No directive can be specified within a single free-form calculation statement. | The /IF, /ELSEIF, /ELSE, and /ENDIF directives can be specified within a single free-form control, file, | definition, or procedure statement. No other directives can be specified within these statements. Within a free-form statement, when a line begins with what appears to be a directive that is not allowed within that statement, it is interpreted as a slash followed by a name. For example, in the following statement, "/TITLE" is interpreted as division by a variable called "TITLE".
x = y /title + 5;
/FREE... /END-FREE
| In earlier releases, the /FREE compiler directive specified the beginning of a free-form calculation | specifications block. /END-FREE specified the end of the block. | If you code the /FREE or /END-FREE directive, it will be ignored, but the syntax of the directive will be | checked. The columns following the directive must be blank. See Free-Form Statements on page 5-3 for | information on free-form statements.
/TITLE
Use the compiler directive /TITLE to specify heading information (such as security classification or titles) that is to appear at the top of each page of the compiler listing. | /TITLE begins in column 7 or later. It must be followed by a blank. The data following the blank is | printed at the top of each subsequent page of the listing. | /TITLE cannot be coded within a free-form statement. A program can contain more than one /TITLE statement. Each /TITLE statement provides heading information for the compiler listing until another /TITLE statement is encountered. A /TITLE statement must be the first RPG specification encountered to print information on the first page of the compiler listing. The information specified by the /TITLE statement is printed in addition to compiler heading information. The /TITLE statement causes a skip to the next page before the title is printed. The /TITLE statement is not printed on the compiler listing.
/EJECT
| /EJECT begins in column 7 or later. It must be followed by at least two blanks. The remaining columns | can contain comments. | /EJECT cannot be coded within a free-form statement. | Use /EJECT to indicate that subsequent specifications are to begin on a new page of the compiler listing. | If the spool file is already at the top of a new page, /EJECT will not advance to a new page. /EJECT is | not printed on the compiler listing.
/SPACE
Use the compiler directive /SPACE to control line spacing within the source section of the compiler listing.
3-8
/SPACE
| | | | | | | /SPACE begins in column 7 or later. It must be followed by exactly one blank, and then followed by a positive integer value from 1 through 112 that defines the number of lines to space on the compiler listing, followed by at least two blanks. The remaining columns can contain comments. /SPACE cannot be coded within a free-form statement. If the number of lines is greater than 112, 112 will be used as the /SPACE value. If the number of lines is greater than the number of lines remaining on the current page, subsequent specifications begin at the top of the next page. /SPACE is not printed on the compiler listing, but is replaced by the specified line spacing. The line spacing caused by /SPACE is in addition to the two lines that are skipped between specification types.
/COPY or /INCLUDE
The /COPY and /INCLUDE directives have the same purpose and the same syntax, but are handled differently by the SQL precompiler. If your program does not have embedded SQL, you can freely choose which directive to use. If your program has embedded SQL, see Using /COPY, /INCLUDE in Source Files with Embedded SQL on page 3-11 for information about which directive to use. The /COPY and /INCLUDE compiler directives cause records from other files to be inserted, at the point where the directive occurs, with the file being compiled. The inserted files may contain any valid specification including /COPY and /INCLUDE up to the maximum nesting depth specified by the COPYNEST keyword (32 when not specified). /COPY and /INCLUDE files can be either physical files or IFS files. To specify a physical file, code your /COPY and /INCLUDE statement in the following way : v /COPY or /INCLUDE followed by exactly one space followed by the file name or path v when specifying a physical file, the library, file, and member name, can be in one of these formats:
libraryname/filename,membername filename,membername membername
A member name must be specified. If a file name is not specified, QRPGLESRC is assumed. If a library is not specified, the library list is searched for the file. All occurrences of the specified source file in the library list are searched for the member until it is located or the search is complete. If a library is specified, a file name must also be specified. v When specifying an IFS (Integrated File System) file, the path can be either absolute (beginning with /) or relative. The path can be enclosed in single or double quotes. If the path contains blanks, it must be enclosed in quotes. If the path does not end with a suffix (for example ".txt"), the compiler will search for the file as named, and also for files with suffixes of ".rpgle" or ".rpgleinc". See the Rational Development Studio for i: ILE RPG Programmer's Guide for information on using IFS /COPY files. v Optionally, at least one space and a comment. Tip: To facilitate application maintenance, you may want to place the prototypes of exported procedures in a separate source member. If you do, be sure to place a /COPY or /INCLUDE directive for that member in both the module containing the exported procedure and any modules that contain calls to the exported procedure.
RPG IV Concepts
3-9
/COPY or /INCLUDE
Figure 3-3 shows some examples of the /COPY and /INCLUDE directive statements.
C/COPY MBR1 1 2 3 4
I/INCLUDE SRCFIL,MBR2
O/COPY SRCLIB/SRCFIL,MBR3
O/COPY dir1/dir2/file.rpg
O/COPY "ifs file containing blanks" O/COPY ifs file containing blanks
8 8
Figure 3-3. Examples of the /COPY and /INCLUDE Compiler Directive Statements
Copies from member MBR1 in source file QRPGLESRC. The current library list is used to search for file QRPGLESRC. If the file is not found in the library list, the search will proceed to the IFS, looking for file MBR1, MBR1.rpgle or MBR1.rpgleinc in the include search path. See the Rational Development Studio for i: ILE RPG Programmer's Guide for information on using IFS source files. Copies from member MBR2 in file SRCFIL. The current library list is used to search for file SRCFIL. Note that the comma is used to separate the file name from the member name. If the file is not found in the library list, the search will proceed to the IFS, looking for file SRCFIL, MBR1 in the include search path, possibly with the .rpgle or .rpgleinc suffixes. Copies from member MBR3 in file SRCFIL in library SRCLIB or from the IFS file SRCFIL, MBR3 in directory SRCLIB. Copies from member "MBR3" in file "SRC>3" in library "SRCLIB!" Copies from the IFS file file.rpg in directory /dir1/dir2. Copies from file, or file.rpgleinc or file.rpgle in directory /dir1/dir2 Copies from the IFS file file.rpg in directory dir1/dir2, searching for directory dir1/dir2 using the IFS search path. Copies from a file whose name contains blanks.
3 4 5 6 7 8
3-10
/COPY or /INCLUDE
For an example of how to prevent multiple inclusion, see Figure 3-4 on page 3-15.
Defining Conditions
Condition-names can be added to or removed from a list of currently defined conditions using the defining condition directives /DEFINE and /UNDEFINE. /DEFINE: The /DEFINE compiler directive defines conditions for conditional compilation. The entries in the condition-name area are free-format (do not have to be left justified). | | | | | /DEFINE must be followed by at least one space, and then the condition-name must be specified on the same line. The remainder of the line must be blank. In fixed-form, /DEFINE must begin in column 7. /DEFINE cannot be specified within a free-form statement. However, between free-form statements, /DEFINE can begin in column 7 or later. The /DEFINE directive adds a condition-name to the list of currently defined conditions. A subsequent /IF DEFINED(condition-name) would be true. A subsequent /IF NOT DEFINED(condition-name) would be false. Note: The command parameter DEFINE can be used to predefine up to 32 conditions on the CRTBNDRPG and CRTRPGMOD commands. /UNDEFINE: Use the /UNDEFINE directive to indicate that a condition is no longer defined. | | | | | /UNDEFINE must be followed by at least one space, and then the condition-name must be specified on the same line. The remainder of the line must be blank. In fixed-form, /UNDEFINE must begin in column 7. /UNDEFINE cannot be specified within a free-form statement. However, between free-form statements, /UNDEFINE can begin in column 7 or later.
RPG IV Concepts
3-11
Predefined Conditions
Several conditions are defined for you by the RPG compiler. These conditions cannot be used with /DEFINE or /UNDEFINE. They can only be used with /IF and /ELSEIF. Conditions Relating to the Environment: *ILERPG This condition is defined if your program is being compiled by the ILE RPG IV compiler (the compiler described in this document).
* This module is to be defined on different platforms. With * the ILE RPG compiler, the BNDDIR keyword is used to * indicate where procedures can be found. With a different * compiler, the BNDDIR keyword might not be valid. /IF DEFINED(*ILERPG) H BNDDIR(QC2LE) /ENDIF
To learn what conditions are available with another version of the RPG IV compiler, consult the reference for the compiler. Conditions Relating to the Command Being Used: *CRTBNDRPG This condition is defined if your program is being compiled by the CRTBNDRPG command, which creates a program.
/IF DEFINED(*CRTBNDRPG) H DFTACTGRP(*NO) /ENDIF
*CRTRPGMOD This condition is defined if your program is being compiled by the CRTRPGMOD command, which creates a module.
* * * * This code might appear in a generic Control specification contained in a /COPY file. The module that contains the main procedure would define condition THIS_IS_MAIN before coding the /COPY directive.
* If the CRTRPGMOD command is not being used, or if * THIS_IS_MAIN is defined, the NOMAIN keyword will not * be used in this Control specification. /IF DEFINED(*CRTRPGMOD) /IF NOT DEFINED(THIS_IS_MAIN) H NOMAIN /ENDIF /ENDIF
Conditions Relating to the Target Release: *VxRxMx This condition is defined if your program is being compiled for a version that is greater than or equal to the release in the condition, starting with *V4R4M0 (Version 4 Release 4 Modification 0).
3-12
Condition Expressions
A condition expression has one of the following forms: v DEFINED(condition-name) v NOT DEFINED(condition-name) The condition expression is free-format but cannot be continued to the next line.
Testing Conditions
Conditions are tested using /IF groups, consisting of an /IF directive, followed by zero or more /ELSEIF directives, followed optionally by an /ELSE directive, followed by an /ENDIF directive. Any source lines except compile-time data, are valid between the directives of an /IF group. This includes nested /IF groups. Note: There is no practical limit to the nesting level of /IF groups. /IF Condition-Expression: The /IF compiler directive is used to test a condition expression for conditional compilation. | | | | | | /IF must be followed by at least one space, and then the condition expression must be specified on the same line. Following the condition expression, the remainder of the line must be blank. In fixed-form, /IF must begin in column 7. /IF can be specified in any free-form statement other than a free-form calculation statement. Within free-form statements, /IF can begin in column 8 or later. See Conditional Directives Within a Free-Form Statement on page 5-4. If the condition expression is true, source lines following the /IF directive are selected to be read by the compiler. Otherwse, lines are excluded until the next /ELSEIF, /ELSE or /ENDIF in the same /IF group. /ELSEIF Condition-Expression: The /ELSEIF compiler directive is used to test a condition expression within an /IF or /ELSEIF group. | | | /ELSEIF must be followed by at least one space, and then the condition expression must be specified on the same line. Following the condition expression, the remainder of the line must be blank. In fixed-form, /ELSEIF must begin in column 7.
RPG IV Concepts
3-13
3-14
The first time this /COPY member is read, XYZ_COPIED will not be defined, so the /EOF will not be considered. The second time this member is read, XYZ_COPIED is defined, so the /EOF is processed. The /IF DEFINED(XYZ_COPIED) ( 3 ) is considered ended, and the file is closed. However, the /IF DEFINED(READ_XYZ) ( 1 ) from the main source member is still active until its own /ENDIF ( 2 ) is reached.
RPG IV Concepts
3-15
3-16
Subprocedure Definition
A subprocedure is a procedure defined after the main source section. A subprocedure differs from a cycle-main procedure in several respects, the main difference being that a subprocedure does not (and cannot) use the RPG cycle while running. # # # # A subprocedure may have a corresponding prototype in the definition specifications of the main source section. If specified, the prototype is used by the compiler to call the program or procedure correctly, and to ensure that the caller passes the correct parameters. If not specified, the prototype is implicitly generated from the procedure interface. Tip: # # # # | | | | | Although it is optional to specify a prototype within the module that defines the procedure, it should not be considered optional when it is exported from the module, and the procedure will be called from other RPG modules. In this case, a prototype should be specified in a copy file and copied into the module that defines the subprocedure and into every module that calls the subprocedure. The following examples show a subprocedure, highlighting the different parts of it. It is shown first using free-form definitions, and second using fixed-form definitions. The procedure performs a function on the 3 numeric values passed to it as value parameters. The example illustrates how a procedure interface is specified for a procedure and how values are returned from a procedure.
// Prototype for procedure FUNCTION DCL-PR Function INT(10); 1 TERM1 INT(5) VALUE; TERM2 INT(5) VALUE; TERM3 INT(5) VALUE; END-PR; DCL-PROC Function; DCL-PI *N INT(10); TERM1 INT(5) VALUE; TERM2 INT(5) VALUE; TERM3 INT(5) VALUE; END-PI; DCL-S Result INT(10); Result = Term1 ** 2 * 17 + Term2 * 7 + Term3; return Result * 45 + 23; END-PROC; 2 3
4 5 6
RPG IV Concepts
3-17
| * Prototype for procedure FUNCTION D FUNCTION PR 10I 0 1 | D TERM1 5I 0 VALUE | D TERM2 5I 0 VALUE | D TERM3 5I 0 VALUE | | P Function B 2 | D Function PI 10I 0 3 | D Term1 5I 0 VALUE | D Term2 5I 0 VALUE | D Term3 5I 0 VALUE | D Result S 10I 0 4 | | Result = Term1 ** 2 * 17 | + Term2 * 7 5 | + Term3; | return Result * 45 + 23; | | P E 6 | | | | Figure 3-6. Example of a Fixed-Form Subprocedure | A Prototype which specifies the name, return value if any, and parameters if any. Since the # 1 procedure is not exported from this module, it is optional to specify the prototype. # | # # # # # | 2 3 A Begin-Procedure specification A Procedure-Interface definition, which specifies the return value and parameters, if any. The procedure interface must match the corresponding prototype. The procedure-interface definition is optional if the subprocedure does not return a value and does not have any parameters that are passed to it. If the prototype had not been specified, the procedure-interface definition would be used by the compiler to implicitly define the prototype. Other local definitions. Any calculation specifications, standard or free-form, needed to perform the task of the procedure. The calculations may refer to both local and global definitions. Any subroutines included within the subprocedure are local. They cannot be used outside of the subprocedure. If the subprocedure returns a value, then the subprocedure must contain a RETURN operation. An End-Procedure specification
4 5
Except for the procedure-interface definition, which may be placed anywhere within the definition specifications, a subprocedure must be coded in the order shown above. No cycle code is generated for subprocedures. Consequently, you cannot code: v Prerun-time and compile-time arrays and tables v *DTAARA definitions v Total calculations The calculation specifications are processed only once and the procedure returns at the end of the calculation specifications. See Subprocedure Calculations on page 3-37 for more information. A subprocedure may be exported, meaning that procedures in other modules in the program can call it. To indicate that it is to be exported, specify the keyword EXPORT on the Procedure-Begin specification. If not specified, the subprocedure can only be called from within the module.
3-18
Return Values
A procedure that returns a value is essentially a user-defined function, similar to a built-in function. To define a return value for a subprocedure, you must 1. Define the return value on both the prototype and procedure-interface definitions of the subprocedure. 2. Code a RETURN operation with an expression that contains the value to be returned. | | | | | | | | | | | | | | | | | | | | | | | You define the length and the type of the return value on the procedure-interface specification (the DCL-PI statement, or the definition specification with PI in positions 24-25). The following keywords are also allowed: DATFMT(fmt) The return value has the date format specified by the keyword. DIM(N) The return value is an array with N elements. LIKE(name) The return value is defined like the item specified by the keyword. LIKEDS(name) The return value is a data structure defined like the data structure specified by the keyword. LIKEREC(name{,type}) The return value is a data structure defined like the record name specified by the keyword. PROCPTR The return value is a procedure pointer. TIMFMT(fmt) The return value has the time format specified by the keyword. To return the value to the caller, you must code a RETURN operation with an expression containing the return value. The operand of the RETURN operation is subject to the same rules as an expression with EVAL. The actual returned value has the same role as the left-hand side of the EVAL expression, while the operand of the RETURN operation has the same role as the right-hand side. You must ensure that a RETURN operation is performed if the subprocedure has a return value defined; otherwise an exception is issued to the caller of the subprocedure.
Scope of Definitions
Any items defined within a subprocedure are local to the subprocedure. If a local item is defined with the same name as a global data item, then any references to that name inside the subprocedure use the local definition. However, keep in mind the following: v Subroutine names and tag names are known only to the procedure in which they are defined, even those defined in the cycle-main procedure. v All fields specified on input and output specifications are global. When a subprocedure uses input or output specifications (for example, while processing a read operation), the global name is used even if there is a local variable of the same name. When using a global KLIST or PLIST in a subprocedure some of the fields may have the same names as local fields. If this occurs, the global field is used. This may cause problems when setting up a KLIST or PLIST prior to using it. For example, consider the following source.
RPG IV Concepts
3-19
1A 1A
* Define a global key field list with 2 fields, Fld1 and Fld2 global_kl KLIST KFLD Fld1 KFLD Fld2
1A
* local_kl has one global kfld (fld1) and one local (fld2) local_kl KLIST KFLD Fld1 KFLD Fld2 * * * * Even though Fld2 is defined locally in the subprocedure, the global Fld2 is used by the global_kl, since global KLISTs always use global fields. As a result, the assignment to the local Fld2 will NOT affect the CHAIN operation. EVAL EVAL SETLL Fld1 = A Fld2 = B file
C C C
global_kl
* Local KLISTs use global fields only when there is no local * field of that name. local_kl uses the local Fld2 and so the * assignment to the local Fld2 WILL affect the CHAIN operation. C EVAL Fld1 = A C EVAL Fld2 = B C local_kl SETLL file ... P E Figure 3-7. Scope of Key Fields Inside a Module
3-20
RPG IV Concepts
3-21
| | |
Cycle Features Allowed Main Procedure Yes Implicitly defined in the main source section
Initialization of global variables, opening of global files, and locking of UDS data areas v When the first procedure in the module is called after the activation group is created. v When the main procedure is called, if the main procedure previously ended with LR on, or ended abnormally.
Implicit closing of global files and unlocking of data areas When the main procedure ends with LR on, or ends abnormally.
Linearmain
MAIN
No
Explicitly defined with the MAIN keyword and Procedure specifications None, indicated by the presence of the NOMAIN keyword
When the main procedure is first called after the activation group is created, or if somehow a sub-procedure is called first. When the first procedure in the module is called after the activation group is created
Never
No main
NOMAIN No
Never
Cycle Module
# # # # # # A cycle module has a cycle-main procedure which uses the RPG Program Cycle; the procedure is implicitly specified in the main source section . (See Program Cycle on page 3-25.) You do not need to code anything special to define the main procedure; it consists of everything before the first Procedure specification. The parameters for the cycle-main procedure can be coded using a procedure interface and an optional prototype in the global Definition specifications, or using a *ENTRY PLIST in the cycle-main procedure's calculations.
# The name of the cycle-main procedure must be the same as the name of the module being created. You # can either use this name for the prototype and procedure interface, or specify this name in the EXTPROC # keyword of the prototype, or of the procedure interface, if the prototype is not specified. # # # # Any procedure interface found in the global definitions is assumed to be the procedure interface for the cycle-main procedure. If a prototype is specified, the name is required for the procedure interface for the cycle-main procedure, and the prototype with the matching name must precede the procedure interface in the source. In the following example, module CheckFile is created. Its cycle-main procedure has three parameters: 1. A file name (input) 2. A library name (input) 3. An indicator indicating whether the file was found (output) # In this example, the procedure is intended to be called from another module, so a prototype must be # specified in a /COPY file. /COPY file CHECKFILEC with the prototype for the cycle-main procedure:
D CheckFile D file D library D found PR 10a 10a 1N const const
Module CheckFile:
3-22
Using a *ENTRY PLIST, you would define the parameters this way:
D file S 10a const D library S 10a const D found S 1N C *ENTRY PLIST C PARM C PARM C PARM C ... code using parameters file, library
# You can also use a prototype and procedure interface to define your cycle-main procedure as a program. # In this case, you would specify the EXTPGM keyword for the prototype. In this example, the program is # intended to be called by other RPG programs, so a prototype must be specified in a /COPY file. /COPY file CHECKFILEC with the prototype for the program:
D CheckFile D file D library D found PR 10a 10a 1N extpgm(CHECKFILE) const const
In the module source, the procedure interface would be defined the same way. # In the following example, the program is not intended to be called by any other RPG programs, so a # prototype is not necessary. In this case, the EXTPGM keyword is specified for the procedure interface. # Since a prototype is not specified, a name is not necessary for the procedure interface. # A procedure interface with the EXTPGM keyword: # F ... file specifications PI extpgm(CUSTREPORT) # D 10a const # D custfile 10a const # D custlib ... code using the custfile and custlib parameters # Use Caution Exporting Subprocedures in Cycle Modules: If a module contains both a cycle-main procedure and exported subprocedures, take great care to ensure that the RPG cycle in the cycle-main procedure does not adversely affect the global data, files, and data areas that the subprocedures are using. You must be aware of when files are opened and closed implicitly, when data areas are locked and unlocked implicitly, and when global data is initialized or re-initialized. Potential Problem Situations: A cycle module having exported subprocedures introduces potential scenarios where the cycle-main procedure initialization is performed at an unexpected time, with the effect that has on files, data area locks, and global data then leading to errors. An exported subprocedure can be called first in the module, from a procedure outside the module, before the cycle-main procedure is called. If the cycle-main procedure is then called, it will initialize at that time. v If module initialization occurs because a subprocedure is the first procedure to be called, and cycle-main procedure initialization occurs later, errors can occur if files are already open or data areas are already locked.
RPG IV Concepts
3-23
Linear Module
A module which specifies the MAIN or NOMAIN keyword on the Control specification is compiled without incorporating the program cycle. When the program cycle is not included in the module, you are restricted in terms of what can be coded in the main source section. Specifically, you cannot code specifications for: v Primary and secondary files v Heading, detail and total output v Executable calculations, including the *INZSR Initialization subroutine v *ENTRY PLIST Instead you would code in the main source section: v Full-procedural files v Input specifications v Definition specifications v Declarative calculations such as DEFINE, KFLD, KLIST, PARM, and PLIST (but not *ENTRY PLIST) v Exception output Caution: There is no implicit closing of global files or unlocking of data areas in a linear module. These objects will remain open or locked until they are explicitly closed or unlocked. Linear Main Module: A module which has a program entry procedure but does not use the RPG Program Cycle can be generated by specifying the MAIN keyword on the control specification. This type of module has one or more procedures, one of which is identified as the main procedure. It does not allow specifications which relate to the RPG Program Cycle. See MAIN(main_procedure_name) on page 5-29 for more information. NOMAIN Module: You can code one or more subprocedures in a module without coding a main procedure. Such a module is called a NOMAIN module, since it requires the specification of the NOMAIN keyword on the control specification. No cycle code is generated for the NOMAIN module.
3-24
NOMAIN Module
Tip: You may want to consider converting all your Cycle modules to NOMAIN modules except the ones that actually contain the program entry procedure for a program, to reduce the individual size of those modules by eliminating the unnecessary cycle code in each of those modules. Note: A module with NOMAIN specified will not have a program entry procedure. Consequently you cannot use the CRTBNDRPG command to compile the source. See NOMAIN on page 5-30 for more information.
Module Initialization
Module initialization occurs when the first procedure (either the main procedure or a subprocedure) is called. A cycle module has an additional form of initialization which can occur repeatedly. Cycle-main procedure initialization occurs when the cycle-main procedure is called the first time. It also occurs on subsequent calls if the cycle-main procedure ended abnormally or with LR on. Initialization of Global Data: Global data in the module is initialized during module initialization and during cycle-main procedure initialization. For special concerns regarding initialization in cycle-main procedures, see Use Caution Exporting Subprocedures in Cycle Modules on page 3-23.
Program Cycle
The ILE RPG compiler supplies part of the logic for an RPG program. For a cycle-main procedure, the logic the compiler supplies is called the program cycle or logic cycle. The program cycle is a series of ordered steps that the main procedure goes through for each record read. The information that you code on RPG IV specifications in your source program need not explicitly specify when records should be read or written. The ILE RPG compiler can supply the logical order for these operations when your source program is compiled. Depending on the specifications you code, your program may or may not use each step in the cycle. | | | | | Primary (identified by a P in position 18 of the file description specifications) and secondary (identified by an S in position 18 of the file description specifications) files indicate input is controlled by the program cycle. A full procedural file (defined using a free-form DCL-F statement, or identified by an F in position 18 of the file description specifications) indicates that input is controlled by program-specified calculation operations (for example, READ and CHAIN). To control the cycle, you can have: v One primary file and, optionally, one or more secondary files v Only full procedural files v A combination of one primary file, optional secondary files, and one or more full procedural files in which some of the input is controlled by the cycle, and other input is controlled by the program. v No files (for example, input can come from a parameter list or a data area data structure).
RPG IV Concepts
3-25
NOMAIN Module
Note: No cycle code is generated for a module when MAIN or NOMAIN is specified on the control specification. See Linear Module on page 3-24 for more information. General RPG IV Program Cycle: Figure 3-8 shows the specific steps in the general flow of the RPG IV program cycle. A program cycle begins with step 1 and continues through step 7, then begins again with step 1. The first and last time a program goes through the RPG IV cycle differ somewhat from the normal cycle. Before the first record is read the first time through the cycle, the program resolves any parameters passed to it, writes the records conditioned by the 1P (first page) indicator, does file and data initialization, and processes any heading or detail output operations having no conditioning indicators or all negative conditioning indicators. For example, heading lines printed before the first record is read might consist of constant or page heading information or fields for reserved words, such as PAGE and *DATE. In addition, the program bypasses total calculations and total output steps on the first cycle. During the last time a program goes through the cycle, when no more records are available, the LR (last record) indicator and L1 through L9 (control level) indicators are set on, and file and data area cleanup is done.
Start
No Move fields
LR on
Yes
End of program
1 2 3 4 5 6 7
All heading and detail lines (H or D in position 17 of the output specifications) are processed. The next input record is read and the record identifying and control level indicators are set on. Total calculations are processed. They are conditioned by an L1 through L9 or LR indicator, or an L0 entry. All total output lines are processed. (identified by a T in position 17 of the output specifications). It is determined if the LR indicator is on. If it is on, the program is ended. The fields of the selected input records are moved from the record to a processing area. Field indicators are set on. All detail calculations are processed (those not conditioned by control level indicators in positions 7 and 8 of the calculation specifications) on the data from the record read at the beginning of the cycle.
3-26
RPG IV Concepts
3-27
3-28
Detailed RPG IV Object Program Cycle: Figure 3-9 on page 3-28 shows the specific steps in the detailed flow of the RPG IV program cycle. The item numbers in the following description refer to the numbers in the figure. Routines are flowcharted in Figure 3-13 on page 3-36 and in Figure 3-11 on page 3-33.
RPG IV Concepts
3-29
If the response is to cancel with a dump, the program goes to step 7; otherwise, the program branches to step 36. The program issues a dump and branches to step 36 (abnormal ending). All record identifying, 1P (first page), and control level (L1 through L9) indicators are set off. All overflow indicators (OA through OG, OV) are set off unless they have been set on during preceding detail calculations or detail output. Any other indicators that are on remain on. If the LR (last record) indicator is on, the program continues with step 10. If it is not on, the program branches to step 11. The appropriate control level (L1 through L9) indicators are set on and the program branches to step 29. If the RT indicator is on, the program continues with step 12; otherwise, the program branches to step 14. Factor 2 is moved to the result field for the parameters of the *ENTRY PLIST. If the RT indicator is on (return code set to 0), the program returns to the caller. If a primary file is present in the program, the program continues with step 15; otherwise, the program branches to step 29. During the first program cycle, the first record from the primary file and from each secondary file in the program is read. File translation is done on the input records. In other program cycles, a record is read from the last file processed. If this file is processed by a record address file, the data in the record address file defines the record to be retrieved. If lookahead fields are specified in the last record processed, the record may already be in storage; therefore, no read may be done at this time. If end of file has occurred on the file just read, the program branches to step 20. Otherwise, the program continues with step 17.
IBM i: ILE RPG Reference
9 10 11 12 13 14 15
16
3-30
19 20
21
22 23 24
25 26 27
28
29
30
31
32 33
RPG IV Concepts
3-31
36
37
38 39 40
Note: Steps 32 through 40 constitute the normal ending routine. For an abnormal ending, steps 34 through 35 are bypassed. 41 42 It is determined whether any overflow indicators (OA through OG OV) are on. If an overflow indicator is on, the program continues with step 42; otherwise, the program branches to step 43. The overflow routine receives control. (For detailed information on the overflow routine, see Overflow Routine on page 3-34.) This step is the return point in the program if factor 2 of an ENDSR operation contains the value *OFL. The MR indicator is set on and remains on for the complete cycle that processes the matching record if this is a multifile program and if the record to be processed is a matching record. Otherwise, the MR indicator is set off. Data from the last record read is made available for processing. Field indicators are set on, if specified. If lookahead fields are specified, the program continues with step 46; otherwise, the program branches to step 47. The lookahead routine receives control. (For detailed information on the lookahead routine, see Lookahead Routine on page 3-34.) Detail calculations are processed. This step is the return point in the program if factor 2 of an ENDSR operation contains the value *DETC. The program branches to step 4.
43
44 45 46 47
Initialization Subroutine: Refer to Figure 3-9 on page 3-28 to see a detailed explanation of the RPG IV initialization subroutine. The initialization subroutine allows you to process calculation specifications before 1P output. A specific subroutine that is to be run at program initialization time can be defined by specifying *INZSR in factor 1 of the subroutine's BEGSR operation. Only one subroutine can be defined as an initialization subroutine. It is called at the end of the program initialization step of the program cycle (that is, after data structures and subfields are initialized, external indicators and user data fields are retrieved, global files are opened, data area data structures, arrays, and tables are loaded, and PARM result fields moved to factor 1 for *ENTRY PLIST). *INZSR may not be specified as a file/program error/exception subroutine. If a program ends with LR off, the initialization subroutine does not automatically run during the next invocation of that program because the subroutine is part of the initialization step of the program.
3-32
Figure 3-11. Detail Flow of RPG IV Match Fields, Overflow, and Lookahead Routines
Match Fields Routine: Figure 3-11 shows the specific steps in the RPG IV match fields routine. The item numbers in the following descriptions refer to the numbers in the figure. 1 2 3 4 If multifile processing is being used, processing continues with step 2; otherwise, the program branches to step 3. The value of the match fields in the hold area is tested to determine which file is to be processed next. The RPG IV program extracts the match fields from the match files and processes sequence checking. If the match fields are in sequence, the program branches to step 5. If the match fields are not in sequence, the RPG IV exception/error handling routine receives control.
RPG IV Concepts
3-33
Overflow Routine: Figure 3-11 on page 3-33 shows the specific steps in the RPG IV overflow routine. The item numbers in the following descriptions refer to the numbers in the figure. 1 The RPG IV program determines whether the overflow lines were written previously using the fetch overflow logic (step 30 in Figure 3-9 on page 3-28). If the overflow lines were written previously, the program branches to the specified return point; otherwise, processing continues with step 2. All output lines conditioned with an overflow indicator are tested and written to the conditioned overflow lines.
The fetch overflow routine allows you to alter the basic RPG IV overflow logic to prevent printing over the perforation and to let you use as much of the page as possible. During the regular program cycle, the RPG IV program checks only once, immediately after total output, to see if the overflow indicator is on. When the fetch overflow function is specified, the RPG IV program checks overflow on each line for which fetch overflow is specified. Specify fetch overflow with an F in position 18 of the output specifications on any detail, total, or exception lines for a PRINTER file. The fetch overflow routine does not automatically cause forms to advance to the next page. During output, the conditioning indicators on an output line are tested to determine whether the line is to be written. If the line is to be written and an F is specified in position 18, the RPG IV program tests to determine whether the overflow indicator is on. If the overflow indicator is on, the overflow routine is fetched and the following operations occur: v Only the overflow lines for the file with the fetch specified are checked for output. v All total lines conditioned by the overflow indicator are written. v Forms advance to a new page when a skip to a line number less than the line number the printer is currently on is specified in a line conditioned by an overflow indicator. v Heading, detail, and exception lines conditioned by the overflow indicator are written. v The line that fetched the overflow routine is written. v Any detail and total lines left to be written for that program cycle are written. Position 18 of each OR line must contain an F if the overflow routine is to be used for each record in the OR relationship. Fetch overflow cannot be used if an overflow indicator is specified in positions 21 through 29 of the same specification line. If this occurs, the overflow routine is not fetched. Use the fetch overflow routine when there is not enough space left on the page to print the remaining detail, total, exception, and heading lines conditioned by the overflow indicator. To determine when to fetch the overflow routine, study all possible overflow situations. By counting lines and spaces, you can calculate what happens if overflow occurs on each detail, total, and exception line. Lookahead Routine: Figure 3-11 on page 3-33 shows the specific steps in the RPG IV lookahead routine. The item numbers in the following descriptions refer to the numbers in the figure. 1 The next record for the file being processed is read. However, if the file is a combined or update file (identified by a C or U, respectively, in position 17 of the file description specifications), the lookahead fields from the current record being processed is extracted. The lookahead fields are extracted.
Ending a Program without a Primary File: If your program does not contain a primary file, you must specify a way for the program to end:
3-34
The LR, RT, H1 through H9 indicators, and the RETURN operation code, can be used in conjunction with each other. | | | | | | | Program Control of File Processing: Specify a full procedural file (F in position 18 of the fixed-form file description specifications, or any file defined by a free-form file definition) to control all or partial input of a program. A full procedural file indicates that input is controlled by program-specified calculation operations (for example, READ, CHAIN). When both full procedural files and a primary file (P in position 18 of the file description specifications) are specified in a program, some of the input is controlled by the program, and other input is controlled by the cycle. Even if the program cycle exists in your module, all the processing of a full-procedural file is done in your calculations. The file operation codes can be used for program control of input. These file operation codes are discussed in File Operations on page 6-30.
RPG IV Concepts
3-35
3-36
3 4 5 6
7 8 9 10 11 12 13 14
15
Subprocedure Calculations
No cycle code is generated for a subprocedure, and so you must code it differently than you would code a cycle-main procedure. The subprocedure ends when one of the following occurs: v A RETURN operation is processed v The last calculation in the body of the subprocedure is processed. Figure 3-14 on page 3-38 shows the normal processing steps for a subprocedure. Figure 3-15 on page 3-39 shows the exception/error handling sequence.
RPG IV Concepts
3-37
Taking the "No" branch means that another procedure has already been called since the program was activated. You should ensure that you do not make any incorrect assumptions about the state of files, data areas, etc., since another procedure may have closed files, or unlocked data areas. If an entry parameter to the main procedure is RESET anywhere in the module, this will cause an exception. If it is possible that a subprocedure will be called before the main procedure, it is not advised to RESET any entry parameters for the cycle-main procedure.
3-38
Here are some points to consider when coding subprocedures: v There is no *INZSR associated with subprocedures. Data is initialized (with either INZ values or default values) when the subprocedure is first called, but before the calculations begin. Note also that if the subprocedure is the first procedure to be called in a module, the *INZSR of the cycle-main procedure (if present) will not be run, although other initialization of global data will be done. The *INZSR of the cycle-main procedure will be run when the cycle-main procedure is called. v When a subprocedure returns normally, the return value, if specified on the prototype of the called program or procedure, is passed to the caller. Nothing else occurs automatically. All files and data areas must be closed manually. Files must be written out manually. You can set on the LR or RT indicators, but it will have no immediate effect on the program termination. If the the subprocedure was called by a cycle-main procedure, the setting of the LR or RT indicators would take effect when the RPG cycle reached the point at which RPG checks those indicators. v Exception handling within a subprocedure differs from a cycle-main procedure primarily because there is no default exception handler for subprocedures and so situations where the default handler would be called for a cycle-main procedure correspond to abnormal end of the subprocedure. For example, Factor 2 of an ENDSR operation for a *PSSR subroutine within a subprocedure must be blank. A blank Factor 2 of the ENDSR for the *PSSR subroutine in a cycle-main procedure would result in control being passed to the default handler. In a subprocedure, if the ENDSR of the *PSSR subroutine is reached, then the subprocedure will end abnormally and RNX9001 will be signalled to the caller of the subprocedure. You can avoid abnormal termination either by coding a RETURN operation in the *PSSR, or by coding a GOTO and label in the subprocedure to continue processing. v The *PSSR error subroutine is local to the subprocedure. v You cannot code an INFSR in a subprocedure, nor can you use a file for which an INFSR is coded. v Indicators that control the cycle function solely as conditioning indicators when used in a linear module (MAIN or NOMAIN on control specification); or in a subprocedure that is active, but where the cycle-main procedure of the module is not. Indicators that control the cycle include: LR, RT, H1-H9, and control level indicators.
RPG IV Concepts
3-39
RPG IV Indicators
An indicator is a one byte character field which contains either '1' (on) or '0' (off). It is generally used to indicate the result of an operation or to condition (control) the processing of an operation. The indicator format can be specified on the definition specifications to define indicator variables. For a description of how to define character data in the indicator format, see Character Format on page 4-51 and Position 40 (Internal Data Type) on page 5-91. This chapter describes a special set of predefined RPG IV indicators (*INxx). RPG IV indicators are defined either by an entry on a specification or by the RPG IV program itself. The positions on the specification in which you define the indicator determine how the indicator is used. An indicator that has been defined can then be used to condition calculation and output operations. The RPG IV program sets and resets certain indicators at specific times during the program cycle. In addition, the state of most indicators can be changed by calculation operations. All indicators except MR, 1P, KA through KN, and KP through KY can be set on with the SETON operation code; all indicators except MR and 1P can be set off with the SETOFF operation code. This chapter is divided into the following topics: v v v v Indicators defined on the RPG IV specifications Indicators not defined on the RPG IV specifications Using indicators Indicators referred to as data.
3-40
Overflow Indicators
An overflow indicator is defined by the OFLIND keyword on the file description specifications. It is set on when the last line on a page has been printed or passed. Valid indicators are *INOA through *INOG, *INOV, and *IN01 through *IN99. A defined overflow indicator can then be used to condition calculation and output operations. A description of the overflow indicator and fetch overflow logic is given in Overflow Routine on page 3-34.
3-41
3-42
3-43
3-44
RPG IV Concepts
3-45
3-46
*...1....+....2....+....3....+....4....+....5....+....6....+....7... IFilename++SqNORiPos1+NCCPos2+NCCPos3+NCC................................ I........................Fmt+SPFrom+To+++DcField+++++++++L1M1FrPlMnZr.... ISALES 01 I 1 2 L2FLD L2 I 3 15 NAME IITEM 02 I 1 2 L2FLD L2 I 3 5 L1FLD L1 I 6 8 AMT CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq.. * Indicator 11 is set on when the salesman record is read. * C 01 SETON 11 * * Indicator 11 is set off when the item record is read. * This allows the normal L1 control break to occur. * C 02 SETOFF 11 C 02AMT ADD L1TOT L1TOT 5 0 CL1 L1TOT ADD L2TOT L2TOT 5 0 CL2 L2TOT ADD LRTOT LRTOT 5 0 *
*...1....+....2....+....3....+....4....+....5....+....6....+....7... OFilename++DF..N01N02N03Excnam++++B++A++Sb+Sa+........................... O..............N01N02N03Field+++++++++YB.End++PConstant/editword/DTformat OPRINTER D 01 1 1 O L2FLD 5 O NAME 25 O D 02 1 O L1FLD 15 O AMT Z 15 * * When the next item record causes an L1 control break, no total * output is printed if indicator 11 is on. Detail calculations * are then processed for the item record. * OFilename++DF..N01N02N03Excnam++++B++A++Sb+Sa+........................... O..............N01N02N03Field+++++++++YB.End++PConstant/editword/DTformat O T L1N11 1 O L1TOT ZB 25 O 27 * O T L2 1 O L2TOT ZB 25 O 28 ** O T LR 1 O LRTOT ZB 25
RPG IV Concepts
3-47
Different record types normally contain the same number of control fields. However, some applications require a different number of control fields in some records. The salesman records contain only the L2 control field. The item records contain both L1 and L2 control fields. With normal RPG IV coding, an unwanted control break is created by the first item record following the salesman record. This is recognized by an L1 control break immediately following the salesman record and results in an asterisk being printed on the line below the salesman record. v Numeric control fields are compared in zoned decimal format. Packed numeric input fields lengths can be determined by the formula:
d = 2n - 1
Where d = number of digits in the field and n = length of the input field. The number of digits in a packed numeric field is always odd; therefore, when a packed numeric field is compared with a zoned decimal numeric field, the zoned field must have an odd length. v When numeric control fields with decimal positions are compared to determine whether a control break has occurred, they are always treated as if they had no decimal positions. For instance, 3.46 is considered equal to 346. v If you specify a field as numeric, only the positive numeric value determines whether a control break has occurred; that is, a field is always considered to be positive. For example, -5 is considered equal to +5. v Date and time fields are converted to *ISO format before being compared v Graphic data is compared by hexadecimal value Split Control Field: A split control field is formed when you assign more than one field in an input record the same control level indicator. For a program described file, the fields that have the same control level indicator are combined by the program in the order specified in the input specifications and treated as a single control field (see Figure 3-20 on page 3-49). The first field defined is placed in the high-order (leftmost) position of the control field, and the last field defined is placed in the low-order (rightmost) position of the control field.
3-48
*...1....+....2....+....3....+....4....+....5....+....6....+....7... IFilename++SqNORiPos1+NCCPos2+NCCPos3+NCC................................ I........................Fmt+SPFrom+To+++DcField+++++++++L1M1FrPlMnZr.... IMASTER 01 I 28 31 CUSNO L4 I 15 20 ACCTNO L4 I 50 52 REGNO L4 Figure 3-20. Split Control Fields
For an externally described file, fields that have the same control level indicator are combined in the order in which the fields are described in the data description specifications (DDS), not in the order in which the fields are specified on the input specifications. For example, if these fields are specified in DDS in the following order: v EMPNO v DPTNO v REGNO and if these fields are specified with the same control level indicator in the following order on the input specifications: v REGNO L3 v DPTNO L3 v EMPNO L3 the fields are combined in the following order to form a split control field: EMPNO DPTNO REGNO. Some special rules for split control fields are: v For one control level indicator, you can split a field in some record types and not in others if the field names are different. However, the length of the field, whether split or not, must be the same in all record types. v You can vary the length of the portions of a split control field for different record types if the field names are different. However, the total length of the portions must always be the same. v A split control field can be made up of a combination of packed decimal fields and zoned decimal fields so long as the field lengths (in digits or characters) are the same. v You must assign all portions of a split control field in one record type the same field record relation indicator and it must be defined on consecutive specification lines. v When a split control field contains a date, time, or timestamp field than all fields in the split control field must be of the same type. Figure 3-21 on page 3-50 shows examples of the preceding rules.
RPG IV Concepts
3-49
*...1....+....2....+....3....+....4....+....5....+....6....+....7... IFilename++SqNORiPos1+NCCPos2+NCCPos3+NCC................................ I........................Fmt+SPFrom+To+++DcField+++++++++L1M1FrPlMnZr.... IDISK BC 91 95 C1 I OR 92 95 C2 I OR 93 95 C3 I * All portions of the split control field must be assigned the same * control level indicator and all must have the same field record * relation entry. I 1 5 FLD1A L1 I 46 50 FLD1B L1 I 11 13 FLDA L2 I 51 60 FLD2A L3 I 31 40 FLD2B L3 I 71 75 FLD3A L4 92 I 26 27 FLD3B L4 92 I 41 45 FLD3C L4 92 I 61 70 FLDB 92 I 21 25 FLDC 92 I 6 10 FLD3D L4 93 I 14 20 FLD3E L4 93 Figure 3-21. Split Control FieldsSpecial Rules
The record identified by a '1' in position 95 has two split control fields: 1. FLD1A and FLD1B 2. FLD2A and FLD2B The record identified with a '2' in position 95 has three split control fields: 1. FLD1A and FLD1B 2. FLD2A and FLD2B 3. FLD3A, FLD3B, and FLD3C The third record type, identified by the 3 in position 95, also has three split control fields: 1. FLD1A and FLD1B 2. FLD2A and FLD2B 3. FLD3D and FLD3E
Field Indicators
A field indicator is defined by an entry in positions 69 and 70, 71 and 72, or 73 and 74 of the input specifications. The valid field indicators are: v 01-99 v H1-H9 v U1-U8 v RT You can use a field indicator to determine if the specified field or array element is greater than zero, less than zero, zero, or blank. Positions 69 through 72 are valid for numeric fields only; positions 73 and 74 are valid for numeric or character fields. An indicator specified in positions 69 and 70 is set on when the numeric input field is greater than zero; an indicator specified in positions 71 and 72 is set on when the numeric input field is less than zero; and an indicator specified in positions 73 and 74 is set on when the numeric input field is zero or when the character input field is blank. You can then use the field indicator to condition calculation or output operations.
3-50
Resulting Indicators
Resulting indicators are used by calculation specifications in the traditional format (C specifications). They are not used by free-form calculation specifications. For most operation codes, in either traditional format or free-form, you can use built-in functions instead of resulting indicators. For more information, see Built-in Functions on page 6-8. A resulting indicator is defined by an entry in positions 71 through 76 of the calculation specifications. The purpose of the resulting indicators depends on the operation code specified in positions 26 through 35. (See the individual operation code in Operation Codes on page 6-140 for a description of the purpose of the resulting indicators.) For example, resulting indicators can be used to test the result field after an arithmetic operation, to identify a record-not-found condition, to indicate an exception/error condition for a file operation, or to indicate an end-of-file condition. The valid resulting indicators are: v 01-99 v v v v v v v H1-H9 OA-OG, OV L1-L9 LR U1-U8 KA-KN, KP-KY (valid only with SETOFF) RT
RPG IV Concepts
3-51
*...1....+....2....+....3....+....4....+....5....+....6....+....7... CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq.. * * Two resulting indicators are used to test for the different * conditions in a subtraction operation. These indicators are * used to condition the calculations that must be processed for * a payroll job. Indicator 10 is set on if the hours worked (HRSWKD) * are greater than 40 and is then used to condition all operations * necessary to find overtime pay. If Indicator 20 is not on * (the employee worked 40 or more hours), regular pay based on a * 40-hour week is calculated. * C HRSWKD SUB 40 OVERTM 3 01020 * C N20PAYRAT MULT (H) 40 PAY 6 2 C 10OVERTM MULT (H) OVRRAT OVRPAY 6 2 C 10OVRPAY ADD PAY PAY * * If indicator 20 is on (employee worked less than 40 hours), pay * based on less than a 40-hour week is calculated. C 20PAYRAT MULT (H) HRSWKD PAY * Figure 3-22. Resulting Indicators Used to Condition Operations
3-52
External Indicators
The external indicators are U1 through U8. These indicators can be set in a CL program or in an RPG IV program. In a CL program, they can be set by the SWS (switch-setting) parameter on the CL commands CHGJOB (Change Job) or CRTJOBD (Create Job Description). In an RPG IV program, they can be set as a resulting indicator or field indicator. The status of the external indicators can be changed in the program by specifying them as resulting indicators on the calculation specifications or as field indicators on the input specifications. However, changing the status of the IBM i job switches with a CL program during processing of an RPG IV program has no effect on the copy of the external indicators used by the RPG IV program. Setting the external indicators on or off in the program has no effect on file operations. File operations function according to the status of the U1 through U8 indicators when the program is initialized. However, when a program ends normally with LR on, the external indicators are copied back into storage, and their status reflects their last status in the RPG IV program. The current status of the external indicators can then be used by other programs. Note: When using RETURN (Return to Caller) on page 6-288 with the LR indicator off, you are specifying a return without an end and, as a result, no external indicators are updated.
Internal Indicators
Internal indicators include: v First page indicator v Last record indicator v Matching record indicator v Return Indicator. First Page Indicator (1P): The first page (1P) indicator is set on by the RPG IV program when the program starts running and is set off by the RPG IV program after detail time output. The first record will be processed after detail time output. The 1P indicator can be used to condition heading or detail records that are to be written at 1P time. Do not use the 1P indicator in any of the following ways: v To condition output fields that require data from input records; this is because the input data will not be available. v v v v To condition total or exception output lines In an AND relationship with control level indicators As a resulting indicator When MAIN or NOMAIN is specified on a control specification
Last Record Indicator (LR): In a program that contains a primary file, the last record indicator (LR) is set on after the last record from a primary/secondary file has been processed, or it can be set on by the programmer. The LR indicator can be used to condition calculation and output operations that are to be done at the end of the program. When the LR indicator is set on, all other control level indicators (L1 through L9) are also set on. If any of the indicators L1 through L9 have not been defined as control level indicators, as record identifying indicators, as resulting indicators, or by *INxx, the indicators are set on when LR is set on, but they cannot be used in other specifications. In a program that does not contain a primary file, you can set the LR indicator on as one method to end the program. (For more information on how to end a program without a primary file, see RPG Cycle and other implicit Logic on page 3-25.) To set the LR indicator on, you can specify the LR indicator as a record identifying indicator or a resulting indicator. If LR is set on during detail calculations, all other control level indicators are set on at the beginning of the next cycle. LR and the record identifying indicators are both on throughout the remainder of the detail cycle, but the record identifying indicators are set off before LR total time.
RPG IV Concepts
3-53
Using Indicators
Indicators that you have defined as overflow indicators, control level indicators, record identifying indicators, field indicators, resulting indicators, *IN, *IN(xx), *INxx, or those that are defined by the RPG IV language can be used to condition files, calculation operations, or output operations. An indicator must be defined before it can be used as a conditioning indicator. The status (on or off) of an indicator is not affected when it is used as a conditioning indicator. The status can be changed only by defining the indicator to represent a certain condition. Note: Indicators that control the cycle function solely as conditioning indicators when used in a MAIN or NOMAIN module; or in a subprocedure that is active, but where the cycle-main procedure of the module is not. Indicators that control the cycle include: LR, RT, H1-H9, and control level indicators.
File Conditioning
The file conditioning indicators are specified by the EXTIND keyword on the file description specifications. Only the external indicators U1 through U8 are valid for file conditioning. (The USROPN keyword can be used to specify that no implicit OPEN should be done.) If the external indicator specified is off when the program is called, the file is not opened and no data transfer to or from the file will occur when the program is running. Primary and secondary input files are
3-54
Using Indicators
processed as if they were at end-of-file. The end-of-file indicator is set on for all READ operations to that file. Input, calculation, and output specifications for the file need not be conditioned by the external indicator. Rules for File Conditioning: When you condition files, remember the following: v A file conditioning entry can be made for input, output, update, or combined files. v A file conditioning entry cannot be made for table or array input. v Output files for tables can be conditioned by U1 through U8. If the indicator is off, the table is not written. v A record address file can be conditioned by U1 through U8, but the file processed by the record address file cannot be conditioned by U1 through U8. v If the indicator conditioning a primary file with matching records is off, the MR indicator is not set on. v Input does not occur for an input, an update, or a combined file if the indicator conditioning the file is off. Any indicators defined on the associated Input specifications in positions 63-74 will be processed as usual using the existing values in the input fields. v Data transfer to the file does not occur for an output, an update, or a combined file if the indicator conditioning the file is off. Any conditioning indicators, numeric editing, or blank after that are defined on the output specifications for these files will be processed as usual. v If the indicator conditioning an input, an update, or a combined file is off, the file is considered to be at end of file. All defined resulting indicators are set off at the beginning of each specified I/O operation. The end-of-file indicator is set on for READ, READC, READE, READPE, and READP operations. CHAIN, EXFMT, SETGT, SETLL, and UNLOCK operations are ignored and all defined resulting indicators remain set off.
3-55
Using Indicators
and 66 of the input specifications, can also be related to a particular record type in an OR relationship if a field record relation indicator is specified. Control fields or match fields in the OR relationship that do not have a field record relation indicator are used with all record types in the OR relationship. If two control fields have the same control level indicator or two match fields have the same matching level value, a field record relation indicator can be assigned to just one of the match fields. In this case, only the field with the field record relation indicator is used when that indicator is on. If none of the field record relation indicators are on for that control field or match field, the field without a field record relation indicator is used. Control fields and match fields can only have entries of 01 through 99 or H1 through H9 in positions 67 and 68. You can use positions 67 and 68 to specify that the program accepts and uses data from a particular field only when a certain condition occurs (for example, when records match, when a control break occurs, or when an external indicator is on). You can indicate the conditions under which the program accepts data from a field by specifying indicators L1 through L9, MR, or U1 through U8 in positions 67 and 68. Data from the field named in positions 49 through 62 is accepted only when the field record relation indicator is on. External indicators are primarily used when file conditioning is specified with the EXTIND(*INUx) on page 5-55 keyword on the file description specifications. However, they can be used even though file conditioning is not specified. A halt indicator (H1 through H9) in positions 67 and 68 relates a field to a record that is in an OR relationship and also has a halt indicator specified in positions 21 and 22. Remember the following points when you use field record relation indicators: v Control level (positions 63 and 64) and matching fields (positions 65 and 66) with the same field record relation indicator must be grouped together. v Fields used for control level (positions 63 and 64) and matching field entries (positions 65 and 66) without a field record relation indicator must appear before those used with a field record relation indicator. v Control level (positions 63 and 64) and matching fields (positions 65 and 66) with a field record relation indicator (positions 67 and 68) take precedence, when the indicator is on, over control level and matching fields of the same level without an indicator. v Field record relations (positions 67 and 68) for matching and control level fields (positions 63 through 66) must be specified with record identifying indicators (01 through 99 or H1 through H9) from the main specification line or an OR relation line to which the matching field refers. If multiple record types are specified in an OR relationship, an indicator that specifies the field relation can be used to relate matching and control level fields to the pertinent record type. v Noncontrol level (positions 63 and 64) and matching field (positions 65 and 66) specifications can be interspersed with groups of field record relation entries (positions 67 and 68). v The MR indicator can be used as a field record relation indicator to reduce processing time when certain fields of an input record are required only when a matching condition exists. v The number of control levels (L1 through L9) specified for different record types in the OR relationship can differ. There can be no control level for certain record types and a number of control levels for other record types. v If all matching fields (positions 65 and 66) are specified with field record relation indicators (positions 67 and 68), each field record relation indicator must have a complete set of matching fields associated with it. v If one matching field is specified without a field record relation indicator, a complete set of matching fields must be specified for the fields without a field record relation indicator.
3-56
Using Indicators
*...1....+....2....+....3....+....4....+....5....+....6....+....7... IFilename++SqNORiPos1+NCCPos2+NCCPos3+NCC................................ I........................Fmt+SPFrom+To+++DcField+++++++++L1M1FrPlMnZr.... IREPORT AA 14 1 C5 I OR 16 1 C6 I 20 30 FLDB I 2 10 FLDA 07 * * Indicator 07 was specified elsewhere in the program. * I 40 50 FLDC 14 I 60 70 FLDD 16 Figure 3-23. Field Record Relation
The file contains two different types of records, one identified by a 5 in position 1 and the other by a 6 in position 1. The FLDC field is related by record identifying indicator 14 to the record type identified by a 5 in position 1. The FLDD field is related to the record type having a 6 in position 1 by record identifying indicator 16. This means that FLDC is found on only one type of record (that identified by a 5 in position 1) and FLDD is found only on the other type. FLDA is conditioned by indicator 07, which was previously defined elsewhere in the program. FLDB is found on both record types because it is not related to any one type by a record identifying indicator.
The function key indicators correspond to function keys 1 through 24. Function key indicator KA corresponds to function key 1, KB to function key 2 ... KY to function key 24. Function key indicators that are set on can then be used to condition calculation or output operations. Function key indicators can be set off by the SETOFF operation.
RPG IV Concepts
3-57
Using Indicators
3-58
Using Indicators
v RT Any indicator that you use in positions 9 through 11 must be previously defined as one of the following types of indicators: v Overflow indicators (file description specifications OFLIND(indicator) on page 5-64 v Record identifying indicators (input specifications, positions 21 and 22) v Control level indicators (input specifications, positions 63 and 64) v v v v v Field indicators (input specifications, positions 69 through 74) Resulting indicators (calculation specifications, positions 71 through 76) External indicators Indicators are set on, such as LR and MR *IN array, *IN(xx) array element, or *INxx field (see Indicators Referred to As Data on page 3-64 for a description of how an indicator is defined when used with one of these reserved words).
If the indicator must be off to condition the operation, place an N in positions 9. The indicators in grouped AND/OR lines, plus the control level indicators (if specified in positions 7 and 8), must all be exactly as specified before the operation is done as in Figure 3-24.
*...1....+....2....+....3....+....4....+....5....+....6....+....7... CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq.. * C 25 CAN L1 SUB TOTAL TOTAL A CL2 10 CANNL3TOTAL MULT 05 SLSTAX B * Figure 3-24. Conditioning Operations (Control Level Indicators)
Assume that indicator 25 represents a record type and that a control level 2 break occurred when record type 25 was read. L1 and L2 are both on. All operations conditioned by the control level indicators in positions 7 and 8 are done before operations conditioned by control level indicators in positions 9 through 11. Therefore, the operation in B occurs before the operation in A . The operation in A is done on the first record of the new control group indicated by 25, whereas the operation in B is a total operation done for all records of the previous control group. The operation in B can be done when the L2 indicator is on provided the other conditions are met: Indicator 10 must be on; the L3 indicator must not be on. The operation conditioned by both L2 and NL3 is done only when a control level 2 break occurs. These two indicators are used together because this operation is not to be done when a control level 3 break occurs, even though L2 is also on. Some special considerations you should know when using conditioning indicators in positions 9 through 11 are as follows: v With externally described work station files, the conditioning indicators on the calculation specifications must be either defined in the RPG program or be defined in the DDS source for the workstation file. v With program described workstation files, the indicators used for the workstation file are unknown at compile time of the RPG program. Thus indicators 01-99 are assumed to be declared and they can be used to condition the calculation specifications without defining them. v Halt indicators can be used to end the program or to prevent the operation from being processed when a specified error condition is found in the input data or in another calculation. Using a halt indicator is necessary because the record that causes the halt is completely processed before the program stops.
RPG IV Concepts
3-59
Using Indicators
Therefore, if the operation is processed on an error condition, the results are in error. A halt indicator can also be used to condition an operation that is to be done only when an error occurs. If LR is specified in positions 9 through 11, the calculation is done after the last record has been processed or after LR is set on. If a control level indicator is used in positions 9 through 11 and positions 7 and 8 are not used (detail time), the operation conditioned by the indicator is done only on the record that causes a control break or any higher level control break. If a control level indicator is specified in positions 7 and 8 (total time) and MR is specified in positions 9 through 11, MR indicates the matching condition of the previous record and not the one just read that caused the control break. After all operations conditioned by control level indicators in positions 7 and 8 are done, MR then indicates the matching condition of the record just read. If positions 7 and 8 and positions 9 through 11 are blank, the calculation specified on the line is done at detail calculation time.
v v
Figure 3-25 and Figure 3-26 on page 3-61 show examples of conditioning indicators.
*...1....+....2....+....3....+....4....+....5....+....6....+....7... IFilenameSqNORiPos1NCCPos2NCCPos3NCC.PFromTo++DField+L1M1FrPlMnZr...* I........................Fmt+SPFrom+To+++DcField+++++++++L1M1FrPlMnZr.... * * Field indicators can be used to condition operations. Assume the * program is to find weekly earnings including overtime. The over* time field is checked to determine if overtime was entered. * If the employee has worked overtime, the field is positive and * indicator 10 is set on. In all cases the weekly regular wage * is calculated. However, overtime pay is added only if * indicator 10 is on. * ITIME AB 01 I 1 7 EMPLNO I 8 10 0OVERTM 10 I 15 20 2RATE I 21 25 2RATEOT CL0N01Factor1+++++++Opcode(E)+Extended-factor2+++++++++++++++++++++++++++ * * Field indicator 10 was assigned on the input specifications. * It is used here to condition calculation operations. * C EVAL (H) PAY = RATE * 40 C 10 EVAL (H) PAY = PAY + (OVERTM * RATEOT) Figure 3-25. Conditioning Operations (Field Indicators)
3-60
Using Indicators
*...1....+....2....+....3....+....4....+....5....+....6....+....7... IFilename++SqNORiPos1+NCCPos2+NCCPos3+NCC................................ I........................Fmt+SPFrom+To+++DcField+++++++++L1M1FrPlMnZr.... * * A record identifying indicator is used to condition an operation. * When a record is read with a T in position 1, the 01 indicator is * set on. If this indicator is on, the field named SAVE is added * to SUM. When a record without T in position 1 is read, the 02 * indicator is set on. The subtract operation, conditioned by 02, * then performed instead of the add operation. * IFILE AA 01 1 CT I OR 02 1NCT I 10 15 2SAVE CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq.. * * Record identifying indicators 01 and 02 are assigned on the input * specifications. They are used here to condition calculation * operations. * CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq.. C 01 ADD SAVE SUM 8 2 C 02 SUB SAVE SUM 8 2 Figure 3-26. Conditioning Operations (Record Identifying Indicators)
See the expressions chapter and the operation codes chapter in this document for more examples and further details.
3-61
Using Indicators
v v v v v Record identifying indicators (input specifications, positions 21 and 22) Control level indicators (input specifications, positions 63 and 64) Field indicators (input specifications, positions 69 through 74) Resulting indicators (calculation specifications, positions 71 through 76) Indicators set by the RPG IV program such as 1P and LR
v External indicators set prior to or during program processing v *IN array, *IN(xx) array element, or *INxx field (see Indicators Referred to As Data on page 3-64 for a description of how an indicator is defined when used with one of these reserved words). If an indicator is to condition an entire record, you enter the indicator on the line that specifies the record type (see Figure 3-28 on page 3-63). If an indicator is to condition when a field is to be written, you enter the indicator on the same line as the field name (see Figure 3-28 on page 3-63). Conditioning indicators are not required on output lines. If conditioning indicators are not specified, the line is output every time that type of record is checked for output. If you specify conditioning indicators, one indicator can be entered in each of the three separate output indicator fields (positions 22 and 23, 25 and 26, and 28 and 29). If these indicators are on, the output operation is done. An N in the position preceding each indicator (positions 21, 24, or 27) means that the output operation is done only if the indicator is not on (a negative indicator). No output line should be conditioned by all negative indicators; at least one of the indicators should be positive. If all negative indicators condition a heading or detail operation, the operation is done at the beginning of the program cycle when the first page (1P) lines are written. You can specify output indicators in an AND/OR relationship by specifying AND/OR in positions 16 through 18. An unlimited number of AND/OR lines can be used. AND/OR lines can be used to condition output records, but they cannot be used to condition fields. However, you can condition a field with more than three indicators by using the EVAL operation in calculations. The following example illustrates this.
CL0N01Factor1+++++++Opcode(E)+Extended-factor2+++++++++++++++++++++++++++ * Indicator 20 is set on only if indicators 10, 12, 14,16, and 18 * are set on. C EVAL *IN20 = *IN10 AND *IN12 AND *IN14 C AND *IN16 AND *IN18 OFilename++DAddN01N02N03Excnam++++....................................... O..............N01N02N03Field+++++++++YB.End++PConstant/editword/DTformat * OUTFIELD is conditioned by indicator 20, which effectively * means it is conditioned by all the indicators in the EVAL * operation. OPRINTER E O 20 OUTFIELD
Other special considerations you should know about for output indicators are as follows: v The first page indicator (1P) allows output on the first cycle before the primary file read, such as printing on the first page. The line conditioned by the 1P indicator must contain constant information used as headings or fields for reserved words such as PAGE and UDATE. The constant information is specified in the output specifications in positions 53 through 80. If 1P is used in an OR relationship with an overflow indicator, the information is printed on every page (see Figure 3-29 on page 3-63). Use the 1P indicator only with heading or detail output lines. It cannot be used to condition total or exception output lines or should not be used in an AND relationship with control level indicators. v If certain error conditions occur, you might not want output operation processed. Use halt indicators to prevent the data that caused the error from being used (see Figure 3-30 on page 3-64). v To condition certain output records on external conditions, use external indicators to condition those records.
3-62
Using Indicators
See the Printer File section in the Rational Development Studio for i: ILE RPG Programmer's Guide for a discussion of the considerations that apply to assigning overflow indicators on the output specifications.
*...1....+....2....+....3....+....4....+....5....+....6....+....7... OFilename++DF..N01N02N03Excnam++++B++A++Sb+Sa+........................... O..............N01N02N03Field+++++++++YB.End++PConstant/editword/DTformat * * One indicator is used to condition an entire line of printing. * When 44 is on, the fields named INVOIC, AMOUNT, CUSTR, and SALSMN * are all printed. * OPRINT D 44 1 O INVOIC 10 O AMOUNT 18 O CUSTR 65 O SALSMN 85 * * A control level indicator is used to condition when a field should * be printed. When indicator 44 is on, fields INVOIC, AMOUNT, and * CUSTR are always printed. However, SALSMN is printed for the * first record of a new control group only if 44 and L1 are on. * OPRINT D 44 1 O INVOIC 10 O AMOUNT 18 O CUSTR 65 O L1 SALSMN 85 Figure 3-28. Output Indicators
*...1....+....2....+....3....+....4....+....5....+....6....+....7... OFilename++DF..N01N02N03Excnam++++B++A++Sb+Sa+........................... O..............N01N02N03Field+++++++++YB.End++PConstant/editword/DTformat * * The 1P indicator is used when headings are to be printed * on the first page only. * OPRINT H 1P 3 O 8 ACCOUNT * * The 1P indicator and an overflow indicator can be used to print * headings on every page. * OPRINT H 1P 3 1 O OR OF O 8 ACCOUNT Figure 3-29. 1P Indicator
RPG IV Concepts
3-63
*...1....+....2....+....3....+....4....+....5....+....6....+....7... IFilename++SqNORiPos1+NCCPos2+NCCPos3+NCC................................ I........................Fmt+SPFrom+To+++DcField+++++++++L1M1FrPlMnZr.... * * When an error condition (zero in FIELDB) is found, the halt * indicator is set on. * IDISK AA 01 I 1 3 FIELDA L1 I 4 8 0FIELDB H1 CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq.. * * When H1 is on, all calculations are bypassed. * C H1 GOTO END C : C : Calculations C : C END TAG OFilename++DF..N01N02N03Excnam++++B++A++Sb+Sa+........................... O..............N01N02N03Field+++++++++YB.End++PConstant/editword/DTformat * * FIELDA and FIELDB are printed only if H1 is not on. * Use this general format when you do not want information that * is in error to be printed. * OPRINT H L1 0 2 01 O 50 HEADING O D 01NH1 1 0 O FIELDA 5 O FIELDB Z 15 Figure 3-30. Preventing Fields from Printing
*IN
The array *IN is a predefined array of 99 one-position, character elements representing the indicators 01 through 99. The elements of the array should contain only the character values '0' (zero) or '1' (one). The specification of the *IN array or the *IN(xx) variable-index array element as a field in an input record, as a result field, or as factor 1 in a PARM operation defines indicators 01 through 99 for use in the program. The operations or references valid for an array of single character elements are valid with the array *IN except that the array *IN cannot be specified as a subfield in a data structure, or as a result field of a PARM operation.
*INxx
The field *INxx is a predefined one-position character field where xx represents any one of the RPG IV indicators except 1P or MR. The specification of the *INxx field or the *IN(n) fixed-index array element (where n = 1 - 99) as a field in an input record, as a result field, or as factor 1 in a PARM operation defines the corresponding indicator for use in the program.
3-64
Additional Rules
Remember the following rules when you are working with the array *IN, the array element *IN(xx) or the field *INxx: v Moving a character '0' (zero) or *OFF to any of these fields sets the corresponding indicator off. v Moving a character '1' (one) or *ON to any of these fields sets the corresponding indicator on. v Do not move any value, other than '0' (zero) or '1' (one), to *INxx. Any subsequent normal RPG IV indicator tests may yield unpredictable results. v If you take the address of *IN, *IN01 - *IN99, or *IN(index), indicators *IN01 to *IN99 will be defined. If you take the address of any other indicator, such as *INLR or *INL1, only that indicator will be defined. See Figure 3-31 for some examples of indicators referred to as data.
*...1....+....2....+....3....+....4....+....5....+....6....+....7... CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq.. * * When this program is called, a single parameter is passed to * control some logic in the program. The parameter sets the value * of indicator 50. The parameter must be passed with a character * value of 1 or 0. * C *ENTRY PLIST C *IN50 PARM SWITCH 1 * * * Subroutine SUB1 uses indicators 61 through 68. Before the * subroutine is processed, the status of these indicators used in * the mainline program is saved. (Assume that the indicators are * set off in the beginning of the subroutine.) After the subroutine * is processed, the indicators are returned to their original state. * * C MOVEA *IN(61) SAV8 8 C EXSR SUB1 C MOVEA SAV8 *IN(61) * * A code field (CODE) contains a numeric value of 1 to 5 and is * used to set indicators 71 through 75. The five indicators are set * off. Field X is calculated as 70 plus the CODE field. Field X is * then used as the index into the array *IN. Different subroutines * are then used based on the status of indicators 71 through 75. * C MOVEA 00000 *IN(71) C 70 ADD CODE X 3 0 C MOVE *ON *IN(X) C 71 EXSR CODE1 C 72 EXSR CODE2 C 73 EXSR CODE3 C 74 EXSR CODE4 C 75 EXSR CODE5 Figure 3-31. Examples of Indicators Referred to as Data
Summary of Indicators
Table 3-2 on page 3-66 and Table 3-3 on page 3-67 show summaries of where RPG IV indicators are defined, what the valid entries are, where the indicators are used, and when the indicators are set on and off. Table 3-3 on page 3-67
RPG IV Concepts
3-65
Summary of Indicators
page 3-66 indicates the primary condition that causes each type of indicator to be set on and set off by the RPG IV program. Function Key Indicators on page 3-57 lists the function key indicators and the corresponding function keys.
Table 3-2. Indicator Entries and Uses Where Defined/Used Overflow indicator, file description specifications, OFLIND keyword Record identifying indicator input specifications, positions 21-22 User Defined Control level, input specifications, positions 63-64 Field level, input specifications, positions 69-74 Resulting indicator, calculation specifications, positions 71-76 RPG Defined Internal Indicator External Indicator File conditioning, file description specifications File record relation, input specifications 67-683 Control level, calculation specifications, positions 7-8 Conditioning indicators, calculation specifications, positions 9-11 Output indicators, output specifications, positions 21-29 Note: 1. The overflow indicator must be defined on the file description specification first. 2. KA through KN and KP through KY can be used as resulting indicators only with the SETOFF operation. 3. Only a record identifying indicator from a main or OR record can be used to condition a control or match field. L1 or L9 cannot be used to condition a control or match field. 4. The 1P indicator is allowed only on heading and detail lines. X X X X X X X X 01-99 X 1P H1-H9 L1-L9 LR MR OA-OG OV X U1-U8 KA-KN KP-KY RT
X1
X2
X X X
Used
X4
3-66
Summary of Indicators
Table 3-3. When Indicators Are Set On and Off by the RPG IV Logic Cycle Type of Indicator Overflow Set On When printing on or spacing or skipping past the overflow line. Set Off OA-OG, OV: After the following heading and detail lines are completed, or after the file is opened unless the H-specification keyword OPENOPT(*NOINZOFL) is used. 01-99: By the user. Before the next primary/secondary record is read during the next processing cycle.
Record identifying
When specified primary / secondary record has been read and before total calculations are processed; immediately after record is read from a full procedural file. When the value in a control field changes. All lower level indicators are also set on. By blank or zero in specified fields, by plus in specified field, or by minus in specified field.
At end of following detail cycle. Before this field status is to be tested the next time.
Resulting
When the calculation is processed and the The next time a calculation is processed for condition that the indicator represents is met. which the same indicator is specified as a resulting indicator and the specified condition is not met. When the corresponding function key is pressed for WORKSTN files and at subsequent reads to associated subfiles. By SETOFF or move fields logic for a WORKSTN file.
Function key
External U1-U8
By CL command prior to beginning the By CL command prior to beginning the program, or when used as a resulting or program, or when used as a resulting or a when used as a resulting or a field indicator. field indicator. Note: The value of the external indicators is set from the job switches during initialization. For a cycle module, it is done during the *INIT phase of the cycle; for other modules, it is done only once, when the first procedure in the module is called. As specified by programmer. When the continue option is selected as a response to a message, or by the programmer. When the program is called again. Before the first record is read. At the beginning of processing, or by the programmer. When all total calculations and output are completed for the last record of the matching group.
H1-H9
RT Internal Indicators 1P LR MR
As specified by programmer. At beginning of processing before any input records are read. After processing the last primary/secondary record of the last file or by the programmer. If the match field contents of the record of a secondary file correspond to the match field contents of a record in the primary file.
RPG IV Concepts
3-67
File Exception/Errors
File Exception/Errors
Some examples of file exception/errors are: undefined record type, an error in trigger program, an I/O operation to a closed file, a device error, and an array/table load sequence error. They can be handled in one of the following ways: v The operation code extender 'E' can be specified. When specified, before the operation begins, this extender sets the %ERROR and %STATUS built-in functions to return zero. If an exception/error occurs during the operation, then after the operation %ERROR returns '1' and %STATUS returns the file status. The optional file information data structure is updated with the exception/error information. You can determine the action to be taken by testing %ERROR and %STATUS. v An indicator can be specified in positions 73 and 74 of the calculation specifications for an operation code. This indicator is set on if an exception/error occurs during the processing of the specified operation. The optional file information data structure is updated with the exception/error information. You can determine the action to be taken by testing the indicator. v ON-ERROR groups can be used to handle errors for statements processed within a MONITOR block. If an error occurs when a statement is processed, control passes to the appropriate ON-ERROR group. v You can create a user-defined ILE exception handler that will take control when an exception occurs. For more information, see Rational Development Studio for i: ILE RPG Programmer's Guide. v A file exception/error subroutine can be specified for a global file in a cycle module. The subroutine is defined by the INFSR keyword on a file description specification with the name of the subroutine that is to receive the control. Information regarding the file exception/error is made available through a file information data structure that is specified with the INFDS keyword on the file description specification. You can also use the %STATUS built-in function, which returns the most recent value set for the program or file status. If a file is specified, %STATUS returns the value contained in the INFDS *STATUS field for the specified file. v If the indicator, 'E' extender, MONITOR block, or file exception/error subroutine is not present, any file exception/errors are handled by the RPG IV default error handler.
3-68
File Exception/Errors
File Feedback Information: The file feedback information starts in position 1 and ends in position 80 in the file information data structure. The file feedback information contains data about the file which is specific to RPG. This includes information about the error/exception that identifies: v The name of the file for which the exception/error occurred v The record being processed when the exception/error occurred or the record that caused the exception/error v The last operation being processed when the exception/error occurred v The status code v The RPG IV routine in which the exception/error occurred. The fields from position 1 to position 66 in the file feedback section of the INFDS are always provided and updated even if INFDS is not specified in the program. The fields from position 67 to position 80 of the file feedback section of the INFDS are only updated after a POST operation to a specific device. If INFDS is not specified, the information in the file feedback section of the INFDS can be output using the DUMP operation. For more information see DUMP (Program Dump) on page 6-187. Overwriting the file feedback section of the INFDS may cause unexpected results in subsequent error handling and is not recommended. The location of some of the more commonly used subfields in the file feedback section of the INFDS is defined by special keywords. The contents of the file feedback section of the INFDS along with the special keywords and their descriptions can be found in the following tables:
Table 3-4. Contents of the File Feedback Information Available in the File Information Data Structure (INFDS) From (Pos. 26-32) 1 9 10 11 To (Pos. 33-39) 8 9 10 15
Length 8 1 1 5,0
Keyword *FILE
Information The first 8 characters of the file name. Open indication (1 = open). End of file (1 = end of file)
*STATUS
Status code. For a description of these codes, see File Status Codes on page 3-80.
RPG IV Concepts
3-69
File Exception/Errors
Table 3-4. Contents of the File Feedback Information Available in the File Information Data Structure (INFDS) (continued) From (Pos. 26-32) 16 To (Pos. 33-39) 21
Format Character
Length 6
Keyword *OPCODE
Information Operation code The first five positions (left-adjusted) specify the type of operation by using the character representation of the calculation operation codes. For example, if a READE was being processed, READE is placed in the leftmost five positions. If the operation was an implicit operation (for example, a primary file read or update on the output specifications), the equivalent operation code is generated (such as READ or UPDAT) and placed in location *OPCODE. Operation codes which have 6 letter names will be shortened to 5 letters. DELETE DELET EXCEPT EXCPT READPE REDPE UNLOCK UNLCK UPDATE UPDAT The remaining position contains one of the following: F R I The last operation was specified for a file name. The last operation was specified for a record. The last operation was an implicit file operation.
22
29
Character
*ROUTINE
First 8 characters of the name of the routine (including a subprocedure) in which the file operation was done. If OPTION(*NOSRCSTMT) is specified, this is the source listing line number of the file operation. If OPTION(*SRCSTMT) is specified, this is the source listing statement number of the file operation. The full statement number is included when it applies to the root source member. If the statement number is greater than 6 digits, that is, it includes a source ID other than zero, the first 2 positions of the 8-byte feedback area will have a "+ " indicating that the rest of the statement number is stored in positions 53-54. User-specified reason for error on SPECIAL file.
30
37
Character
38
42
Zoned decimal
5,0
3-70
File Exception/Errors
Table 3-4. Contents of the File Feedback Information Available in the File Information Data Structure (INFDS) (continued) From (Pos. 26-32) 38 To (Pos. 33-39) 45
Format Character
Length 8
Keyword *RECORD
Information For a program described file the record identifying indicator is placed left-adjusted in the field; the remaining six positions are filled with blanks. For an externally described file, the first 8 characters of the name of the record being processed when the exception/error occurred. Machine or system message number. Unused. Source Id matching the statement number from positions 30-37.
46 53 77
52 66 78
7 14 2
Table 3-5. Contents of the File Feedback Information Available in the File-Information Data Structure (INFDS) Valid after a POST From (Pos. 26-32) 67 71 To (Pos. 33-39) 70 72
Information Screen size (product of the number of rows and the number of columns on the device screen). The display's keyboard type. Set to 00 if the keyboard is alphanumeric or katakana. Set to 10 if the keyboard is ideographic. The display type. Set to 00 if the display is alphanumeric or katakana. Set to 10 if the display is ideographic. Set to 20 if the display is DBCS. Always set to 00.
73
74
Zoned decimal
2,0
*OUT
75
76
Zoned decimal
2,0
*MODE
INFDS File Feedback Example: To specify an INFDS which contains fields in the file feedback section, you can make the following entries: v Specify the INFDS keyword on the file description specification with the name of the file information data structure v Specify the file information data structure and the subfields you wish to use on a definition specification. v Specify special keywords as the first keyword of a free-form subfield definition, or left-adjusted, in the FROM field (positions 26-32) on the definition specification, or specify the positions of the fields in the FROM field (position 26-32) and the TO field (position 33-39).
| | |
RPG IV Concepts
3-71
File Exception/Errors
| DCL-F MYFILE DISK(*EXT) INFDS(FILEFBK); | DCL-DS FILEFBK; | FILE *FILE; // File name | OPEN_IND IND POS(9); // File open? | EOF_IND IND POS(10: // File at eof? | STATUS *STATUS; // Status code | OPCODE *OPCODE; // Last opcode | ROUTINE *ROUTINE; // RPG Routine | LIST_NUM CHAR(8) POS(30); // Listing line | SPCL_STAT ZONED(5) POS(38); // SPECIAL status | RECORD *RECORD; // Record name | MSGID CHAR(7) POS(46); // Error MSGID | SCREEN *SIZE; // Screen size | NLS_IN *INP; // NLS Input? | NLS_OUT *OUT; // NLS Output? | NLS_MODE *MODE; // NLS Mode? | END-DS; | | | | Figure 3-32. Example of Coding an INFDS with File Feedback Information in free form |
FFilename++IPEASFRlen+LKlen+AIDevice+.Keywords+++++++++++++++++++++++++++++Comments++++++++++ FMYFILE IF E DISK INFDS(FILEFBK) DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++Comments++++++++++ DFILEFBK DS D FILE *FILE * File name D OPEN_IND 9 9N * File open? D EOF_IND 10 10N * File at eof? D STATUS *STATUS * Status code D OPCODE *OPCODE * Last opcode D ROUTINE *ROUTINE * RPG Routine D LIST_NUM 30 37 * Listing line D SPCL_STAT 38 42S 0 * SPECIAL status D RECORD *RECORD * Record name D MSGID 46 52 * Error MSGID D SCREEN *SIZE * Screen size D NLS_IN *INP * NLS Input? D NLS_OUT *OUT * NLS Output? D NLS_MODE *MODE * NLS Mode? Figure 3-33. Example of Coding an INFDS with File Feedback Information in fixed form
Note: The keywords are not labels and cannot be used to access the subfields. Short entries are padded on the right with blanks. Open Feedback Information: Positions 81 through 240 in the file information data structure contain open feedback information. The contents of the file open feedback area are copied by RPG to the open feedback section of the INFDS whenever the file associated with the INFDS is opened. This includes members opened as a result of a read operation on a multi-member processed file. A description of the contents of the open feedback area, and what file types the fields are valid for, can be found in the IBM i Information Center. INFDS Open Feedback Example: To specify an INFDS which contains fields in the open feedback section, you can make the following entries: v Specify the INFDS keyword on the file description specification with the name of the file information data structure v Specify the file information data structure and the subfields you wish to use on a definition specification.
3-72
File Exception/Errors
v Use information in the IBM i Information Center database and file systems category to determine which fields you wish to include in the INFDS. To calculate the starting position and length of the subfields of the open feedback section of the INFDS, use the Offset, Data Type, and Length given in the Information Center and do the following calculations: Start = 81 + Offset Character_Length = Length (in bytes) For example, for overflow line number of a printer file, the Information Center gives: Offset = 107 Data Type is binary Length = 2 bytes Therefore, Start = 81 + 107 = 188 RPG data type is integer Length = 5 digits See subfield OVERFLOW in the example below.
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
DCL-F MYFILE PRINTER(132) INFDS(OPNFBK); DCL-DS OPNFBK; ODP_TYPE FILE_NAME LIBRARY SPOOL_FILE SPOOL_LIB SPOOL_NUM_OLD RCD_LEN KEY_LEN MEMBER TYPE ROWS COLUMNS NUM_RCDS SPOOL_NUM VOL_OFF BLK_RCDS OVERFLOW BLK_INCR FLAGS1 REQUESTER OPEN_COUNT BASED_MBRS FLAGS2 OPEN_ID RCDFMT_LEN CCSID FLAGS3 NUM_DEVS END-DS; CHAR(2) CHAR(10) CHAR(10) CHAR(10) CHAR(10) INT(5) INT(5) INT(5) CHAR(10) INT(5) INT(5) INT(5) INT(10) INT(10) INT(5) INT(5) INT(5) INT(5) CHAR(1) CHAR(10) INT(5) INT(5) CHAR(1) CHAR(2) INT(5) INT(5) CHAR(1) INT(5) POS(81); POS(83); POS(93); POS(103); POS(113); POS(123); POS(125); POS(127); POS(129); POS(147); POS(152); POS(154); POS(156); POS(160); POS(184); POS(186); POS(188); POS(190); POS(196); POS(197); POS(207); POS(211); POS(213); POS(214); POS(216); POS(218); POS(220); POS(227); // // // // // // // // // // // // // // // // // // // // // // // // // // // // ODP Type File name Library name Spool file name Spool file lib Spool file num Max record len Max key len Member name File type Num PRT/DSP rows Num PRT/DSP cols Num of records 6 digit Spool Nbr Vol label offset Max rcds in blk Overflow line Blk increment Misc flags Requester name Open count Num based mbrs Misc flags Open identifier Max rcd fmt len Database CCSID Misc flags Num devs defined
Input/Output Feedback Information: Positions 241 through 366 in the file information data structure are used for input/output feedback information. The contents of the file common input/output feedback area are copied by RPG to the input/output feedback section of the INFDS: v If the presence of a POST operation affects the file: only after a POST for the file.
RPG IV Concepts
3-73
File Exception/Errors
v Otherwise: after each I/O operation, if blocking is not active for the file. after the I/O request to data management to get or put a block of data, if blocking is active for the file. For more information see POST (Post) on page 6-268. A description of the contents of the input/output feedback area can be found in the Information Center. INFDS Input/Output Feedback Example: To specify an INFDS which contains fields in the input/output feedback section, you can make the following entries: v Specify the INFDS keyword on the file description specification with the name of the file information data structure v Specify the file information data structure and the subfields you wish to use on a definition specification. v Use information in the Information Center to determine which fields you wish to include in the INFDS. To calculate the starting position and length of the subfields of the input/output feedback section of the INFDS, use the Offset, Data Type, and Length given in the Information Center and do the following calculations: Start = 241 + Offset Character_Length = Length (in bytes) For example, for device class of a file, the Information Center gives: Offset = 30 Data Type is character Length = 2 Therefore, Start = 241 + 30 = 271 See subfield DEV_CLASS in the example below
| DCL-F MYFILE WORKSTN INFDS(MYIOFBK); | DCL-DS MYIOFBK; | // 241-242 not used | WRITE_CNT INT(10) POS(243); // Write count | READ_CNT INT(10) POS(247); // Read count | WRTRD_CNT INT(10) POS(251); // Write/read count | OTHER_CNT INT(10) POS(255); // Other I/O count | OPERATION CHAR(1) POS(260); // Current operation | IO_RCD_FMT CHAR(10) POS(261); // Rcd format name | DEV_CLASS CHAR(2) POS(271); // Device class | IO_PGM_DEV CHAR(10) POS(273); // Pgm device name | IO_RCD_LEN INT(10) POS(283); // Rcd len of I/O | END-DS; | | | | Figure 3-35. Example of Coding an INFDS with Input/Output Feedback Information | Device Specific Feedback Information: The device specific feedback information in the file information data structure starts at position 367 in the INFDS, and contains input/output feedback information specific to a device.
3-74
File Exception/Errors
The length of the INFDS when device specific feedback information is required, depends on two factors: the device type of the file, and on whether DISK files are keyed or not. The minimum length is 528; but some files require a longer INFDS. v For WORKSTN files, the INFDS is long enough to hold the device-specific feedback information for any type of display or ICF file starting at position 241. For example, if the longest device-specific feedback information requires 390 bytes, the INFDS for WORKSTN files is 630 bytes long (240+390=630). v For externally described DISK files, the INFDS is at least long enough to hold the longest key in the file beginning at position 401. More information on the contents and length of the device feedback for database file, printer files, ICF and display files can be found in the IBM i Information Center database and file systems category. The contents of the device specific input/output feedback area of the file are copied by RPG to the device specific feedback section of the INFDS: v If the presence of a POST operation affects the file: only after a POST for the file. v Otherwise: after each I/O operation, if blocking is not active for the file. after the I/O request to data management to get or put a block of data, if blocking is active for the file. Note: 1. After each keyed input operation, only the key fields will be updated. 2. After each non-keyed input operation, only the relative record number will be updated. For more information see POST (Post) on page 6-268. INFDS Device Specific Feedback Examples: To specify an INFDS which contains fields in the device-specific feedback section, you can make the following entries: v Specify the INFDS keyword on the file description specification with the name of the file information data structure v Specify the file information data structure and the subfields you wish to use on a definition specification. v Use information in the Information Center to determine which fields you wish to include in the INFDS. To calculate the starting position and length of the subfields of the input/output feedback section of the INFDS, use the Offset, Data Type, and Length given in the Information Center and do the following calculations: Start = 367 + Offset Character_Length = Length (in bytes) For example, for the relative record number of a data base file, the Information Center gives: Offset = 30 Data Type is binary Length = 4 Therefore, Start = 367 + 30 = 397 RPG data type is integer Length = 10 digits See subfield DB_RRN in DBFBK data structure in the example below.
RPG IV Concepts
| | | | | | | | | | | | | | |
3-75
File Exception/Errors
| DCL-F MYFILE PRINTER(132) INFDS(PRTFBK); | DCL-DS PRTFBK; | CUR_LINE INT(5) POS(367); // Current line num | CUR_PAGE INT(10) POS(369); // Current page cnt | // If the first bit of PRT_FLAGS is on, the spooled file has been | // deleted. Use TESTB X80 or TESTB 0 to test this bit. | PRT_FLAGS CHAR(1) POS(373); // Print Flags | PRT_MAJOR CHAR(2) POS(401); // Major ret code | PRT_MINOR CHAR(2) POS(403); // Minor ret code | END-DS; | | | | Figure 3-36. Example of Coding an INFDS with Printer Specific Feedback Information |
DCL-F MYFILE DISK(*EXT) INFDS(DBFBK); | | DCL-DS DBFBK; | FDBK_SIZE INT(10) POS(367); // Current line num | JOIN_BITS INT(10) POS(371); // JFILE bits | LOCK_RCDS INT(5) POS(377); // Nbr locked rcds | POS_BITS CHAR(1) POS(385); // File pos bits | DLT_BITS CHAR(1) POS(384); // Rcd deleted bits | NUM_KEYS INT(5) POS(387); // Num keys (bin) | KEY_LEN INT(5) POS(393); // Key length | MBR_NUM INT(5) POS(395); // Member number | DB_RRN INT(10) POS(397); // Relative-rcd-num | KEY CHAR(2000) POS(401); // Key value (max size 2000) | END-DS; | | | | Figure 3-37. Example of Coding an INFDS with Database Specific Feedback Information | DCL-F MYFILE WORKSTN(*EXT) INFDS(ICFFBK); | | DCL-DS ICFFBK; | ICF_AID CHAR(1) POS(369); // AID byte | ICF_LEN INT(10) POS(372); // Actual data len | ICF_MAJOR CHAR(2) POS(401); // Major ret code | ICF_MINOR CHAR(2) POS(403); // Minor ret code | SNA_SENSE CHAR(8) POS(405); // SNA sense rc | SAFE_IND CHAR(1) POS(413); // Safe indicator | RQSWRT CHAR(1) POS(415); // Request write | RMT_FMT CHAR(10) POS(416); // Remote rcd fmt | ICF_MODE CHAR(8) POS(430); // Mode name | END-DS; | | | | Figure 3-38. Example of Coding an INFDS with ICF Specific Feedback Information |
3-76
File Exception/Errors
| | | | | | | | | | | | | | | | | |
DCL-F MYFILE WORKSTN(*EXT) INFDS(DSPFBK); DCL-DS DSPFBK; DSP_FLAG1 DSP_AID CURSOR DATA_LEN SF_RRN MIN_RRN NUM_RCDS ACT_CURS DSP_MAJOR DSP_MINOR END-DS; CHAR(2) CHAR(1) CHAR(2) INT(10) INT(5) INT(5) INT(5) CHAR(2) CHAR(2) CHAR(2) POS(367); POS(369); POS(370); POS(372); POS(376); POS(378); POS(380); POS(382); POS(401); POS(403); // // // // // // // // // // Display flags AID byte Cursor location Actual data len Subfile rrn Subfile min rrn Subfile num rcds Active window cursor location Major ret code Minor ret code
Figure 3-39. Example of Coding an INFDS with Display Specific Feedback Information
Get Attributes Feedback Information: The get attributes feedback information in the file information data structure starts at position 241 in the INFDS, and contains information about a display device or ICF session (a device associated with a WORKSTN file). The end position of the get attributes feedback information depends on the length of the data returned by a get attributes data management operation. The get attributes data management operation is performed when a POST with a program device specified for factor 1 is used. More information about the contents and the length of the get attributes data can be found in the Information Center. INFDS Get Attributes Feedback Example: To specify an INFDS which contains fields in the get attributes feedback section, you can make the following entries: v Specify the INFDS keyword on the file description specification with the name of the file information data structure v Specify the file information data structure and the subfields you wish to use on a definition specification. v Use information in the Information Center to determine which fields you wish to include in the INFDS. To calculate the starting position and length of the subfields of the get attributes feedback section of the INFDS, use the Offset, Data Type, and Length given in the Information Center and do the following calculations: Start = 241 + Offset Character_Length = Length (in bytes) For example, for device type of a file, the Information Center gives: Offset = 31 Data Type is character Length = 6 Therefore, Start = 241 + 31 = 272 See subfield DEV_TYPE in the example below.
RPG IV Concepts
3-77
File Exception/Errors
| DCL-F MYFILE WORKSTN INFDS(DSPATRFBK); | DCL-DS DSPATRFBK; | PGM_DEV CHAR(10) POS(241); // Program device | DEV_DSC CHAR(10) POS(251); // Dev description | USER_ID CHAR(10) POS(261); // User ID | DEV_CLASS CHAR(1) POS(271); // Device class | DEV_TYPE CHAR(6) POS(272); // Device type | REQ_DEV CHAR(1) POS(278); // Requester? | ACQ_STAT CHAR(1) POS(279); // Acquire status | INV_STAT CHAR(1) POS(280); // Invite status | DATA_AVAIL CHAR(1) POS(281); // Data available | NUM_ROWS INT(5) POS(282); // Number of rows | NUM_COLS INT(5) POS(284); // Number of cols | BLINK CHAR(1) POS(286); // Allow blink? | LINE_STAT CHAR(1) POS(287); // Online/offline? | DSP_LOC CHAR(1) POS(288); // Display location | DSP_TYPE CHAR(1) POS(289); // Display type | KBD_TYPE CHAR(1) POS(290); // Keyboard type | CTL_INFO CHAR(1) POS(342); // Controller info | COLOR_DSP CHAR(1) POS(343); // Color capable? | GRID_DSP CHAR(1) POS(344); // Grid line dsp? | // The following fields apply to ISDN. | ISDN_LEN INT(5) POS(385); // Rmt number len | ISDN_TYPE CHAR(2) POS(387); // Rmt number type | ISDN_PLAN CHAR(2) POS(389); // Rmt number plan | ISDN_NUM CHAR(40) POS(391); // Rmt number | ISDN_SLEN INT(5) POS(435); // Rmt sub-address length | ISDN_STYPE CHAR(2) POS(437); // Rmt sub-address type | ISDN_SNUM CHAR(40) POS(439); // Rmt sub-address | ISDN_CON CHAR(1) POS(480); // Connection | ISDN_RLEN INT(5) POS(481); // Rmt address len | ISDN_RNUM CHAR(32) POS(483); // Rmt address | ISDN_ELEN INT(5) POS(519); // Extension len | ISDN_ETYPE CHAR(1) POS(521); // Extension type | ISDN_ENUM CHAR(40) POS(522); // Extension num | ISDN_XTYPE CHAR(1) POS(566); // X.25 call type | END-DS; | | | | Figure 3-40. Example of Coding an INFDS with Display file Get Attributes Feedback Information |
3-78
File Exception/Errors
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
DCL-F MYFILE WORKSTN INFDS(ICFATRFBK); DCL-DS ICFATRFBK; PGM_DEV CHAR(10) DEV_DSC CHAR(10) USER_ID CHAR(10) DEV_CLASS CHAR(1) DEV_TYPE CHAR(1) REQ_DEV CHAR(1) ACQ_STAT CHAR(1) INV_STAT CHAR(1) DATA_AVAIL CHAR(1) SES_STAT CHAR(1) SYNC_LVL CHAR(1) CONV_TYPE CHAR(1) RMT_LOC CHAR(10) LCL_LU CHAR(8) LCL_NETID CHAR(8) RMT_LU CHAR(8) RMT_NETID CHAR(8) APPC_MODE CHAR(8) LU6_STATE CHAR(1) LU6_COR CHAR(8) // The following fields ISDN_LEN INT(5) ISDN_TYPE CHAR(2) ISDN_PLAN CHAR(2) ISDN_NUM CHAR(40) ISDN_SLEN INT(5) ISDN_STYPE CHAR(2) ISDN_SNUM CHAR(40) ISDN_CON CHAR(1) ISDN_RLEN INT(5) ISDN_RNUM CHAR(32) ISDN_ELEN CHAR(2) ISDN_ETYPE CHAR(1) ISDN_ENUM CHAR(40) ISDN_XTYPE CHAR(1) POS(241); // POS(251); // POS(261); // POS(271); // POS(272); // POS(278); // POS(279); // POS(280); // POS(281); // POS(291); // POS(292); // POS(293); // POS(294); // POS(302); // POS(310); // POS(318); // POS(326); // POS(334); // POS(345); // POS(346); // apply to ISDN. POS(385); // POS(387); // POS(389); // POS(391); // POS(435); // POS(437); // POS(439); // POS(480); // POS(481); // POS(483); // POS(519); // POS(521); // POS(522); // POS(566); // Program device Dev description User ID Device class Device type Requester? Acquire status Invite status Data available Session status Synch level Conversation typ Remote location Local LU name Local net ID Remote LU Remote net ID APPC Mode LU6 conv state LU6 conv correlator Rmt number len Rmt number type Rmt number plan Rmt number sub-addr len sub-addr type Rmt sub-address Connection Rmt address len Rmt address Extension len Extension type Extension num X.25 call type
// The following information is available only when program was started // as result of a received program start request. (P_ stands for protected) TRAN_PGM CHAR(64) POS(567); // Trans pgm name P_LUWIDLN CHAR(1) POS(631); // LUWID fld len P_LUNAMELN CHAR(1) POS(632); // LU-NAME len P_LUNAME CHAR(17) POS(633); // LU-NAME P_LUWIDIN CHAR(6) POS(650); // LUWID instance P_LUWIDSEQ INT(5) POS(656); // LUWID seq num // The following information is available only when a protected conversation // is started on a remote system. (U_ stands for unprotected) U_LUWIDLN CHAR(1) POS(658); // LUWID fld len U_LUNAMELN CHAR(1) POS(659); // LU-NAME len U_LUNAME CHAR(17) POS(660); // LU-NAME U_LUWIDIN CHAR(6) POS(677); // LUWID instance U_LUWIDSEQ INT(5) POS(683); // LUWID seq num END-DS; Figure 3-41. Example of Coding an INFDS with ICF file Get Attributes Feedback Information
Blocking Considerations: The fields of the input/output specific feedback in the INFDS and in most cases the fields of the device specific feedback information section of the INFDS, are not updated for each operation to the file in which the records are blocked and unblocked. The feedback information is updated only when a block of records is transferred between an RPG program and the operating system. However, if you are doing blocked input on a data base file, the relative record number and the key value in the data base feedback section of the INFDS are updated:
RPG IV Concepts
3-79
File Exception/Errors
v On every input/output operation, if the file is not affected by the presence of a POST operation in the program. v Only after a POST for the file, if file is affected by a POST operation in the program. See POST (Post) on page 6-268. You can obtain valid updated feedback information by using the CL command OVRDBF (Override with Database File) with SEQONLY(*NO) specified. If you use a file override command, the ILE RPG compiler does not block or unblock the records in the file. For more information on blocking and unblocking of records in RPG see Rational Development Studio for i: ILE RPG Programmer's Guide. File Status Codes: Any code placed in the subfield location *STATUS that is greater than 99 is considered to be an exception/error condition. When the status code is greater than 99; the error indicator if specified in positions 73 and 74 is set on, or the %ERROR built-in function if the 'E' extender is specified is set to return '1'; otherwise, the file exception/error subroutine receives control. Location *STATUS is updated after every file operation. You can use the %STATUS built-in function to get information on exception/errors. It returns the most recent value set for the program or file status. If a file is specified, %STATUS returns the value contained in the INFDS *STATUS field for the specified file. The codes in the following tables are placed in the subfield location *STATUS for the file information data structure:
Table 3-6. Normal Codes Code 00000 00002 00011 00012 00013
1
Device1
RC2
Condition No exception/error.
W W,D,SQ W,D,SQ W
Function key used to end display. End of file on a read (input). No-record-found condition on a CHAIN, SETLL, and SETGT operations. Subfile is full on WRITE operation.
Note: Device refers to the devices for which the condition applies. The following abbreviations are used: P = PRINTER; D = DISK; W = WORKSTN; SP = SPECIAL; SQ = Sequential. The major/minor return codes under column RC apply only to WORKSTN files. 2The formula mmnn is used to described major/minor return codes: mm is the major and nn the minor. Table 3-7. Exception/Error Codes Code 01011 01021 Device1 W,D,SQ W,D,SQ RC2 n/a n/a Condition Undefined record type (input record does not match record identifying indicator). Tried to write a record that already exists (file being used has unique keys and key is duplicate, or attempted to write duplicate relative record number to a subfile). Referential constraint error detected on file member. Error in trigger program before file operation performed. Error in trigger program after file operation performed. Match field out of sequence. Array/table load sequence error.
3-80
File Exception/Errors
Table 3-7. Exception/Error Codes (continued) Code 01042 01051 01061 01071 01121 01122 01123 01124 01125 01126
4 4 4 4 4 4
RC2 n/a n/a n/a n/a n/a n/a n/a n/a n/a n/a 34xx n/a n/a yes yes n/a n/a n/a n/a n/a n/a 80xx 81xx 82xx 83xx n/a n/a n/a 0309 n/a 0800 n/a n/a yes 0310
Condition Array/table load sequence error. Alternate collating sequence used. Excess entries in array/table file. Error handling for an associated variable for a file parameter Numeric sequence error. No indicator on the DDS keyword for Print key. No indicator on the DDS keyword for Roll Up key. No indicator on the DDS keyword for Roll Down key. No indicator on the DDS keyword for Clear key. No indicator on the DDS keyword for Help key. No indicator on the DDS keyword for Home key. Record mismatch detected on input. I/O operation to a closed file. OPEN issued to a file already opened. Error on an implicit OPEN/CLOSE operation. Error on an explicit OPEN/CLOSE operation. Record already locked. Update operation attempted without a prior read. Record cannot be allocated due to referential constraint error Error on SPECIAL file. Error in PRTCTL space or skip entries. Record number not found. (Record number specified in record address file is not present in file being processed.) Permanent I/O error occurred. Session or device error occurred. Recovery may be possible. Attempt to exceed maximum number of acquired devices. Attempt to acquire unavailable device Operation to unacquired device. Job ending with controlled option. Unable to acquire second device for single device file Attempt to acquire a device already acquired. Attempt to open shared file with SAVDS or IND options. Response indicators overlap IND indicators. Other I/O error detected. Wait time exceeded for READ from WORKSTN file.
01201 01211 01215 01216 01217 01218 01221 01222 01231 01235 01241 01251 01255 01261 01271 01281 01282 01284 01285 01286 01287 01299 01331
RPG IV Concepts
3-81
File Exception/Errors
Table 3-7. Exception/Error Codes (continued) Code Note: 1. Device refers to the devices for which the condition applies. The following abbreviations are used: P = PRINTER; D = DISK; W = WORKSTN; SP = SPECIAL; SQ = Sequential. The major/minor return codes under column RC apply only to WORKSTN files. 2. The formula mmnn is used to described major/minor return codes: mm is the major and nn the minor. 3. Any errors that occur during an open or close operation will result in a *STATUS value of 1216 or 1217 regardless of the major/minor return code value. 4. See Figure 3-13 on page 3-36 for special handling. Device1 RC2 Condition
The following table shows the major/minor return code to *STATUS value mapping for errors that occur to programs using WORKSTN files only. See the Information Center for more information on major/minor return codes.
Major 00,02 03 03 03 04 08 11 34 80,81 82,83 Note: 1. The return code field will not be updated for a *STATUS value of 1285, 1261, or 1281 because these conditions are detected before calling data management. To monitor for these errors, you must check for the *STATUS value and not for the corresponding major/minor return code value. Minor all all (except 09,10) 09 10 all all all all all all *STATUS 00000 00000 01282 01331 01299 012851 00011 01201 01251 01255
3-82
File Exception/Errors
can use a MONITOR group to handle errors for several operations. The ON-ERROR section of your MONITOR group could call a subprocedure to handle the details of the error handling. The ENDSR operation must be the last specification for the file exception/error subroutine and should be specified as follows: Position Entry 6 7-11 12-25 26-35 36-49 C Blank Can contain a label that is used in a GOTO specification within the subroutine. ENDSR Optional entry to designate where control is to be returned following processing of the subroutine. The entry must be a 6-position character field, literal, or array element whose value specifies one of the following return points. Note: If the return points are specified as literals, they must be enclosed in apostrophes. If they are specified as named constants, the constants must be character and must contain only the return point with no leading blanks. If they are specified in fields or array elements, the value must be left-adjusted in the field or array element. *DETL Continue at the beginning of detail lines. *GETIN Continue at the get input record routine. *TOTC Continue at the beginning of total calculations. *TOTL Continue at the beginning of total lines. *OFL *DETC Continue at the beginning of detail calculations. *CANCL Cancel the processing of the program. Blanks Return control to the RPG IV default error handler. This applies when factor 2 is a value of blanks and when factor 2 is not specified. If the subroutine was called by the EXSR operation and factor 2 is blank, control returns to the next sequential instruction. Blanks are only valid at runtime. 50-76 Blank. Continue at the beginning of overflow lines.
Remember the following when specifying the file exception/error subroutine: v The programmer can explicitly call the file exception/error subroutine by specifying the name of the subroutine in factor 2 of the EXSR operation. v After the ENDSR operation of the file exception/error subroutine is run, the RPG IV language resets the field or array element specified in factor 2 to blanks. Thus, if the programmer does not place a value in this field during the processing of the subroutine, the RPG IV default error handler receives control following processing of the subroutine unless the subroutine was called by the EXSR operation. Because factor 2 is set to blanks, the programmer can specify the return point within the subroutine that is best suited for the exception/error that occurred. If the subroutine was called by the EXSR
RPG IV Concepts
3-83
File Exception/Errors
operation and factor 2 of the ENDSR operation is blank, control returns to the next sequential instruction following the EXSR operation. A file exception/error subroutine can handle errors in more than one file. v If a file exception/error occurs during the start or end of a program, control passes to the RPG IV default error handler, and not to the user-written file exception/error or subroutine (INFSR). v Because the file exception/error subroutine may receive control whenever a file exception/error occurs, an exception/error could occur while the subroutine is running if an I/O operation is processed on the file in error. If an exception/error occurs on the file already in error while the subroutine is running, the subroutine is called again; this will result in a program loop unless the programmer codes the subroutine to avoid this problem. One way to avoid such a program loop is to set a first-time switch in the subroutine. If it is not the first time through the subroutine, set on a halt indicator and issue the RETURN operation as follows:
*...1....+....2....+....3....+....4....+....5....+....6....+....7... CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq.. C* If INFSR is already handling the error, exit. C C C C ERRRTN SW BEGSR IFEQ SETON RETURN 1 H1
Note: It may not be possible to continue processing the file after an I/O error has occurred. To continue, it may be necessary to issue a CLOSE operation and then an OPEN operation to the file.
Program Exception/Errors
Some examples of program exception/errors are: division by zero, SQRT of a negative number, invalid array index, error on a CALL, error return from called program, and start position or length out of range for a string operation. They can be handled in one of the following ways: v The operation code extender 'E' can be specified for some operation codes. When specified, before the operation begins, this extender sets the %ERROR and %STATUS built-in functions to return zero. If an exception/error occurs during the operation, then after the operation %ERROR returns '1' and
3-84
Program Exception/Errors
%STATUS returns the program status. The optional program status data structure is updated with the exception/error information. You can determine the action to be taken by testing %ERROR and %STATUS. v An indicator can be specified in positions 73 and 74 of the calculation specifications for some operation codes. This indicator is set on if an exception/error occurs during the processing of the specified operation. The optional program status data structure is updated with the exception/error information. You can determine the action to be taken by testing the indicator. v ON-ERROR groups can be used to handle errors for statements processed within a MONITOR block. If an error occurs when a statement is processed, control passes to the appropriate ON-ERROR group. v You can create a user-defined ILE exception handler that will take control when an exception occurs. For more information, see Rational Development Studio for i: ILE RPG Programmer's Guide. v A program exception/error subroutine can be specified. You enter *PSSR in factor 1 of a BEGSR operation to specify this subroutine. Information regarding the program exception/error is made available through a program status data structure that is specified with an S in position 23 of the data structure statement on the definition specifications. You can also use the %STATUS built-in function, which returns the most recent value set for the program or file status. v If the indicator, 'E' extender, monitor block, or program exception/error subroutine is not present, program exception/errors are handled by the RPG IV default error handler.
RPG IV Concepts
3-85
Program Exception/Errors
Table 3-8. Contents of the Program Status Data Structure From (Pos. 26-32) 1 To (Pos. 33-39) 10 Format Character Length 10 Keyword *PROC Information If the module was compiled with CRTRPGMOD, this is the name of the module that was created; if the program was created using CRTBNDRPG, this is the name of the program that was created. For a cycle-main module, this is the name of the main procedure. Status code. For a description of these codes, see Program Status Codes on page 3-89. Previous status code. RPG IV source listing line number or statement number. The source listing line number is replaced by the source listing statement number if OPTION(*SRCSTMT) is specified instead of OPTION(*NOSRCSTMT). The full statement number is included when it applies to the root source member. If the statement number is greater than 6 digits (that is, it includes a source ID other than zero), the first 2 positions of the 8-byte feedback area will have a "+ " indicating that the rest of statement number is stored in positions 354-355. *ROUTINE Name of the RPG IV routine in which the exception or error occurred. This subfield is updated at the beginning of an RPG IV routine or after a program call only when the *STATUS subfield is updated with a nonzero value. The following names identify the routines: *INIT Program initialization
11 16 21
15 20 28
5,0 5,0 8
*STATUS
29
36
Character
*DETL Detail lines *GETIN Get input record *TOTC Total calculations *TOTL Total lines *DETC Detail calculations *OFL *TERM Program ending *ROUTINE Name of program or procedure called (first 8 characters). Note: *ROUTINE is not valid unless you use the normal RPG IV cycle. Logic that takes the program out of the normal RPG IV cycle may cause *ROUTINE to reflect an incorrect value. Overflow lines
3-86
Program Exception/Errors
Table 3-8. Contents of the Program Status Data Structure (continued) From (Pos. 26-32) 37 To (Pos. 33-39) 39 Format Zoned decimal Length 3,0 Keyword *PARMS Information Number of parameters passed to this program from a calling program. The value is the same as that returned by %PARMS. If no information is available, -1 is returned. Exception type (CPF for an operating system exception or MCH for a machine exception). Exception number. For a CPF exception, this field contains a CPF message number. For a machine exception, it contains a machine exception number. Reserved Work area for messages. This area is only meant for internal use by the ILE RPG compiler. The organization of information will not always be consistent. It can be displayed by the user. Name of library in which the program is located. Retrieved exception data. CPF messages are placed in this subfield when location *STATUS contains 09999. Identification of the exception that caused RNX9001 exception to be signaled. Name of file on which the last file operation occurred (updated only when an error occurs). This information always contains the full file name. Unused. Date (*DATE format) the job entered the system. In the case of batch jobs submitted for overnight processing, those that run after midnight will carry the next day's date. This value is derived from the job date, with the year expanded to the full four years. The date represented by this value is the same date represented by positions 270 - 275. First 2 digits of a 4-digit year. The same as the first 2 digits of *YEAR. This field applies to the century part of the date in positions 270 to 275. For example, for the date 1999-06-27, UDATE would be 990627, and this century field would be 19. The value in this field in conjunction with the value in positions 270 - 275 has the combined information of the value in positions 191 -198. Note: This century field does not apply to the dates in positions 276 to 281, or positions 288 to 293. Name of file on which the last file operation occurred (updated only when an error occurs). This file name will be truncated if a long file name is used. See positions 175-184 for long file name information.
40 43
42 46
Character Character
3 4
47 51
50 80
Character Character
4 30
81 91
90 170
Character Character
10 80
171 175
174 184
Character Character
4 10
185 191
190 198
Character Character
6 8
199
200
Zoned decimal
2,0
201
208
Character
RPG IV Concepts
3-87
Program Exception/Errors
Table 3-8. Contents of the Program Status Data Structure (continued) From (Pos. 26-32) 209 To (Pos. 33-39) 243 Format Character Length 35 Keyword Information Status information on the last file used. This information includes the status code, the RPG IV opcode, the RPG IV routine name, the source listing line number or statement number, and record name. It is updated only when an error occurs. Note: The opcode name is in the same form as *OPCODE in the INFDS The source listing line number is replaced by the source listing statement number if OPTION(*SRCSTMT) is specified instead of OPTION(*NOSRCSTMT). The full statement number is included when it applies to the root source member. If the statement number is greater than 6 digits (that is, it includes a source ID other than zero), the first 2 positions of the 8-byte feedback area will have a "+ " indicating that the rest of statement number is stored in positions 356-357. Job name. User name from the user profile. Job number. Date (in UDATE format) the program started running in the system (UDATE is derived from this date). See User Date Special Words on page 3-5 for a description of UDATE. This is commonly known as the 'job date'. The date represented by this value is the same date represented by positions 191 - 198. Date of program running (the system date in UDATE format). If the year part of this value is between 40 and 99, the date is between 1940 and 1999. Otherwise the date is between 2000 and 2039. The 'century' value in positions 199 - 200 does not apply to this field. Time (in the format hhmmss) of the program running. Date (in UDATE format) the program was compiled. If the year part of this value is between 40 and 99, the date is between 1940 and 1999. Otherwise the date is between 2000 and 2039. The 'century' value in positions 199 - 200 does not apply to this field. Time (in the format hhmmss) the program was compiled. Level of the compiler. Source file name. Source library name. Source file member name. Program containing procedure.
10 10 6,0 6,0
276
281
Zoned decimal
6,0
282 288
287 293
6,0 6
6 4 10 10 10 10
3-88
Program Exception/Errors
Table 3-8. Contents of the Program Status Data Structure (continued) From (Pos. 26-32) 344 354 356 358 368 372 380 To (Pos. 33-39) 353 355 357 367 371 379 429 Format Character Binary Binary Character Integer Integer Character Length 10 2 2 10 10,0 20,0 50 Keyword Information Module containing procedure. Source Id matching the statement number from positions 21-28. Source Id matching the statement number from positions 228-235. Current user profile name. External error code XML elements set by operation Unused.
Program Status Codes: Any code placed in the subfield location *STATUS that is greater than 99 is considered to be an exception/error condition. When the status code is greater than 99; the error indicator if specified in positions 73 and 74 is set on, or the %ERROR built-in function if the 'E' extender is specified is set to return '1', or control passes to the appropriate ON-ERROR group within a MONITOR block; otherwise, the program exception/error subroutine receives control. Location *STATUS is updated when an exception/error occurs. The %STATUS built-in function returns the most recent value set for the program or file status. The following codes are placed in the subfield location *STATUS for the program status data structure: Normal Codes Code 00000 00001 00050 Condition No exception/error occurred Called program returned with the LR indicator on. Conversion resulted in substitution.
Exception/Error Codes Code 00100 00101 00102 00103 00104 00105 00112 00113 Condition Value out of range for string operation Negative square root Divide by zero An intermediate result is not large enough to contain the result. Float underflow. An intermediate value is too small to be contained in the intermediate result field. Invalid characters in character to numeric conversion functions. Invalid Date, Time or Timestamp value. Date overflow or underflow. (For example, when the result of a Date calculation results in a number greater than *HIVAL or less than *LOVAL.)
RPG IV Concepts
3-89
Program Exception/Errors
00114 00115 00120 00121 00122 00123 00202 00211 00222 00231 00232 00233 00299 00301 00302 00303 00304 00305 00306 00333 00351 00352 00353 00354 00401 00402 00411 00412 00413 00414 00415 00421 00425 00426 00431 00432 00450 Date mapping errors, where a Date is mapped from a 4-character year to a 2-character year, and the date range is not 1940-2039. Variable-length field has a current length that is not valid. Table or array out of sequence. Array index not valid OCCUR outside of range Reset attempted during initialization step of program Called program or procedure failed; halt indicator (H1 through H9) not on Error calling program or procedure Pointer or parameter error Called program or procedure returned with halt indicator on Halt indicator on in this program Halt indicator on when RETURN operation run RPG IV formatted dump failed Class or method not found for a method call, or error in method call. Error while converting a Java array to an RPG parameter on entry to a Java native method. Error converting RPG parameter to Java array on exit from an RPG native method. Error converting RPG parameter to Java array in preparation for a Java method call. Error converting Java array to RPG parameter or return value after a Java method. Error converting RPG return value to Java array. Error on DSPLY operation Error parsing XML document Invalid option for %XML XML document does not match RPG variable Error preparing for XML parsing Data area specified on IN/OUT not found *PDA not valid for non-prestart job Data area type or length does not match Data area not locked for output Error on IN/OUT operation User not authorized to use data area User not authorized to change data area Error on UNLOCK operation Length requested for storage allocation is out of range Error encountered during storage management operation Data area previously locked by another program Data area locked by program in the same process Character field not entirely enclosed by shift-out and shift-in characters
IBM i: ILE RPG Reference
3-90
Program Exception/Errors
00451 | 00452 00501 00502 00802 00803 00804 00805 00907 00970 09998 09999 Conversion between two CCSIDs is not supported. Some characters could not be converted between two CCSIDs. Failure to retrieve sort sequence. Failure to convert sort sequence. Commitment control not active. Rollback operation failed. Error occurred on COMMIT operation Error occurred on ROLBK operation Decimal data error (digit or sign not valid) The level number of the compiler used to generate the program does not agree with the level number of the RPG IV run-time subroutines. Internal failure in ILE RPG compiler or in run-time subroutines Program exception in system routine.
PSDS Example: To specify a PSDS in your program, you code the program status data structure and the subfields you wish to use on a definition specification.
RPG IV Concepts
3-91
Program Exception/Errors
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++Comments++++++++++ DMYPSDS D PROC_NAME D PGM_STATUS D PRV_STATUS D LINE_NUM D ROUTINE D PARMS D EXCP_TYPE D EXCP_NUM D PGM_LIB D EXCP_DATA D EXCP_ID D DATE D YEAR D LAST_FILE D FILE_INFO D JOB_NAME D USER D JOB_NUM D JOB_DATE D RUN_DATE D RUN_TIME D CRT_DATE D CRT_TIME D CPL_LEVEL D SRC_FILE D SRC_LIB D SRC_MBR D PROC_PGM D PROC_MOD SDS *PROC *STATUS 16 21 *ROUTINE *PARMS 40 43 81 91 171 191 199 201 209 244 254 264 270 276 282 288 294 300 304 314 324 334 344 42 46 90 170 174 198 200S 0 208 243 253 263 269S 0 275S 0 281S 0 287S 0 293 299 303 313 323 333 343 353 20S 0 28 * Procedure name * Status code * Previous status * Src list line num * Routine name * Num passed parms * Exception type * Exception number * Program library * Exception data * Exception Id * Date (*DATE fmt) * Year (*YEAR fmt) * Last file used * File error info * Job name * User name * Job number * Date (UDATE fmt) * Run date (UDATE) * Run time (UDATE) * Create date * Create time * Compiler level * Source file * Source file lib * Source file mbr * Pgm Proc is in * Mod Proc is in
3-92
Program Exception/Errors
Note: The keywords are not labels and cannot be used to access the subfields. Short entries are padded on the right with blanks.
RPG IV Concepts
3-93
File devices
| The device of a file is specified by the device-type keyword for a free-form file definition, and by the | Device entry for a fixed-form file definition. | The RPG IV device name defines the ILE RPG functions that can be done on the associated file. Certain | functions are valid only for a specific ILE RPG device name (such as the EXFMT operation for the | WORKSTN device). | Note: If no device-type keyword is specified for a free-form file, and the LIKEFILE keyword is not | specified, the device defaults to DISK(*EXT). | File device types | PRINTER The file is a printer file, a file with control characters that can be sent to a printer. | | DISK The file is a disk file. This device supports sequential and random read/write functions. These files can be accessed on a remote system by Distributed Data Management (DDM). | | WORKSTN The file is a workstation file. Input and output is through a display or ICF file. | | SPECIAL The file is a a special file. Input or output is on a device that is accessed by a user-supplied | program. The name of the program must be specified as the parameter for the PGMNAME | keyword. A parameter list is created for use with this program, including an option code | parameter and a status code parameter. The file must be a fixed unblocked format. See | PLIST(Plist_name) on page 5-64 and PGMNAME(program_name) on page 5-64 for more | information. | | SEQ | The file is a sequentially organized file. The actual device is specified in a CL command or in the file description, which is accessed by the file name.
3-94
| | | | | | | | | | | | | | | | | | | | | | | | | | | |
RPG IV Concepts
3-95
| The copy file also contains several named constants that can be used within the handler. For example, | there are several named constants whose names begin with QrnOperation_, such as QrnOperation_OPEN, | that can be used with subfield rpgOperation of the handler parameter. | The subfields provide the handler with all the information it needs to perform the required operation. For | example, for an output operation, it receives the data to be written to the file. | The subfields also allow the handler to pass back all the information needed by RPG following the | operation. For example, for an input operation, the handler can pass back the input data, and it can pass | back information about whether the file reached end-of-file. | | | | | | If the handler needs to communicate directly with the RPG programmer, the handler provider can ask the RPG programmer to specify the communication-area parameter of the HANDLER keyword. The RPG program and the handler provider must ensure that the communication-area parameter is defined the same in the handler and the RPG program. Normally, the handler provider would provide a template data structure in a copy file that the RPG programmer can use to define the communication-area parameter.
| Note: The communication area is also referred to as the user area. The userArea subfield in the handler | parameter is a pointer to the communication-area parameter specified on the HANDLER keyword in the | RPG program. | | | | | | If the handler needs to maintain state information that is available across calls to the handler, it can use the stateInfo pointer subfield in the handler parameter. If the handler places a pointer value in this subfield during one call to the handler, the same pointer value will be avaiable for all subsequent calls to the handler for that particular file. Normally, a handler will allocate storage for the state information while it is handling the OPEN operation, and it will deallocate the storage when it is handling the CLOSE operation.
| Errors in the handler | If the handler fails with an unhandled exception, the RPG operation will fail with a status code relevant | to the operation. For example, if the operation is an OPEN or a CLOSE operation, the error status will be | either 1216 or 1217. For other operations, the status will be 1299. | If the handler detects an error, there are two mechanisms to communicate the failure to the RPG | program: | v Send an exception message that will cause the handler to end with an unhandled exception. This message will appear in the joblog, and the subsequent RPG error message will refer to this error | message. | The advantage of this mechanism is that the handler ends as soon as the exception message is sent, so | the handler does not have to keep track of whether the operation has failed. | | v Set the rpgStatus subfield of the handler parameter to the desired RPG status code. It may also be helpful to send a diagnostic message to the joblog. |
3-96
The following shows the RPG program that defines the Open Access file. Note the following aspects of the program 1. The copy file provided for the handler. 2. The communication-area data structure used to communicate directly with the handler. The userArea subfield in the parameter passed to the handler will point to this data structure. 3. The Open Access file. The handler in this example supports both program-described files and externally-described files. This example program uses an externally-described file defined from the following source file.
A A R STREAMFMT LINE 32740A VARLEN
4. The HANDLER keyword a. The first parameter for the HANDLER keyword is the named constant from the copy file that defines the handler program or procedure. b. The second parameter for the HANDLER keyword is the communication-area data structure data structure. 5. The program sets up the communication area with the additional information needed by the handler and then it opens the file. 6. It writes two records to the file.
RPG IV Concepts
3-97
| | | | | | | | | | | | | | | | | | | |
CTL-OPT DFTACTGRP(*NO) ACTGRP(*NEW); /copy IFSHDLRS/SRC,RPG 1 DCL-DS ifs_info LIKEDS(ifshdlrs_info_t); 2 DCL-F streamfile DISK(*EXT) USAGE(*OUTPUT) 3 EXTDESC(MYLIB/MYSTMF) HANDLER(ifshdlrs_write_handler : ifs_info) USROPN; ifs_info.path = /home/mydir/myfile.txt; ifs_info.createCcsid = 0; // job CCSID ifs_info.append = *ON; OPEN streamfile; line = Hello; 6 WRITE streamFmt; line = world!; WRITE streamFmt; *inlr = 1; 5
4a 4b
| The following examples show the handler. | v Control statement, copy files and global definitions | v Main handler procedure | v Procedure to open the file on page 3-100 | v Procedure to close the file on page 3-101 | v Procedure to write the file using the output buffer on page 3-102 | v Procedure to | v Procedure to | v Procedure to | v Procedure to | v Procedure to write the file using the names-values information on page 3-102 write one line to the file on page 3-103 send an exception on page 3-104 send an exception related to "errno" on page 3-104 get the value of "errno" on page 3-105
| Control statement, copy files and global definitions | 1. The state_t template data structure defines the information needed by the handler across calls to the handler. In this example, the handler needs to keep track of the descriptor for the open file. | | | | | | | | | | | | |
CTL-OPT DFTACTGRP(*NO) ACTGRP(*CALLER) MAIN(writeHdlr); /COPY IFSHDLRS/SRC,RPG /COPY QOAR/QRPGLESRC,QRNOPENACC /COPY QSYSINC/QRPGLESRC,IFS DCL-S descriptor_t INT(10) TEMPLATE; DCL-DS state_t QUALIFIED template; 1 descriptor LIKE(descriptor_t); END-DS;
| Main handler procedure | 1. The procedure interface defines the parameter that is passed to every Open Access handler. The QrnOpenAccess_T template is defined in copy file QRNOPENACC in source file QOAR/QRPGLESRC. | | 2. Several based data structures are defined. The basing pointers for these data structures will be set from pointers in the handler parameter. |
3-98
RPG IV Concepts
3-99
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
DCL-PROC writeHdlr; DCL-PI *N EXTPGM; 1 parm LIKEDS(QrnOpenAccess_T); END-PI; DCL-S stackOffsetToRpg INT(10) INZ(2); DCL-S errnoVal INT(10); DCL-DS state LIKEDS(state_t) BASED(pState); 2 DCL-DS ifsInfo LIKEDS(ifshdlrs_info_t) BASED(pIfsInfo); DCL-DS namesValues LIKEDS(QrnNamesValues_T) BASED(parm.namesValues); pState = parm.stateInfo; 3 pIfsInfo = parm.userArea; SELECT; WHEN parm.RpgOperation = QrnOperation_OPEN; pState = %ALLOC(%SIZE(state_t)); parm.stateInfo = pState; 4
state.descriptor = openFile (ifsInfo : stackOffsetToRpg + 1); IF parm.externallyDescribed; parm.useNamesValues = 1; ENDIF; WHEN parm.RpgOperation = QrnOperation_WRITE; IF parm.useNamesValues; writeFileNv (state.handle : namesValues : stackOffsetToRpg + 1); ELSE: writeFileBuf (state.handle : parm.outputBuffer : parm.outputBufferLen : stackOffsetToRpg + 1); ENDIF; WHEN parm.RpgOperation = QrnOperation_CLOSE; closeFile (state.handle : stackOffsetToRpg + 1); state.descriptor = -1; DEALLOC(N) pState; OTHER; 7 sendException (Unexpected operation + %CHAR(parm.RpgOperation) : stackOffsetToRpg + 1); // Control will not return here ENDSL; END-PROC writeHdlr;
| Procedure to open the file | 1. If the file could not be opened, the procedure sends an exception message. This causes the handler program to fail, which will cause the OPEN operation to fail in the RPG program. | |
3-100
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
DCL-PROC openFile; DCL-PI *n LIKE(descriptor_t); ifsInfo LIKEDS(ifshdlrs_info_t) CONST; stackOffsetToRpg INT(10) VALUE; END-PI; DCL-C JOB_CCSID 0; DCL-S openFlags INT(10); DCL-S descriptor LIKE(descriptor_t); openFlags = O_WRONLY + O_CREAT + O_TEXT_CREAT + O_TEXTDATA + O_CCSID + O_INHERITMODE; IF ifsInfo.append; openFlags += O_APPEND; ELSE: openFlags += O_TRUNC; ENDIF; descriptor = open(ifsInfo.path : openFlags : 0 : ifsInfo.createCcsid : JOB_CCSID); IF descriptor < 0; 1 errnoException (Could not open + ifsInfo.path + . : getErrno () : stackOffsetToRpg + 1); // Control will not return here ENDIF; return descriptor; END-PROC openFile;
RPG IV Concepts
3-101
| Procedure to write the file using the names-values information | 1. The names-values information contains an array of information about each field in the | externally-described format. The handler in this example has its own restrictions on the number and | type of fields that can be in the externally-described format. | a. The handler verifies that there is only one field. | b. Then the handler verifies that it is an alphanumeric field. | 2. nv.field(1).value is a pointer to the data in the first field. If the field is a varying-length field, this | pointer points to the data portion of the field. nv.field(1).valueLenBytes holds the length of the data. | | | | | | | | | | | | | | | | | | | | | | | | |
DCL-PROC writeFileNv; DCL-PI *n; descriptor LIKE(descriptor_t) VALUE; nv LIKEDS(QrnNamesValues_T); stackOffsetToRpg INT(10) VALUE; END-PI; IF nv.num > 1; 1a sendException (Only one field supported. : stackOffsetToRpg + 1); // Control will not return here ELSE: IF nv.field(1).dataType <> QrnDatatype_Alpha 2b AND nv.field(1).dataType <> QrnDatatype_AlphaVarying; sendException (Field + nv.field(1).externalName + must be Alpha or AlphaVarying type. : stackOffsetToRpg + 1); // Control will not return here ENDIF; ENDIF; writeLine (descriptor : nv.field(1).value : nv.field(1).valueLenBytes : stackOffsetToRpg + 1); END-PROC writeFileNv;
3-102
RPG IV Concepts
3-103
3-104
See the Rational Open Access: RPG Edition topic for information on writing an Open Access handler.
File Parameters
You can pass files as parameters using prototyped calls to RPG programs and procedures. You can define file parameters for prototypes and procedure interface definitions, using the LIKEFILE keyword. The called program or procedure can perform any operation that is valid on the original file that was used to define the file parameter. Note: RPG file parameters are in a form that is not related to the forms used for file parameters in other languages such as C and C++. The file parameters used by RPG are not interchangeable with the file parameters used by other languages; you cannot pass a C file to an RPG procedure that is expecting an RPG file parameter, and you cannot pass an RPG file to a C program. For an example of a program that passes a file parameter, see Example of passing a file and passing a data structure with the associated variables. on page 3-106
RPG IV Concepts
3-105
EXTFILE
Input
Example of passing a file and passing a data structure with the associated variables.
The following example shows you how to define a data structure to hold the associated variables for a file, how to pass the file and the data structure as parameters to a procedure, and how to use the parameters within the procedure.
3-106
* The /COPY file has template definitions for the File and Associated Variables /if defined(FILE_DEFINITIONS) // Template for the "INFILE" file type Finfile_t if e disk template block(*yes) F extdesc(MYLIB/MYFILE) /eof /endif /if defined(DATA_DEFINITIONS) // Template for the associated variables for an INFILE file D infileVars_t ds qualified template D filename 21a D mbrname 10a // Prototype for a procedure to open an INFILE file D open_infile pr D theFile likefile(infile_t) D kwVars likeds(infileVars) D options(*nullind) /eof /endif Figure 3-44. /COPY file INFILE_DEFS
P myproc b // Copy in the template and prototype definitions /define FILE_DEFINITIONS /COPY INFILE_DEFS /undefine FILE_DEFINITIONS /define DATA_DEFINITIONS /COPY INFILE_DEFS /undefine DATA_DEFINITIONS // Define the file using LIKEFILE, to enable it to be passed as // a parameter to the "open_infile" procedure. // Define all the associated variables as subfields of a data // structure, so that all the associated variables can be // passed to the procedure as a single parameter Ffile1 likefile(infile_t) F extfile(file1Vars.filename) F extmbr(file1Vars.mbrname) F usropn D file1Vars /free open_infile (file1 : file1Vars); . . . Figure 3-45. The calling procedure that passes the file parameter ds likeds(infileVars_t)
RPG IV Concepts
3-107
// Copy in the template and prototype definitions /define FILE_DEFINITIONS /COPY INFILE_DEFS /undefine FILE_DEFINITIONS /define DATA_DEFINITIONS /COPY INFILE_DEFS /undefine DATA_DEFINITIONS P open_infile b // The open_infile procedure has two parameters // - a file // - a data structure containing all the associated variables for the file D open_infile pi D theFile likefile(infile_t) D kwVars likeds(infileVars) /free // The %OPEN(filename) built-in function reflects the // current state of the file if not %open(theFile); // The called procedure modifies the calling procedures "file1Vars" // variables directly, through the passed parameter kwVars.extfile = LIB1/FILE1; kwVars.extmbr = MBR1; // The OPEN operation uses the file1Vars subfields in the // calling procedure to open the file, opening file LIB1/FILE1(MBR1) open theFile; endif; . . . Figure 3-46. The called procedure that uses the file parameter
| An full procedural file is defined using a free-form DCL-F statement, or identified by an F in position 18 | of the file description specifications. | All input, update, and output operations for the file are controlled by calculation operations.
3-108
3-109
3-110
*...1....+....2....+....3....+....4....+....5....+....6....+....7... FFilename++IPEASFRlen+LKlen+AIDevice+.Keywords++++++++++++++++++++++++++++ * The files in this example are externally described (E in position * 22) and are to be processed by keys (K in position 34). FMASTER IP E K DISK FWEEKLY IS E K DISK *...1....+....2....+....3....+....4....+....5....+....6....+....7... IRcdname+++....Ri........................................................ I..............Ext-field+..................Field+++++++++L1M1..PlMnZr.... * MASTER FILE IEMPMAS 01 I EMPLNO M1 I DIVSON M3 I DEPT M2 IDEPTMS 02 I EMPLNO M1 I DEPT M2 I DIVSON M3 * WEEKLY FILE IWEEKRC 03 I EMPLNO M1 I DIVSON M3 I DEPT M2 Figure 3-47. Match Fields in Which All Values Match
Three files are used in matching records. All the files have three match fields specified, and all use the same values (M1, M2, M3) to indicate which fields must match. The MR indicator is set on only if all three match fields in either of the files EMPMAS and DEPTMS are the same as all three fields from the WEEKRC file. The three match fields in each file are combined and treated as one match field organized in the following descending sequence: DIVSON M3 DEPT M2 EMPLNO M1 The order in which the match fields are specified in the input specifications does not affect the organization of the match fields.
RPG IV Concepts
3-111
*...1....+....2....+....3....+....4....+....5....+....6....+....7... IFilename++SqNORiPos1+NCCPos2+NCCPos3+NCC................................ I........................Fmt+SPFrom+To+++DcField+++++++++L1M1FrPlMnZr.... IDISK AB 01 1 C1 I OR 02 1 C2 I OR 03 1 C3 I 1 10 0EMPNO M1 I 11 15 0DUMMY M2 I 11 15 0DEPT M202 I 16 20 0DEPT M203
M 1 E M P N O
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
M 1 E M P N O
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
Figure 3-48. Match Fields with a Dummy M2 Field
Three different record types are found in the input file. All three contain a match field in positions 1 through 10. Two of them have a second match field. Because M1 is found on all record types, it can be specified without a field record relation entry in positions 67 and 68. If one match value (M1 through M9) is specified without field record relation entries, all match values must be specified once without field record relation entries. Because the value M1 is specified without field record relationship, an M2 value must also be specified once without field record relationship. The M2 field is not on all record types; therefore a dummy M2 field must be specified next. The dummy field can be given any unique name, but its specified length must be equal to the length of the true M2 field. The M2 field is then related to the record types on which it is found by field record relation entries.
3-112
*...1....+....2....+....3....+....4....+....5....+....6....+....7... FFilename++IPEASFRlen+LKlen+AIDevice+.Keywords++++++++++++++++++++++++++++ FPRIMARY IPEA F 64 DISK FFIRSTSEC IS A F 64 DISK FSECSEC IS A F 64 DISK *...1....+....2....+....3....+....4....+....5....+....6....+....7... IFilename++SqNORiPos1+NCCPos2+NCCPos3+NCC................................ I........................Fmt+SPFrom+To+++DcField+++++++++L1M1FrPlMnZr.... IPRIMARY AA 01 1 CP 2NC I 2 3 MATCH M1 * I BB 02 1 CP 2 C I 2 3 NOM * IFIRSTSEC AB 03 1 CS 2NC I 2 3 MATCH M1 * I BC 04 1 CS 2 C I 2 3 NOM * ISECSEC AC 05 1 CT 2NC I 2 3 MATCH M1 * I BD 06 1 CT 2 C I 2 3 NOM Figure 3-49. Match Field Specifications for Three Disk Files
Processing Matching Records: Matching records for two or more files are processed in the following manner: v Whenever a record from the primary file matches a record from the secondary file, the primary file is processed first. Then the matching secondary file is processed. The record identifying indicator that identifies the record type just selected is on at the time the record is processed. This indicator is often used to control the type of processing that takes place. v Whenever records from ascending files do not match, the record having the lowest match field content is processed first. Whenever records from descending files do not match, the record having the highest match field content is processed first. v A record type that has no match field specification is processed immediately after the record it follows. The MR indicator is off. If this record type is first in the file, it is processed first even if it is not in the primary file. v The matching of records makes it possible to enter data from primary records into their matching secondary records because the primary record is processed before the matching secondary record. However, the transfer of data from secondary records to matching primary records can be done only when look-ahead fields are specified. Figure 3-50 on page 3-114 through Figure 3-51 on page 3-115 show how records from three files are selected for processing.
RPG IV Concepts
3-113
P 20
P 20
P 40
P 50
Primary File
60 80
1 No Match Field
11 12 13 17 22
S 20
S 30
S 30
S 60
S 70
S 80
3 Match Field
18 19 21 23 24
T 10
T 30
T 50
T 50
T 60
T 80
10 14 15 16 20 25 26
The records from the three disk files above are selected in the order indicated by the dark numbers. Figure 3-50. Normal Record Selection from Three Disk Files Table 3-10. Normal Record Selection from Three Disk Files Cycle 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 File Processed PRIMARY PRIMARY FIRSTSEC SECSEC PRIMARY PRIMARY FIRSTSEC FIRSTSEC FIRSTSEC SECSEC PRIMARY PRIMARY PRIMARY SECSEC SECSEC SECSEC PRIMARY FIRSTSEC FIRSTSEC SECSEC FIRSTSEC PRIMARY FIRSTSEC FIRSTSEC SECSEC
IBM i: ILE RPG Reference
Indicators On 02 02 04 05 01, MR 01, MR 03, MR 03 03 05 01 01, MR 02 05, MR 05, MR 06 01, MR 03, MR 04 05, MR 03 01, MR 03, MR 02, MR 05, MR
Reason for Setting Indicator No match field specified No match field specified No match field specified Second secondary low; no primary match Primary matches first secondary Primary matches first secondary First secondary matches primary First secondary low; no primary match First secondary low; no primary match Second secondary low; no primary match Primary low; no secondary match Primary matches second secondary No match field specified Second secondary matches primary Second secondary matches primary No match field specified Primary matches both secondary files First secondary matches primary No match field specified Second secondary matches primary First secondary low; no primary match Primary matches both secondary files First secondary matches primary First secondary matches primary Second secondary matches primary
3-114
STEP 1 The first record from each file is read. The P and S records have no match field, so they are processed before the T record that has a match field. Because the P record comes from the primary file, it is selected for processing first.
T 10
STEP 2 The next P record is read. It contains no match field and comes from the primary file, so the new P record is also selected for processing before the S record.
T 10
STEP 3 The next P record has a match field. The S record has no match field, so it is selected for processing.
P 20
T 10
STEP 4 The next S record is read. All three records have match fields. Because the value in the match field of the T record is lower than the value in the other two, the T record is selected for processing.
P 20
S 20
T 10
STEP 5
P 20
S 20
T 30
The next T record is read. The matching P and S records both have the low match field value, so they are processed before the T record. Because the matching P record comes from the pr imary file, it is selected for processing first.
Figure 3-51. Normal Record Selection from Three Disk Files, Part 1
RPG IV Concepts
3-115
File Translation
STEP 6 The next P record is read. Because it contains the same match field and comes from the pr imary file, the new P record is selected instead of the S record.
P 20
S 20
T 30
STEP 7 The next P record is read. The value of the match field in the S record is the lowest of the three, so the S record is selected for processing.
P 40
S 20
T 30
STEP 8
P 40
S 30
T 30
The next S record is read. Because the S and T records have the lowest match field, they are selected before the P record. Because the S record comes from the first secondar y file, it is selected for processing before the T record.
STEP 9 The next S record is read. Because it also has the same match field as the S record just selected, it too is selected before the T record.
P 40
S 30
T 30
STEP 10 The next S record is read. The T record contains the lowest match field value, and is selected for processing.
P 40
S 60
T 30
Figure 3-52. Normal Record Selection from Three Disk Files, Part 2
File Translation
The file translation function translates any of the 8-bit codes used for characters into another 8-bit code. The use of file translation indicates one or both of the following: v A character code used in the input data must be translated into the system code. v The output data must be translated from the system code into a different code. The translation on input data occurs before any field selection has taken place. The translation on output data occurs after any editing taken place. Remember the following when specifying file translation: v File translation can be specified for data in array or table files (T in position 18 of the file description specifications). v File translation can be used with data in combined, input, or update files that are translated at input and output time according to the file translation table provided. If file translation is used to translate data in an update file, each record must be written before the next record is read. v For any I/O operation that specifies a search argument in factor 1 (such as CHAIN, READE, READPE, SETGT, or SETLL) for files accessed by keys, the search argument is translated before the file is accessed.
3-116
File Translation
v If file translation is specified for both a record address file and the file being processed (if the file being processed is processed sequentially within limits), the records in the record address file are first translated according to the file translation specified for that file, and then the records in the file being processed are translated according to the file translation specified for that file. v File translation applies only on a single byte basis. v Every byte in the input and output record is translated. v File translation is not supported for local files defined in subprocedures.
1-8 (to translate a Enter the name of the file to be translated. Complete the file translation table record beginning specific file) with positions 11 and 12. The *FILES entry is not made in positions 1 through 8 when a specific file is to be translated. 9-10 11-12 13-14 Blank Enter the hexadecimal value of the character to be translated from on input or to be translated to on output. Enter the hexadecimal equivalent of the internal character the RPG IV language works with. It will replace the character in positions 11 and 12 on input and be replaced by the character in positions 11 and 12 on output. All groups of four beginning with position 15 are used in the same manner as positions 11 through 14. In the first two positions of a group, enter the hexadecimal value of the character to be replaced. In the last two positions, enter the hexadecimal value of the character that replaces it.
The first blank entry ends the record. There can be one or more records per file translation table. When multiple records are required in order to define the table, the same file name must be entered on all records. A change in file name is used to separate multiple translation tables. An *FILES record causes all files, including tables and arrays specified by a T in position 18 of the file description specifications, to be translated by the same table.
RPG IV Concepts
3-117
File Translation
HKeywords++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * In this example all the files are translated H FTRANS FFilename++IPEASFRlen+LKlen+AIDevice+.Keywords++++++++++++++++++++++ FFILE1 IP F 10 DISK FFILE2 IS F 10 DISK FFILE3 IS F 10 DISK FFILE4 IS F 10 DISK **FTRANS *FILES 81C182C283C384C4
HKeywords++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * In this example different translate tables are used and * FILE3 is not translated. H FTRANS FFilename++IPEASFRlen+LKlen+AIDevice+.Keywords++++++++++++++++++++++ FFILE1 IP F 10 DISK FFILE2 IS F 10 DISK FFILE3 IS F 10 DISK FFILE4 IS F 10 DISK **FTRANS FILE1 8182 FILE2 C1C2 FILE4 81C182C283C384C4
Additional file names are associated with the table until a file name not followed by a comma is encountered. A file name cannot be split between two records; a comma following a file name must be on the same record as the file name. You can create only one file translation table by using *EQUATE. Specifying the Table: File translation table records must be formatted as follows:
Record Position 1-7 8-10 11-12 Entry *EQUATE Leave these positions blank. Enter the hexadecimal value of the character to be translated from on input or to be translated to on output.
3-118
File Translation
Record Position 13-14
Entry Enter the hexadecimal equivalent of the internal character the RPG IV language works with. It will replace the character in positions 11 and 12 on input and be replaced by the character in positions 11 and 12 on output. All groups of four beginning with position 15 are used the same way as positions 11 through 14. In the first two positions of a group, enter the hexadecimal value of the character to be replaced. In the last two positions, enter the hexadecimal value of the character that replaces it.
The first blank record position ends the record. If the number of entries exceeds 80 positions, duplicate positions 1 through 10 on the next record and continue as before with the translation pairs in positions 11 through 80. All table records for one file must be kept together. The records that describe the file translation tables must be preceded by a record with ** ( = blank) in positions 1 through 3 or with **FTRANS. The remaining positions in this record can be used for comments.
HKeywords++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * In this example several files are translated with the * same translation table. FILE2 is not translated. H FTRANS FFilename++IPEASFRlen+LKlen+AIDevice+.Keywords++++++++++++++++++++++ FFILE1 IP F 10 DISK FFILE2 IS F 10 DISK FFILE3 IS F 10 DISK FFILE4 IS F 10 DISK **FTRANS *EQUATE FILE1,FILE3,FILE4 *EQUATE 81C182C283C384C485C586C687C788C889C98ACA8BCB8CCC8DCD8ECE8F *EQUATE 91D192D2
RPG IV Concepts
3-119
File Translation
3-120
Definitions
Defining variables, constants, prototypes, and procedure interfaces This section provides information on the different types of definitions that can be coded in your source. It describes: v How to define Standalone fields, arrays, and tables Named constants Data structures and their subfields Prototypes Prototyped parameters Procedure interface v Scope and storage of definitions as well as how to define each definition type. v Data types and Data formats v Editing numeric fields For information on how to define files, see File Description Specifications on page 5-37 and also the chapter on defining files in the IBM Rational Development Studio for i: ILE RPG Programmer's Guide.
General Considerations
You define items by using definition specifications. Definitions can appear in two places within a module or program: within the cycle-main source section and within a subprocedure. (The main source section consists of the first set of H, F, D, I, C, and O specifications in a module; it corresponds to the specifications found in a standalone program or a cycle-main procedure.) Depending on where the definition occurs, there are differences both in what can be defined and also the scope of the definition. Specify the type of definition in positions 24 through 25, as follows: Entry Definition Type
Blank A data structure subfield or parameter definition C DS Named constant Data structure
4-1
General Considerations
PI PR S Procedure interface Prototype Standalone field
Definitions of data structures, prototypes, and procedure interfaces end with the first definition specification with non-blanks in positions 24-25, or with the first specification that is not a definition specification.
*-----------------------------------------------------------------* * Global Definitions *-----------------------------------------------------------------* D String S 6A INZ(ABCDEF) D Spcptr S * D SpcSiz C 8 D DS1 DS OCCURS(3) D Fld1 5A INZ(ABCDE) D Fld1a 1A DIM(5) OVERLAY(Fld1) D Fld2 5B 2 INZ(123.45) D Switch PR D Parm 1A ... *-----------------------------------------------------------------* * Local Definitions *-----------------------------------------------------------------* P Switch B D Switch PI D Parm 1A * Define a local variable. D Local S 5A INZ(aaaaa) ... P E Figure 4-1. Sample Definitions
Scope of Definitions
Depending on where a definition occurs, it will have different scope. Scope refers to the range of source lines where a name is known. There are two types of scope: global and local, as shown in Figure 4-2.
In general, all items that are defined in the main source section are global, and therefore, known throughout the module. Global definitions are definitions that can be used by both the cycle-main procedure and any subprocedures within the module. They can also be exported.
4-2
General Considerations
Items in a subprocedure, on the other hand, are local. Local definitions are definitions that are known only inside that subprocedure. If an item is defined with the same name as a global item, then any references to that name inside the subprocedure will use the local definition. However, note the following exceptions: v Subroutine names and tag names are known only to the procedure in which they are defined. This includes subroutine or tag names that are defined in the cycle-main procedure. v All fields specified on input and output specifications are global. For example, if a subprocedure does an operation using a record format, say a WRITE operation, the global fields will be used even if there are local definitions with the same names as the record format fields. Sometimes you may have a mix of global and local definitions. For example, KLISTs and PLISTs can be global or local. The fields associated with global KLISTs and PLISTs contain only global fields. The fields associated with local KLISTs and PLISTs can contain both global and local fields. For more information on the behavior of KLISTs and KFLDs inside subprocedures, see Scope of Definitions on page 3-19.
Storage of Definitions
Local definitions use automatic storage. Automatic storage is storage that exists only for the duration of the call to the procedure. Variables in automatic storage do not save their values across calls. Global definitions, on the other hand, use static storage. Static storage is storage that has a constant location in memory for all calls of a program or procedure. It keeps its value across calls. Specify the STATIC keyword to indicate that a local field definition use static storage, in which case it will keep its value on each call to the procedure. If the keyword STATIC is specified, the item will be initialized at module initialization time. In a cycle module, static storage for global definitions is subject to the RPG cycle, and so the value changes on the next call to the cycle-main procedure if LR was on at the end of the last call. However, local static variables will not get reinitialized because of LR in the cycle-main procedure. Tip: Using automatic storage reduces the amount of storage that is required at run time by the program. The storage is reduced largely because automatic storage is only allocated while the procedure is running. On the other hand, all static storage associated with the program is allocated when the program starts, even if no procedure using the static storage is ever called.
Standalone Fields
Standalone fields allow you to define individual work fields. A standalone field has the following characteristics: v It has a specifiable internal data type v It may be defined as an array, table, or field v It is defined in terms of data length, not in terms of absolute byte positions. For more information on standalone fields, see: v Using Arrays and Tables on page 4-31 v Data Types and Data Formats on page 4-48 v Definition-Specification Keywords on page 5-92
Variable Initialization
You can initialize data with the INZ{(initial value)} on page 5-114 keyword on the definition specification. Specify an initial value as a parameter on the INZ keyword, or specify the keyword without
Definitions
4-3
Standalone Fields
a parameter and use the default initial values. If the initialization is too complicated to express using the INZ keyword, you can further initialize data in the initialization subroutine. Default initial values for the various data types are described in Data Types and Data Formats on page 4-48. See Using Arrays and Tables on page 4-31 for information on initializing arrays. To reinitialize data while the program is running, use the CLEAR and RESET operations. The CLEAR operation code sets a record format or variable (field, subfield, indicator, data structure, array, or table) to its default value. All fields in a record format, data structure, or array are cleared in the order in which they are declared. The RESET operation code restores a variable to its reset value. The reset value for a global variable is the value it had at the end of the initialization step in the RPG IV cycle, after the initialization subroutine has been invoked. You can use the initialization subroutine to assign initial values to a global variable and then later use RESET to set the variable back to this value. This applies only to the initialization subroutine when it is run automatically as a part of the initialization step. For local variables the reset value is the value of the variable when the subprocedure was first called, but before the calculations begin.
Constants
Literals and named constants are types of constants. They can be specified in any of the following places: v In factor 1 v v v v v In factor 2 In an extended factor 2 on the calculation specifications As parameters to keywords on the control specification As parameters to built-in functions In the Field Name, Constant, or Edit Word fields in the output specifications.
v As array indexes v As the format name in a WORKSTN output specification v With keywords on the definition specification.
Literals
A literal is a self-defining constant that can be referred to in a program. A literal can belong to any of the RPG IV data types. Character Literals The following are the rules for specifying a character literal: v Any combination of characters can be used in a character literal. This includes DBCS characters. DBCS characters must be enclosed by shift-out and shift-in characters and must be an even number of bytes. Embedded blanks are valid. v A character literal with no characters between the apostrophes is allowed. See Figure 4-4 on page 4-8 for examples. v Character literals must be enclosed in apostrophes (). v An apostrophe required as part of a literal is represented by two apostrophes. For example, the literal OCLOCK is coded as OCLOCK. v Character literals are compatible only with character data. v Indicator literals are one byte character literals which contain either '1' (on) or '0' (off).
4-4
Constants
Hexadecimal Literals The following are the rules for specifying a hexadecimal literal: v Hexadecimal literals take the form:
Xx1x2...xn
v v v v
where Xx1x2...xn can only contain the characters A-F, a-f, and 0-9. The literal coded between the apostrophes must be of even length. Each pair of characters defines a single byte. Hexadecimal literals are allowed anywhere that character literals are supported except as factor 2 of ENDSR and as edit words. Except when used in the bit operations BITON, BITOFF, and TESTB, a hexadecimal literal has the same meaning as the corresponding character literal. For the bit operations, factor 2 may contain a hexadecimal literal representing 1 byte. The rules and meaning are the same for hexadecimal literals as for character fields. If the hexadecimal literal contains the hexadecimal value for a single quote, it does not have to be specified twice, unlike character literals. For example, the literal AB is specified as AB but the hexadecimal version is XC17DC2 not XC17D7DC2. Normally, hexadecimal literals are compatible only with character data. However, a hexadecimal literal that contains 16 or fewer hexadecimal digits can be treated as an unsigned numeric value when it is used in a numeric expression or when a numeric variable is initialized using the INZ keyword.
Numeric Literals The following are the rules for specifying a numeric literal: v A numeric literal consists of any combination of the digits 0 through 9. A decimal point or a sign can be included. v The sign (+ or -), if present, must be the leftmost character. An unsigned literal is treated as a positive number. v Blanks cannot appear in a numeric literal. v Numeric literals are not enclosed in apostrophes (). v Numeric literals are used in the same way as a numeric field, except that values cannot be assigned to numeric literals. v The decimal separator may be either a comma or a period Numeric literals of the float format are specified differently. Float literals take the form:
<mantissa>E<exponent> Where <mantissa> is a literal as described above with 1 to 16 digits <exponent> is a literal with no decimal places, with a value between -308 and +308
v Float literals do not have to be normalized. That is, the mantissa does not have to be written with exactly one digit to the left of the decimal point. (The decimal point does not even have to be specified.) v Lower case e may be used instead of E. v Either a period ('.') or a comma (',') may be used as the decimal point. v Float literals are allowed anywhere that numeric constants are allowed except in operations that do not allow float data type. For example, float literals are not allowed in places where a numeric literal with zero decimal positions is expected, such as an array index.
Definitions
4-5
Constants
v Float literals follow the same continuation rules as for regular numeric literals. The literal may be split at any point within the literal. The following lists some examples of valid float literals:
1E1 1.2e-1 -1234.9E0 12e12 +67,89E+0003 = = = = = 10 .12 -1234.9 12000000000000 67890 (the comma is the decimal point)
Date Literals Date literals take the form D'xx-xx-xx' where: v D indicates that the literal is of type date v xx-xx-xx is a valid date in the format specified on the control specification (separator included) v xx-xx-xx is enclosed by apostrophes Time Literals Time literals take the form T'xx:xx:xx' where: v T indicates that the literal is of type time v xx:xx:xx is a valid time in the format specified on the control specification (separator included) v xx:xx:xx is enclosed by apostrophes Timestamp Literals Timestamp literals take the form Z'yyyy-mm-dd-hh.mm.ss.mmmmmm' where: v v v v v Z indicates that the literal is of type timestamp yyyy-mm-dd is a valid date (year-month-day) hh.mm.ss.mmmmmm is a valid time (hours.minutes.seconds.microseconds) yyyy-mm-dd-hh.mm.ss.mmmmmm is enclosed by apostrophes Microseconds are optional and if not specified will default to zeros
Graphic Literals Graphic literals take the form G'oK1K2i' where: v G indicates that the literal is of type graphic v o is a shift-out character v K1K2 is an even number of bytes (possibly zero) and does not contain a shift-out or shift-in character v i is a shift-in character v oK1K2i is enclosed by apostrophes UCS-2 Literals
4-6
Constants
UCS-2 literals take the form U'Xxxx...Yyyy' where: v U indicates that the literal is of type UCS-2. v Each UCS-2 literal requires four bytes per UCS-2 character in the literal. Each four bytes of the literal represents one double-byte UCS-2 character. v UCS-2 literals are compatible only with UCS-2 data. UCS-2 literals are assumed to be in the default UCS-2 CCSID of the module. Example of Defining Literals:
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 H DATFMT(*ISO) * Examples of literals used to initialize fields DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++ D.....................................Keywords+++++++++++++++++++++++++++++ D DateField S D INZ(D1988-09-03) D NumField S 5P 1 INZ(5.2) D CharField S 10A INZ(abcdefghij) D UCS2Field S 2C INZ(U00610062) * Even though the date field is defined with a 2-digit year, the * initialization value must be defined with a 4-digit year, since * all literals must be specified in date format specified * on the control specification. D YmdDate S D INZ(D2001-01-13) D DATFMT(*YMD) * Examples of literals used to define named constants D DateConst C CONST(D1988-09-03) D NumConst C CONST(5.2) D CharConst C CONST(abcdefghij) * Note that the CONST keyword is not required. D Upper C ABCDEFGHIJKLMNOPQRSTUVWXYZ * Note that the literal may be continued on the next line D Lower C abcdefghijklmnD opqrstuvwxyz C C C C * Examples of literals used EVAL IF EVAL ENDIF in operations CharField = abc NumField > 12 DateField = D1995-12-25
Definitions
4-7
Constants
Example of Using Literals with Zero Length:
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++ D.....................................Keywords+++++++++++++++++++++++++++++ * The following two definitions are equivalent: D varfld1 S 5 INZ VARYING D varfld2 S 5 INZ() VARYING * Various fields used by the examples below: D blanks S 10 INZ D vblanks S 10 INZ( ) VARYING D fixfld1 S 5 INZ(abcde) * VGRAPHIC and VUCS2 are initialized with zero-length literals. D vgraphic S 10G INZ(Goi) VARYING D vucs2 S 10C INZ(U) VARYING CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq++++ * The following statements do the same thing: C eval varfld1 = C clear varfld1 * Moving to a variable-length field using MOVE(P) or MOVEL(P) * sets the field to blanks up to the fields current length. C move(p) varfld1 C movel(p) varfld1 * Moving to a fixed-length field has no effect in the following * examples: (The rightmost or leftmost 0 characters are changed.) C move fixfld1 C movel fixfld1 * The following comparisons demonstrate how the shorter operand * is padded with blanks: C eval *in01 = (blanks = ) * *in01 is 1 C * *in02 is 1 C * *in03 is 1 C * *in04 is 1 C * *in05 is 1 C * *in06 is 1 eval *in06 = (%len(vucs2)=0) eval *in05 = (%len(vgraphic)=0) eval *in04 = (varfld2 = vblanks) eval *in03 = (varfld2 = blanks) eval *in02 = (vblanks = )
Figure 4-4. Character, Graphic, and UCS-2 Literals with Zero Length
Named Constants
You can give a name to a constant. This name represents a specific value which cannot be changed when the program is running. Numeric named constants have no predefined precision. Their actual precision is defined by the context that is specified. See Figure 4-3 on page 4-7 for examples of defining named constants. The value of the named constant is specified in the keyword section of the definition specification. The presence of the keyword CONST is optional, however. For example, to assign a value of 'ab' to a constant, you could specify either CONST('ab') or 'ab' in the keyword section.
4-8
Constants
Figurative Constants
The figurative constants *BLANK/*BLANKS, *ZERO/*ZEROS, *HIVAL, *LOVAL, *NULL, *ALL'x..', *ALLG'oK1K2i', *ALLU'XxxxYyyy', *ALLX'x1..', and *ON/*OFF are implied literals that can be specified without a length, because the implied length and decimal positions of a figurative constant are the same as those of the associated field. (For exceptions, see the following section, Rules for Figurative Constants on page 4-10.) Figurative constants can be specified in factor 1 and factor 2 of the calculation specifications. The following shows the reserved words and implied values for figurative constants: Reserved Words Implied Values *BLANK/*BLANKS All blanks. Valid only for character, graphic, or UCS-2 fields. The value for character is ' ' (blank) or X'40', for graphic is X'4040', and for UCS-2 is X'0020'. *ZERO/*ZEROS Character/numeric fields: All zeros. The value is '0' or X'F0'. For numeric float fields: The value is '0 E0'. *HIVAL Character, graphic, or UCS-2 fields: The highest collating character for the system (hexadecimal FFs). Numeric fields: The maximum value allowed for the corresponding field (with a positive sign if applicable). For Float fields: *HIVAL for 4-byte float = 3.402 823 5E38 (/x'7F7FFFFF'/) *HIVAL for 8-byte float = 1.797 693 134 862 315 E308 (/x'7FEFFFFFFFFFFFFF'/) Date, time and timestamp fields: See Date Data Type on page 4-73, Time Data Type on page 4-75 and Timestamp Data Type on page 4-77 for *HIVAL values for date, time, and timestamp data. *LOVAL Character, graphic, or UCS-2 fields: The lowest collating character for the system (hexadecimal zeros). Numeric fields: The minimum value allowed (with a negative sign if applicable). For Float fields: *LOVAL for 4-byte float = -3.402 823 5E38 (/x'FF7FFFFF'/) *LOVAL for 8-byte float = -1.797 693 134 862 315 E308 (/x'FFEFFFFFFFFFFFFF'/) Date, time and timestamp fields: See Date Data Type on page 4-73, Time Data Type on page 4-75 and Timestamp Data Type on page 4-77 for *LOVAL values for date, time, and timestamp data. *ALL'x..' Character/numeric fields: Character string x . . is cyclically repeated to a length equal to the associated field. If the field is a numeric field, all characters within the string must be numeric (0 through 9). No sign or decimal point can be specified when *ALL'x..' is used as a numeric constant. Note: You cannot use *ALL'x..' with numeric fields of float format. Note: For numeric integer or unsigned fields, the value is never greater than the maximum value allowed for the corresponding field. For example, *ALL'95' represents the value 9595 if the corresponding field is a 5-digit integer field, since 95959 is greater than the maximum value allowed for a 5-digit signed integer. *ALLG'oK1K2i' Graphic fields: The graphic string K1K2 is cyclically repeated to a length equal to the associated field. *ALLU'XxxxYyyy' UCS-2 fields: A figurative constant of the form *ALLU'XxxxYyyy' indicates a literal of the form 'XxxxYyyyXxxxYyyy...' with a length determined by the length of the field associated with the *ALLU'XxxxYyyy' constant. Each double-byte character in the constant is represented by four hexadecimal digits. For example, *ALLU'0041' represents a string of repeated UCS-2 'A's.
Definitions
4-9
Constants
*ALLX'x1..' Character fields: The hexadecimal literal X'x1..' is cyclically repeated to a length equal to the associated field. *NULL A null value valid for basing pointers, procedure pointers, or objects. *ON/*OFF *ON is all ones ('1' or X'F1'). *OFF is all zeros ('0' or X'F0'). Both are only valid for character fields. Rules for Figurative Constants: Remember the following rules when using figurative constants: v MOVE and MOVEL operations allow you to move a character figurative constant to a numeric field. The figurative constant is first expanded as a zoned numeric with the size of the numeric field, then converted to packed or binary numeric if needed, and then stored in the target numeric field. The digit portion of each character in the constant must be valid. If not, a decimal data error will occur. v Figurative constants are considered elementary items. Except for MOVEA, figurative constants act like a field if used in conjunction with an array. For example: MOVE *ALL'XYZ' ARR. If ARR has 4-byte character elements, then each element will contain 'XYZX'. v MOVEA is considered to be a special case. The constant is generated with a length equal to the portion of the array specified. For example: MOVEA *BLANK ARR(X) Beginning with element X, the remainder of ARR will contain blanks. MOVEA *ALL'XYZ' ARR(X) ARR has 4-byte character elements. Element boundaries are ignored, as is always the case with character MOVEA operations. Beginning with element X, the remainder of the array will contain 'XYZXYZXYZ...'. Note that the results of MOVEA are different from those of the MOVE example above. v After figurative constants are set/reset to their appropriate length, their normal collating sequence can be altered if an alternate collating sequence is specified. v The move operations MOVE and MOVEL produce the same result when moving the figurative constants *ALL'x..', *ALLG'oK1K2i', and *ALLX'x1..'. The string is cyclically repeated character by character (starting on the left) until the length of the associated field is the same as the length of the string. v Figurative constants can be used in compare operations as long as one of the factors is not a figurative constant. v The figurative constants, *BLANK/*BLANKS, are moved as zeros to a numeric field in a MOVE operation.
Data Structures
The ILE RPG compiler allows you to define an area in storage and the layout of the fields, called subfields, within the area. This area in storage is called a data structure. | | | You define a data structure in free form by specifying the DCL-DS operation code followed by the data structure name and keywords. You define a data structure in fixed form by specifying DS in positions 24 through 25 on a definition specification. You can use a data structure to: v Define the same internal area multiple times using different data formats v Define a data structure and its subfields in the same way a record is defined. v Define multiple occurrences of a set of data. v Group non-contiguous data into contiguous internal storage locations.
4-10
Data Structures
v Operate on all the subfields as a group using the name of the data structure. v Operate on an individual subfield using its name. In addition, there are four special data structures, each with a specific purpose: v A data area data structure (identified by the *AUTO parameter of the DTAARA keyword for a free-form definition or a U in position 23 of a fixed-form definition) v A file information data structure (identified by the keyword INFDS on a file description specification) v A program-status data structure (identified by the PSDS keyword for a free-form definition, or by an S in position 23 of a fixed-form definition) v An indicator data structure (identified by the keyword INDDS on a file description specification). Data structures can be either program-described or externally described, except for indicator data structures, which are program-described only. One data structure can be defined like another using the LIKEDS keyword. A program-described data structure is identified by the absence of the EXT or EXTNAME keywords for a free-form definition, or by a blank in position 22 of a fixed-form definition. The subfield definitions for a program-described data structure must immediately follow the data structure definition. | | | | | An externally described data structure, identified by the EXT keyword or the EXTNAME keyword for a free-form definition, or by an E in position 22 of a fixed-form definition, has subfield descriptions contained in an externally described file. At compile time, the ILE RPG compiler uses the external name to locate and extract the external description of the data structure subfields. If the EXTNAME keyword is not specified, the name of the data structure is used for the external file name. Note: The data formats specified for the subfields in the external description are used as the internal formats of the subfields by the compiler. This differs from the way in which externally described files are treated. An external subfield name can be renamed in the program using the keyword EXTFLD. The keyword PREFIX can be used to add a prefix to the external subfield names that have not been renamed with EXTFLD. Note that the data structure subfields are not affected by the PREFIX keyword specified on a file-description specification even if the file name is the same as the parameter specified in the EXTNAME keyword when defining the data structure using an external file name. Additional subfields can be added to an externally described data structure by specifying program-described subfields immediately after the list of external subfields.
| | | |
Definitions
4-11
Data Structures
In addition, arbitrary levels of indexing and qualification are allowed. For example, a programmer could code:ds(x).subf1.s2.s3(y+1).s4 as an operand within an expression. Please see QUALIFIED on page 5-139 for further information on the use of the QUALIFIED keyword. Fully qualified names may be specified as the Result-Field operand for opcodes CLEAR and DSPLY when coded in free-form calc specs. Expressions are allowed as Factor 1 and Factor 2 operands for opcode DSPLY (coded in free-form calculation specifications), however, if the operand is more complex than a fully qualified name, the expression must be enclosed in parentheses.
4-12
Data Structures
# # # # #
SORTA TEAMS(*).EMPS.NAME; SORTA TEAMS.EMPS(*).NAME;
e. This statement is not valid because at least one array must be indexed by (*). TEAMS(1).EMPS(1).NAME is a scalar value.
SORTA TEAMS(1).EMPS(1).NAME;
* PartInfo is a data structure describing a part. PartInfo DS QUALIFIED Manufactr 4 Drug 6 Strength 3 Count 3 0 * Procedure "Proc" has a parameter "Part" that is a data * structure whose subfields are the same as the subfields * in "PartInfo". When calling this procedure, it is best * to pass a parameter that is also defined LIKEDS(PartInfo) * (or pass "PartInfo" itself), but the compiler will allow * you to pass any character field that has the correct * length. D Proc PR D Part LIKEDS(PartInfo) P Proc B * The procedure interface also defines the parameter Part * with keyword LIKEDS(PartInfo). * This means the parameter is a data structure, and the subfields * can be used by specifying them qualified with "Part.", for * example "Part.Strength" D Proc PI D Part LIKEDS(PartInfo) C IF Part.Strength > getMaxStrength (Part.Drug) C CALLP PartError (Part : DRUG_STRENGTH_ERROR) C ELSE C EVAL Part.Count = Part.Count + 1 C ENDIF P Proc E D D D D D
Definitions
4-13
Data Structures
You can also define a subfield like an existing item using the LIKE keyword. When defined in this way, the subfield receives the length and data type of the item on which it is based. Similarly, you can use the LIKEDS keyword to define an entire data structure like an existing item. See Examples of defining data using the LIKE keyword on page 5-116 for an example using the LIKE keyword. The keyword LIKEDS is allowed on any subfield definition. When specified, the subfield is defined to be a data structure, with its own set of subfields. If data structure DS has subfield S1 which is defined like a data structure with a subfield S2, a programmer must refer to S2 using the expression DS.S1.S2. Note: 1. Keyword LIKEDS is allowed for subfields only within QUALIFIED data structures. 2. Keywords DIM and LIKEDS are both allowed on the same subfield definition. You can overlay the storage of a previously defined subfield with that of another subfield using the OVERLAY keyword. The keyword is specified on the later subfield definition. See Figure 4-9 on page 4-20 for an example using the OVERLAY keyword. Specifying Subfield Length: The length of a subfield may be specified using absolute (positional) or length notation, or its length may be implied. Free-form The length is specified as a parameter to the data-type keyword. Absolute notation in fixed form Specify a value in both the From-Position (positions 26 through 32) and the To-Position/Length (positions 33 through 39) entries on the definition specification. Length notation in fixed form Specify a value in the To-Position/Length (positions 33 through 39) entry. The From-Position entry is blank. Implied Length If a subfield appears in the first parameter of one or more OVERLAY keywords, the subfield can be defined without specifying any type or length information. In this case, the type is character and the length is determined by the overlaid subfields. | | | | | | In addition, some data types, such as Pointers, Dates, Times and Timestamps have a fixed length. For these types, the length is implied, although it can be specified in fixed form. When the POS keyword is not specified in a free-form definition, or the From-Position is not specified in a fixed-form definition, the subfield is positioned such that its starting position is greater than the maximum ending position of all previously defined subfields. For examples of each notation, see Data Structure Examples on page 4-16. Aligning Data Structure Subfields: Alignment of subfields may be necessary. In some cases it is done automatically; in others, it must be done manually. For example, when defining subfields of type basing pointer or procedure pointer using the length notation, the compiler will automatically perform padding if necessary to ensure that the subfield is aligned properly. When defining float, integer or unsigned subfields, alignment may be desired to improve run-time performance. If the subfields are defined using length notation, you can automatically align float, integer or unsigned subfields by specifying the keyword ALIGN on the data structure definition. However, note the following exceptions: v The ALIGN keyword is not allowed for a file information data structure or a program status data structure.
4-14
Data Structures
v Subfields defined using the keyword OVERLAY are not aligned automatically, even if the keyword ALIGN is specified for the data structure. In this case, you must align the subfields manually. Automatic alignment will align the fields on the following boundaries. v 2 bytes for 5-digit integer or unsigned subfields v 4 bytes for 10-digit integer or unsigned subfields or 4-byte float subfields v 8 bytes for 20-digit integer or unsigned subfields v 8 bytes for 8-byte float subfields v 16 bytes for pointer subfields If you are aligning fields manually, make sure that they are aligned on the same boundaries. A start-position is on an n-byte boundary if ((position - 1) mod n) = 0. (The value of "x mod y" is the remainder after dividing x by y in integer arithmetic. It is the same as the MVR value after X DIV Y.) Figure 4-5 shows a sequence of bytes and identifies the different boundaries used for alignment.
Note the following about the above byte sequence: v Position 1 is on a 16-byte boundary, since ((1-1) mod 16) = 0. v Position 13 is on a 4-byte boundary, since ((13-1) mod 4) = 0. v Position 7 is not on a 4-byte boundary, since ((7-1) mod 4) = 2. Initialization of Nested Data Structures: The keyword INZ(*LIKEDS) is allowed on a LIKEDS subfield. The LIKEDS subfield is initialized exactly the same as the corresponding data structure. Keyword INZ is allowed on a LIKEDS subfield. All nested subfields of the LIKEDS subfield are initialized to their default values. This also applies to more deeply nested LIKEDS subfields, with the exception of nested LIKEDS subfields with INZ(*LIKEDS) specified. If keyword INZ is coded on a main data structure definition, keyword INZ is implied on all subfields of the data structure without explicit initialization. This includes LIKEDS subfields.
4-15
Data Structures
This indicates to the compiler that it should read in and lock the data area of the same name at program initialization and should write out and unlock the same data area at the end of the program. Locking does not apply to the local data area (see Local Data Area (*LDA)). Data area data structures, as in all other data structures, have the type character. A data area read into a data area data structure must also be character. The data area and data area data structure must have the same name unless you rename the data area within the ILE RPG program by using the *DTAARA DEFINE operation code or the DTAARA keyword. You can specify the data area operations (IN, OUT, and UNLOCK) for a data area that is implicitly read in and written out. Before you use a data area data structure with these operations, you must specify that data area data structure name in the result field of the *DTAARA DEFINE operation or with the DTAARA keyword. A data area data structure cannot be specified in the result field of a PARM operation in the *ENTRY PLIST. | Local Data Area (*LDA): The compiler uses the local data area in the following situations: | v A free-form definition has the DTAARA keyword without a parameter for an unnamed data structure. | v A fixed-form definition has blanks for the name of the data area data structure (positions 7 through 21 | of the definition specification that contains a U in position 23). To provide a name for the local data area, use the *DTAARA DEFINE operation, with *LDA in factor 2 and the name in the result field or DTAARA(*LDA) on the definition specification. File Information Data Structure: You can specify a file information data structure (defined by the keyword INFDS on a file description specifications) for each file in the program. This provides you with status information on the file exception/error that occurred. A file information data structure can be used for only one file. A file information data structure contains predefined subfields that provide information on the file exception/error that occurred. For a discussion of file information data structures and their subfields, see File Information Data Structure on page 3-68. | | | | Program-Status Data Structure: A program-status data structure, identified by the PSDS keyword for a free-form definition, or by a blank in position 22 of a fixed-form definition, provides program exception/error information to the program. For a discussion of program-status data structures and their predefined subfields, see Program Status Data Structure on page 3-85. Indicator Data Structure: An indicator data structure is identified by the keyword INDDS on the file description specifications. It is used to store conditioning and response indicators passed to and from data management for a file. By default, the indicator data structure is initialized to all zeros ('0's). The rules for defining the data structure are: v It must not be externally described. v It can only have indicator or fixed-length character subfields. v It can be defined as a multiple occurrence data structure. v %SIZE for the data structure will return 99. For a multiple occurrence data structure, %SIZE(ds:*ALL) will return a multiple of 99. If a length is specified, it must be 99. v Subfields may contain arrays of indicators as long as the total length does not exceed 99.
4-16
Data Structures
Example Figure 4-8 on page 4-19 Figure 4-9 on page 4-20 Figure 4-10 on page 4-20 Figure 4-11 on page 4-21 Figure 4-12 on page 4-21 Figure 4-13 on page 4-22 Figure 4-14 on page 4-23 Figure 4-15 on page 4-24 Figure 4-16 on page 4-24 Figure 4-17 on page 4-25 Figure 4-18 on page 4-26 Description Using keywords QUALIFIED, LIKEDS, and DIM with data structures, and how to code fully-qualified subfields Data structure with absolute and length notation Rename and initialize an externally described data structure Using PREFIX to rename all fields in an external data structure Defining a multiple occurrence data structure Aligning data structure subfields Defining a *LDA data area data structure Using data area data structures (1) Using data area data structures (2) Using an indicator data structure Using a multiple-occurrence indicator data structure
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++ D.....................................Keywords+++++++++++++++++++++++++++++ * * Use length notation to define the data structure subfields. * You can refer to the entire data structure by using Partno, or by * using the individual subfields Manufactr, Drug, Strength or Count. * D Partno DS D Manufactr 4 D Drug 6 D Strength 3 D Count 3 0 D *.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 IFilename++SqNORiPos1+NCCPos2+NCCPos3+NCC.................................. I........................Fmt+SPFrom+To+++DcField+++++++++L1M1FrPlMnZr...... * * Records in program described file FILEIN contain a field, Partno, * which needs to be subdivided for processing in this program. * To achieve this, the field Partno is described as a data structure * using the above Definition specification * IFILEIN NS 01 1 CA 2 CB I 3 18 Partno I 19 29 Name I 30 40 Patno Figure 4-6. Using a Data structure to subdivide a field
Definitions
4-17
Data Structures
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++ D.....................................Keywords+++++++++++++++++++++++++++++ * * When you use a data structure to group fields, fields from * non-adjacent locations on the input record can be made to occupy * adjacent internal locations. The area can then be referred to by * the data structure name or individual subfield name. * D Partkey DS D Location 4 D Partno 8 D Type 4 D *.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 IFilename++SqNORiPos1+NCCPos2+NCCPos3+NCC.................................. I........................Fmt+SPFrom+To+++DcField+++++++++L1M1FrPlMnZr...... * * Fields from program described file TRANSACTN need to be * compared to the field retrieved from an Item_Master file * ITRANSACTN NS 01 1 C1 2 C2 I 3 10 Partno I 11 16 0Quantity I 17 20 Type I 21 21 Code I 22 25 Location I *.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq.... * * Use the data structure name Partkey, to compare to the field * Item_Nbr * C : C Partkey IFEQ Item_Nbr 99 C : C* Figure 4-7. Using a data structure to group fields
4-18
Data Structures
QUALIFIED BASED(@)
QUALIFIED BASED(@)
/free TotalCost = 0; for i = 1 to SalesTransation. Numproducts; TotalCost = TotalCost + SalesTransaction.Products (i).Cost; dsply SalesTransaction.Products (i).Cost; endfor; dsply (Total cost is + %char(TotalCost)); /end-free Figure 4-8. Using Keywords QUALIFIED, LIKEDS and DIM with data structures
Definitions
4-19
Data Structures
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++ D.....................................Keywords+++++++++++++++++++++++++++++ * * Define a program described data structure called FRED * The data structure is composed of 5 fields: * 1. An array with element length 10 and dimension 70(Field1) * 2. A field of length 30 (Field2) * 3/4. Divide Field2 in 2 equal length fields (Field3 and Field4) * 5. Define a binary field over the 3rd field * Note the indentation to improve readability * * * Absolute notation: * * The compiler will determine the array element length (Field1) * by dividing the total length (700) by the dimension (70) * D FRED DS D Field1 1 700 DIM(70) D Field2 701 730 D Field3 701 715 D Field5 701 704B 2 D Field4 716 730 * * Length notation: * * The OVERLAY keyword is used to subdivide Field2 * D FRED DS D Field1 10 DIM(70) D Field2 30 D Field3 15 OVERLAY(Field2) D Field5 4B 2 OVERLAY(Field3) D Field4 15 OVERLAY(Field2:16) Figure 4-9. Data structure with absolute and length notation
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++ D.....................................Keywords+++++++++++++++++++++++++++++ * * Define an externally described data structure with internal name * FRED and external name EXTDS and rename field CUST to CUSTNAME * Initialize CUSTNAME to GEORGE and PRICE to 1234.89. * Assign to subfield ITMARR the DIM keyword. * The ITMARR subfield is defined in the external description as a * 100 byte character field. This divides the 100 byte character * field into 10 array elements, each 10 bytes long. * Using the DIM keyword on an externally described numeric subfield * should be done with caution, because it will divide the field into * array elements (similar to the way it does when absolute notation * is used for program described subfields). * D Fred E DS EXTNAME(EXTDS) D CUSTNAME E EXTFLD(CUST) INZ(GEORGE) D PRICE E INZ(1234.89) D ITMARR E DIM(10) Figure 4-10. Rename and initialize an externally described data structure
4-20
Data Structures
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++ D.....................................Keywords+++++++++++++++++++++++++++++ D D extds1 E DS EXTNAME (CUSTDATA) D PREFIX (CU_) D Name E INZ (Joes Garage) D Custnum E EXTFLD (NUMBER) D * * The previous data structure will expand as follows: * -- All externally described fields are included in the data * structure * -- Renamed subfields keep their new names * -- Subfields that are not renamed are prefixed with the * prefix string * * Expanded data structure: * D EXTDS1 E DS D CU_NAME E 20A EXTFLD (NAME) D INZ (Joes Garage) D CU_ADDR E 50A EXTFLD (ADDR) D CUSTNUM E 9S0 EXTFLD (NUMBER) D CU_SALESMN E 7P0 EXTFLD (SALESMN) Figure 4-11. Using PREFIX to rename all fields in an external data structure
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++ D.....................................Keywords+++++++++++++++++++++++++++++ * * Define a Multiple Occurrence data structure of 20 elements with: * -- 3 fields of character 20 * -- A 4th field of character 10 which overlaps the 2nd * field starting at the second position. * * Named constant Max_Occur is used to define the number of * occurrences. * * Absolute notation (using begin/end positions) * D Max_Occur C CONST(20) D DDataStruct DS OCCURS (Max_Occur) D field1 1 20 D field2 21 40 D field21 22 31 D field3 41 60 * * Mixture of absolute and length notation * D DataStruct DS OCCURS(twenty) D field1 20 D field2 20 D field21 22 31 D field3 41 60 Figure 4-12. Defining a multiple occurrence data structure
Definitions
4-21
Data Structures
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++ * Data structure with alignment: D MyDS DS ALIGN * Properly aligned subfields * Integer subfields using absolute notation. D Subf1 33 34I 0 D Subf2 37 40I 0 * Integer subfields using length notation. * Note that Subf3 will go directly after Subf2 * since positions 41-42 are on a 2-byte boundary. * However, Subf4 must be placed in positions 45-48 * which is the next 4-byte boundary after 42. D Subf3 5I 0 D Subf4 10I 0 * Integer subfields using OVERLAY. D Group 101 120A D Subf6 5I 0 OVERLAY (Group: 3) D Subf7 10I 0 OVERLAY (Group: 5) D Subf8 5U 0 OVERLAY (Group: 9) * Subfields that are not properly aligned: * Integer subfields using absolute notation: D SubfX1 10 11I 0 D SubfX2 15 18I 0 * Integer subfields using OVERLAY: D BadGroup 101 120A D SubfX3 5I 0 OVERLAY (BadGroup: 2) D SubfX4 10I 0 OVERLAY (BadGroup: 6) D SubfX5 10U 0 OVERLAY (BadGroup: 11) * Integer subfields using OVERLAY: D WorseGroup 200 299A D SubfX6 5I 0 OVERLAY (WorseGroup) D SubfX7 10I 0 OVERLAY (WorseGroup: 3) * * The subfields receive warning messages for the following reasons: * SubfX1 - end position (11) is not a multiple of 2 for a 2 byte field. * SubfX2 - end position (18) is not a multiple of 4 for a 4 byte field. * SubfX3 - end position (103) is not a multiple of 2. * SubfX4 - end position (109) is not a multiple of 4. * SubfX5 - end position (114) is not a multiple of 4. * SubfX6 - end position (201) is not a multiple of 2. * SubfX7 - end position (205) is not a multiple of 4. Figure 4-13. Aligning Data Structure Subfields
4-22
Data Structures
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++ D.....................................Keywords+++++++++++++++++++++++++++++ * * Define a data area data structure based on the *LDA. * * Example 1: * A data area data structure with no name is based on the *LDA. * In this case, the DTAARA keyword does not have to be used. * D UDS D SUBFLD 1 600A *.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++ * Example 2: * This data structure is explicitly based on the *LDA using * the DTAARA keyword. Since it is not a data area data * structure, it must be handled using IN and OUT operations. * D LDA_DS DS DTAARA(*LDA) D SUBFLD 1 600A ... C IN LDA_DS C OUT LDA_DS *.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++ * Example 3: * This data structure is explicitly based on the *LDA using * the DTAARA keyword. Since it is a data area data * structure, it is read in during initialization and written * out during termination. It can also be handled using IN * and OUT operations, since the DTAARA keyword was used. * D LDA_DS UDS DTAARA(*LDA) D SUBFLD 1 600A ... C IN LDA_DS C OUT LDA_DS Figure 4-14. Defining a *LDA data area data structure
Definitions
4-23
Data Structures
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 HKeywords++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ H DFTNAME(Program1) H * FFilename++IPEASF.....L.....A.Device+.Keywords+++++++++++++++++++++++++++ FSALESDTA IF E DISK * DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++ D.....................................Keywords+++++++++++++++++++++++++++++ * * This program uses a data area data structure to accumulate * a series of totals. The data area subfields are then added * to fields from the file SALESDTA. D Totals UDS D Tot_amount 8 2 D Tot_gross 10 2 D Tot_net 10 2 *.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 CL0N01Factor1+++++++Opcode(E)+Factor2++++++++++++++++++++++++++++++++++++++ * C : C EVAL Tot_amount = Tot_amount + amount C EVAL Tot_gross = Tot_gross + gross C EVAL Tot_net = Tot_net + net Figure 4-15. Using data area data structures (program 1)
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 HKeywords++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ H DFTNAME(Program2) *.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++ D.....................................Keywords+++++++++++++++++++++++++++++ * * This program processes the totals accumulated in Program1. * Program2 then uses the total in the subfields to do calculations. * D Totals UDS D Tot_amount 8 2 D Tot_gross 10 2 D Tot_net 10 2 *.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq.... * C : C EVAL *IN91 = (Amount2 <> Tot_amount) C EVAL *IN92 = (Gross2 <> Tot_gross) C EVAL *IN93 = (Net2 <> Tot_net) C : Figure 4-16. Using data area data structures (program 2)
4-24
Data Structures
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 FFilename++IPEASFRLen+LKlen+AIDevice+.Keywords++++++++++++++++++++++++++ * Indicator data structure "DispInds" is associated to file "Disp". FDisp CF E WORKSTN INDDS (DispInds) DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++ D.....................................Keywords+++++++++++++++++++++++++++++ * * This is the indicator data structure: * D DispInds DS * Conditioning indicators for format "Query" D ShowName 21 21N * Response indicators for format "Query" D Exit 3 3N D Return 12 12N D BlankNum 31 31N * Conditioning indicators for format "DispSflCtl" D SFLDSPCTL 41 41N D SFLDSP 42 42N D SFLEND 43 43N D SFLCLR 44 44N CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq.... * * Set indicators to display the subfile: C EVAL SFLDSP = *ON C EVAL SFLEND = *OFF C EVAL SFLCLR = *OFF C EXFMT DispSFLCTL * * Using indicator variables, we can write more readable programs: C EXFMT Query C IF Exit or Return C RETURN C ENDIF Figure 4-17. Using an indicator data structure
Definitions
4-25
Data Structures
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 FFilename++IPEASFRLen+LKlen+AIDevice+.Keywords++++++++++++++++++++++++++ * Indicator data structure "ErrorInds" is associated to file "Disp". FDisp CF E WORKSTN INDDS (ERRORINDS) DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++ D.....................................Keywords+++++++++++++++++++++++++++++ D @NameOk C 0 D @NameNotFound C 1 D @NameNotValid C 2 D @NumErrors C 2 * * Indicator data structure for ERRMSG: * D ERRORINDS DS OCCURS(@NumErrors) * Indicators for ERRMSG: D NotFound 1 1N D NotValid 2 2N * * Indicators for QUERY: D Exit 3 3N D Refresh 5 5N D Return 12 12N * * Prototype for GetName procedure (code not shown) D GetName PR 10I 0 D Name 50A CONST CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq.... * C DOU Exit or Return C EXFMT QUERY * Check the response indicators C SELECT C WHEN Exit or Return C RETURN C WHEN Refresh C RESET QUERY C ITER C ENDSL * * Check the name C EVAL RC = GetName(Name) * * If it is not valid, display an error message C IF RC <> @NameOk C RC OCCURS ErrorInds C EXFMT ERRMSG C ENDIF C ENDDO ... C *INZSR BEGSR * * Initialize the occurrences of the ErrorInds data structure C @NameNotFound OCCUR ErrorInds C EVAL NotFound = 1 C @NameNotValid OCCUR ErrorInds C EVAL NotValid = 1 C ENDSR Figure 4-18. Using a multiple-occurrence indicator data structure
4-26
Prototypes
A prototype is a definition of the call interface. It includes the following information: v Whether the call is bound (procedure) or dynamic (program) v How to find the program or procedure (the external name) v The number and nature of the parameters v Which parameters must be passed, and which are optionally passed v Whether operational descriptors should be passed v The data type of the return value, if any (for a procedure) # # # # # # # # # A prototype may be explicitly or implicitly defined. If the procedure is called from a different RPG module, the prototype must be explicitly specified in both the calling module and the module that defines the procedure. If the procedure is only called within the same module, the prototype may be explicitly defined, or it may be omitted. If the prototype is omitted, the compiler will implicitly define it from the procedure interface. For modules that call a procedure that is defined in a different module, a prototype must be included in the definition specifications of the program or procedure that makes the call. The prototype is used by the compiler to call the program or procedure correctly, and to ensure that the caller passes the correct parameters. The following rules apply to prototype definitions. v A prototype must have a name. If the keyword EXTPGM or EXTPROC is specified on the prototype definition, then any calls to the program or procedure use the external name specified for that keyword. If neither keyword is specified, then the external name is the prototype name in uppercase. v In free form, specify the DCL-PR operation code followed by the prototype name and keywords; in fixed form, specify PR in the Definition-Type entry (positions 24-25). Any parameter definitions must immediately follow the PR specification. In free-form, the prototype definition ends with the END-PR statement; in fixed form, the prototype definition ends with the first definition specification with non-blanks in positions 24-25 or by a non-definition specification. v Specify any of the following keywords as they pertain to the call interface: EXTPROC(name) The call will be a bound procedure call that uses the external name specified by the keyword. EXTPGM(name) The call will be an external program call that uses the external name specified by the keyword. OPDESC Operational descriptors are to be passed with the parameters that are described in the prototype. # # # RTNPARM The return value is to be handled as a parameter. This may improve performance when calling the procedure, especially for large return values.
Definitions
| | | | | | | |
4-27
If you are writing a prototype for an exported subprocedure or for a main procedure, put the prototype in a /COPY file and copy the prototype into the source file for both the callers and the module that defines the procedure. This coding technique provides maximum parameter-checking benefits for both the callers and the procedure itself, since they all use the same prototype.
Prototyped Parameters
# If the prototyped call interface involves the passing of parameters then you must define the parameter # immediately following the PR or PI specification. The following keywords, which apply to defining the # type, are allowed on the parameter definition specifications: ASCEND The array is in ascending sequence.
4-28
4-29
Procedure Interface
# # # # # # # If a prototyped program or procedure has call parameters or a return value, then a procedure interface definition must be defined, either in the main source section (for a cycle-main procedure) or in the subprocedure section. If a prototype was specified, the procedure interface definition repeats the prototype information within the definition of a procedure. Otherwise, the procedure interface provides the information that allows the compiler to implicitly define the prototype. The procedure interface is used to declare the entry parameters for the procedure and to ensure that the internal definition of the procedure is consistent with the external definition (the prototype).
The following rules apply to procedure interface definitions. | v The name of the procedure interface is optional. If specified, it must match the name of the | corresponding prototype definition. | v In a free-form definition, specify DCL-PI to begin a procedure interface definition. In a fixed-form | definition, specify PI in the Definition-Type entry (positions 24-25). The procedure-interface definition | can be specified anywhere in the definition specifications. In the cycle-main procedure, the procedure | interface must be preceded by the prototype that it refers to, if the prototoype is specified. A procedure | interface is if the procedure returns a value, or if it has any parameters; otherwise, it is optional. v Any parameter definitions must immediately follow the procedure-interface specification. | v A free-form procedure interface must end with END-PI, either at the end of the DCL-PI statement, or | as a separate statement following the parameters.
4-30
# # # #
UCS-2 v Format v Number of decimal positions (if numeric) Arrays and tables differ in that: v You can refer to a specific array element by its position v You cannot refer to specific table elements by their position v An array name by itself refers to all elements in the array v A table name always refers to the element found in the last LOOKUP (Look Up a Table or Array Element) on page 6-220 operation
Definitions
4-31
Arrays
There are three types of arrays: v The run-time array is loaded by your program while it is running. v The compile-time array is loaded when your program is created. The initial data becomes a permanent part of your program. v The prerun-time array is loaded from an array file when your program begins running, before any input, calculation, or output operations are processed. The essentials of defining and loading an array are described for a run-time array. For defining and loading compile-time and prerun-time arrays you use these essentials and some additional specifications.
| | | |
4-32
Arrays
*...1....+....2....+....3....+....4....+....5....+....6....+....7... DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++ DARC S 3A DIM(12) Figure 4-20. The Essential Array Specifications to Define a Run-Time Array
If the fields in the database record that correspond to the array are scattered throughout the database record, then the array must be loaded with a several Input specifications. The example in Figure 4-22 on page 4-34 assumes that the database record contains data for all the array elements, but a blank separates the data for each array element in the database record. Each Input specification defines the position in the database record for a single element.
Definitions
4-33
Arrays
*...1....+....2....+....3....+....4....+....5....+....6....+....7... DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++ DARRX S 12A DIM(6) IFilename++SqNORiPos1+NCCPos2+NCCPos3+NCC................................ I........................Fmt+SPFrom+To+++DcField+++++++++L1M1FrPlMnZr.... IARRFILE AA 01 I 1 12 ARRX(1) I 14 25 ARRX(2) I 27 38 ARRX(3) I 40 51 ARRX(4) I 53 64 ARRX(5) I 66 77 ARRX(6) Figure 4-22. Defining a Run-Time Array with Scattered Elements
Loading a Run-Time Array by Reading Several Records from A File: If the data for the array is not available in a single record from the database file, the array must be loaded by reading more than one record from the database file. Each record may provide the data for one or more elements of the array. The ILE RPG program processes one record at a time. Therefore, the entire array is not processed until all the records containing the array information are read and the information is moved into the array elements. It may be necessary to suppress calculation and output operations until the entire array is read into the program. For example, assume that each record from file ARRFILE2 contains the information for one array element in positions 1-12. You can code the Input specification for the array element with a variable index. Your program would set the index before the record was read as shown in Figure 4-23.
*...1....+....2....+....3....+....4....+....5....+....6....+....7... DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++ DARRX S 12A DIM(6) DN S 5P 0 INZ(1) IFilename++SqNORiPos1+NCCPos2+NCCPos3+NCC................................ I........................Fmt+SPFrom+To+++DcField+++++++++L1M1FrPlMnZr.... IARRFILE2 AA 01 I 1 12 ARRX(N) CL0N01Factor1+++++++Opcode&ExtFactor2;+++++++Result++++++++Len++D+HiLoEq C IF N = %ELEM(ARR) * The array has been loaded ..... process the array * Set the index to 1 to prepare for the next complete array C EVAL N = 1 C ELSE * Increment the index so the next input operation will fill * the next array element C EVAL N = N + 1 C ENDIF Figure 4-23. Loading an array from a file, one element per record
Loading an Array from Identical Externally-Described Fields: If an input record from a externally-described database file has several fields that are defined identically, you can define a data structure that will allow you to process those fields as though they were an array. There are three cases to consider: 1. The fields are consecutive in the record and appear at the beginning of the record.
A A A A A R REC FLD1 FLD2 FLD3 OTHER 5P 0 5P 0 5P 0 10A
For this case, you can use an externally-described data structure and define your array as an additional subfield, mapping the array to the fields using the OVERLAY keyword:
4-34
Arrays
FMYFILE IF D myDS D fldArray D C C C* C A A A A A A A E E DS DISK EXTNAME(MYFILE) LIKE(FLD1) DIM(3) OVERLAY(myDs)
READ MYFILE FOR i = 1 to %ELEM(fldArray) ... process fldArray(i) ENDFOR R REC OTHER1 10A ... more fields FLD1 15A FLD2 15A FLD3 15A OTHER2 10A
2. The fields are consecutive in the record but do not appear at the beginning of the record.
For this case, you can use an externally-described data structure and define your array as a standalone field, mapping the array to the fields using the BASED keyword, and initializing the basing pointer to the address of the first field.
FMYFILE D myDS IF E E DS S S * DISK EXTNAME(MYFILE) LIKE(FLD1) DIM(3) BASED(pFldArray) INZ(%addr(FLD1))
D fldArray D D pFldArray C C C* C A A A A A A A
READ MYFILE FOR i = 1 to %ELEM(fldArray) ... process fldArray(i) ENDFOR R REC OTHER1 FLD1 FLD2 OTHER2 FLD3 OTHER3
For this case, you must define a program-described data structure and list the fields to be used for the array without defining any type information. Then map the array to the fields using the OVERLAY keyword.
FMYFILE IF D myDS D FLD1 D FLD2 D FLD3 D fldArray D C C C* C E DS DISK
LIKE(FLD1) DIM(3) OVERLAY(myDs) READ MYFILE FOR i = 1 to %ELEM(fldArray) ... process fldArray(i) ENDFOR
Sequencing Run-Time Arrays: Run-time arrays are not sequence checked. If you process a SORTA (sort an array) operation, the array is sorted into the sequence specified on the definition specification (the ASCEND or DESCEND keywords) defining the array. If the sequence is not specified, the array is sorted into ascending sequence. When the high (positions 71 and 72 of the calculation specifications) or low (positions 73 and 74 of the calculation specifications) indicators are used in the LOOKUP operation, the array sequence must be specified.
Definitions
4-35
Arrays
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords++++++++++++++++++++ DARC S 3A DIM(12) PERRCD(5) CTDATA **CTDATA ARC 48K16343J64044HComments can be placed here 12648A47349K346Comments can be placed here 50B125 Comments can be placed here
v Each record, except the last, must contain the number of entries specified with the PERRCD keyword on the definition specifications. In the last record, unused entries must be blank and comments can be included after the unused entries. v Each entry must be contained entirely on one record. An entry cannot be split between two records; therefore, the length of a single entry is limited to the maximum length of 100 characters (size of
4-36
Arrays
source record). If arrays are used and are described in alternating format, corresponding elements must be on the same record; together they cannot exceed 100 characters. v For date and time compile-time arrays the data must be in the same format and use the same separators as the date or time array being loaded. v Array data may be specified in one of two ways: 1. **CTDATA arrayname: The data for the array may be specified anywhere in the compile-time data section. 2. **b: (b=blank) The data for the arrays must be specified in the same order in which they are specified in the Definition specifications. Only one of these techniques may be used in one program. v Arrays can be in ascending(ASCEND keyword), descending (DESCEND keyword), or no sequence (no keyword specified). v For ascending or descending character arrays when ALTSEQ(*EXT) is specified on the control specification, the alternate collating sequence is used for the sequence checking. If the actual collating sequence is not known at compile time (for example, if SRTSEQ(*JOBRUN) is specified on a control specification or as a command parameter) the alternate collating sequence table will be retrieved at runtime and the checking will occur during initialization at *INIT. Otherwise, the checking will be done at compile time. v Graphic and UCS-2 arrays will be sorted by hexadecimal values, regardless of the alternate collating sequence. v If L or R is specified on the EXTFMT keyword on the definition specification, each element must include the sign (+ or -). An array with an element size of 2 with L specified would require 3 positions in the source data as shown in the following example.
*....+....1....+....2....+....3....+....4....+....5....+....6....+....* DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords++++++++++++++++++++ D UPDATES 2 0 DIM(5) PERRCD(5) EXTFMT(L) CTDATA **CTDATA UDPATES +37-38+52-63-49+51
v Float compile-time data are specified in the source records as float or numeric literals. Arrays defined as 4-byte float require 14 positions for each element; arrays defined as 8-byte float require 23 positions for each element. v Graphic data must be enclosed in shift-out and shift-in characters. If several elements of graphic data are included in a single record (without intervening nongraphic data) only one set of shift-out and shift-in characters is required for the record. If a graphic array is defined in alternating format with a nongraphic array, the shift-in and shift-out characters must surround the graphic data. If two graphic arrays are defined in alternating format, only one set of shift-in and shift-out characters is required for each record.
4-37
Arrays
4-38
Arrays
Control Specification Entry ALTSEQ Used for SORTA, When Sequence Checked LOOKUP and Sequence for Compile Time Array Checking ALTSEQ(*NONE) ALTSEQ(*SRC) ALTSEQ(*EXT) (known at compile time) ALTSEQ(*EXT) (known only at run time) No No Yes Yes Compile time Compile time Compile time Run time When Sequence Checked for Prerun Time Array Run time Run time Run time Run time
Note: For compatibility with RPG III, SORTA and LOOKUP do not use the alternate collating sequence with ALTSEQ(*SRC). If you want these operations to be performed using the alternate collating sequence, you can define a table on the system (object type *TBL), containing your alternate sequence. Then you can change ALTSEQ(*SRC) to ALTSEQ(*EXT) on your control specification and specify the name of your table on the SRTSEQ keyword or parameter of the create command.
Initializing Arrays
Run-Time Arrays
To initialize each element in a run-time array to the same value, specify the INZ keyword on the definition specification. If the array is defined as a data structure subfield, the normal rules for data structure initialization overlap apply (the initialization is done in the order that the fields are declared within the data structure).
Definitions
4-39
The records for ARRA and ARRB look like the records below when described as two separate array files. This record contains ARRA entries in positions 1 through 60.
The records for ARRA and ARRB look like the records below when described as one array file in alternating format. The first record contains ARRA and ARRB entries in alternating format in positions 1 through 55. The second record contains ARRA and ARRB entries in alternating format in positions 1 through 55.
Figure 4-29. Arrays Records for One Array File in Alternating Format
4-40
Searching Arrays
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++ DARRA S 6A DIM(6) PERRCD(1) CTDATA DARRB S 5 0 DIM(6) ALT(ARRA) DARRGRAPHIC S 3G DIM(2) PERRCD(2) CTDATA DARRC S 3A DIM(2) ALT(ARRGRAPHIC) DARRGRAPH1 S 3G DIM(2) PERRCD(2) CTDATA DARRGRAPH2 S 3G DIM(2) ALT(ARRGRAPH1) **CTDATA ARRA 345126 373 38A437 498 39K143 1297 40B125 93 41C023 3998 42D893 87 **CTDATA ARRGRAPHIC ok1k2k3iabcok4k5k6iabc **CTDATA ARRGRAPH1 ok1k2k3k4k5k6k1k2k3k4k5k6i
Searching Arrays
The following can be used to search arrays: v The LOOKUP operation code v v v v v The The The The The %LOOKUP built-in function %LOOKUPLT built-in function %LOOKUPLE built-in function %LOOKUPGT built-in function %LOOKUPGE built-in function
For more information about the LOOKUP operation code, see: v Searching an Array with an Index on page 4-42 v Searching an Array Without an Index v LOOKUP (Look Up a Table or Array Element) on page 6-220 For more information about the %LOOKUPxx built-in functions, see %LOOKUPxx (Look Up an Array Element) on page 6-101.
4-41
Searching Arrays
Figure 4-30 shows an example of a LOOKUP on an array without an index.
*...1....+....2....+....3....+....4....+....5....+....6....+....7... FFilename++IPEASFRlen+LKlen+AIDevice+.Keywords++++++++++++++++++++++++++++ FARRFILE IT F 5 DISK F* DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++ DDPTNOS S 5S 0 DIM(50) FROMFILE(ARRFILE) D* CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq.. C* The LOOKUP operation is processed and, if an element of DPTNOS equal C* to the search argument (DPTNUM) is found, indicator 20 is set on. C DPTNUM LOOKUP DPTNOS 20 Figure 4-30. LOOKUP Operation for an Array without an Index
ARRFILE, which contains department numbers, is defined in the file description specifications as an input file (I in position 17) with an array file designation (T in position 18). The file is program described (F in position 22), and each record is 5 positions in length (5 in position 27). In the definition specifications, ARRFILE is defined as containing the array DPTNOS. The array contains 50 entries (DIM(50)). Each entry is 5 positions in length (positions 33-39) with zero decimal positions (positions 41-42). One department number can be contained in each record (PERRCD defaults to 1). # Searching an Array Data Structure # You can use the %LOOKUP built-in function to search an array data structure using one of its subfields # as a key. # For more information about searching an array data structure, see %LOOKUPxx (Look Up an Array # Element) on page 6-101.
4-42
Searching Arrays
*...1....+....2....+....3....+....4....+....5....+....6....+....7... FFilename++IPEASFRlen+LKlen+AIDevice+.Keywords++++++++++++++++++++++++++++ FARRFILE IT F 25 DISK F* DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++ DDPTNOS S 5S 0 DIM(50) FROMFILE(ARRFILE) DDPTDSC S 20A DIM(50) ALT(DPTNOS) D* CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq.. C* The Z-ADD operation begins the LOOKUP at the first element in DPTNOS. C Z-ADD 1 X 3 0 C* At the end of a successful LOOKUP, when an element has been found C* that contains an entry equal to the search argument DPTNUM, C* indicator 20 is set on and the MOVE operation places the department C* description, corresponding to the department number, into DPTNAM. C DPTNUM LOOKUP DPTNOS(X) 20 C* If an element is not found that is equal to the search argument, C* element X of DPTDSC is moved to DPTNAM. C IF NOT *IN20 C MOVE DPTDSC(X) DPTNAM 20 C ENDIF Figure 4-31. LOOKUP Operation on an Array with an Index
This example shows the same array of department numbers, DPTNOS, as Figure 4-30 on page 4-42. However, an alternating array of department descriptions, DPTDSC, is also defined. Each element in DPTDSC is 20 positions in length. If there is insufficient data in the file to initialize the entire array, the remaining elements in DPTNOS are filled with zeros and the remaining elements in DPTDSC are filled with blanks.
Using Arrays
Arrays can be used in input, output, or calculation specifications.
4-43
Using Arrays
when the last element of the array with the fewest elements has been processed. When factor 1 is not specified for the ADD, SUB, MULT, and DIV operations, factor 1 is assumed to be the same as the result field. v When one of the factors is a field, a literal, or a figurative constant and the other factor and the result field are arrays, the operation is done once for every element in the shorter array. The same field, literal, or figurative constant is used in all of the operations. v The result field must always be an array. v If an operation code uses factor 2 only (for example, Z-ADD, Z-SUB, SQRT, ADD, SUB, MULT, or DIV may not have factor 1 specified) and the result field is an array, the operation is done once for every element in the array. The same field or constant is used in all of the operations if factor 2 is not an array. v Resulting indicators (positions 71 through 76) cannot be used because of the number of operations being processed. v In an EVAL expression, if any arrays on the right-hand side are specified without an index, the left-hand side must also contain an array without an index. Note: When used in an EVAL operation %ADDR(arr) and %ADDR(arr(*)) do not have the same meaning. See %ADDR (Get Address of Variable) on page 6-65 for more detail. When coding an EVAL or a SORTA operation, built-in function %SUBARR(arr) can be used to select a portion of the array to be used in the operation. See %SUBARR (Set/Get Portion of an Array) on page 6-125 for more detail.
Sorting Arrays
# # # # You can sort an array or a section of an array using the SORTA (Sort an Array) on page 6-303 operation code. The array is sorted into sequence (ascending or descending), depending on the sequence specified for the array on the definition specification. If no sequence is specified for the array, the sequence defaults to ascending sequence, but you can sort in descending sequence by specifying the 'D' operation extender.
4-44
Sorting Arrays
# Sorting an Array Data Structure # You can use the SORTA operation to sort an array data structure using one of its subfields as a key. # For more information about sorting an array data structure, see SORTA (Sort an Array) on page 6-303.
Array Output
Entire arrays can be written out under ILE RPG control only at end of program when the LR indicator is on. To indicate that an entire array is to be written out, specify the name of the output file with the TOFILE keyword on the definition specifications. This file must be described as a sequentially organized output or combined file in the file description specifications. If the file is a combined file and is externally described as a physical file, the information in the array at the end of the program replaces the information read into the array at the start of the program. Logical files may give unpredictable results. If an entire array is to be written to an output record (using output specifications), describe the array along with any other fields for the record: v Positions 30 through 43 of the output specifications must contain the array name used in the definition specifications. v Positions 47 through 51 of the output specifications must contain the record position where the last element of the array is to end. If an edit code is specified, the end position must include blank positions and any extensions due to the edit code (see Editing Entire Arrays listed next in this chapter). Output indicators (positions 21 through 29) can be specified. Zero suppress (position 44), blank-after (position 45), and data format (position 52) entries pertain to every element in the array.
Definitions
4-45
Tables
* Define the "names" array as large as you think it could grow D names S 25A VARYING DIM(2000) * Define a variable to keep track of the number of valid elements D numNames S 10I 0 INZ(0) * Define another array D temp S 50A DIM(20) D p S 10I 0 /free // set 3 elements in the names array names(1) = Friendly; names(2) = Rusty; names(3) = Jerome; names(4) = Tom; names(5) = Jane; numNames = 5; // copy the current names to the temporary array // Note: %subarr could also be used for temp, but // it would not affect the number of elements // copied to temp temp = %subarr(names : 1 : numNames); // change one of the temporary values, and then copy // the changed part of the array back to the "names" array temp(3) = Jerry; temp(4) = Harry; // The number of elements actually assigned will be the // minimum of the number of elements in any array or // subarray in the expression. In this case, the // available sizes are 2 for the "names" sub-array, // and 18 for the "temp" subarray, from element 3 // to the end of the array. %subarr(names : 3 : 2) = %subarr(temp : 3); // sort the "names" array sorta %subarr(names : 1 : numNames); // search the "names" array // Note: %SUBARR is not used with %LOOKUP. Instead, // the start element and number of elements // are specified in the third and fourth // parameters of %LOOKUP. p = %lookup(Jane : names : 1 : numNames); Figure 4-33. Example using a dynamically-sized array
Tables
The explanation of arrays applies to tables except for the following differences: Activity Differences Defining A table name must be a unique symbolic name that begins with the letters TAB. Loading Tables can be loaded only at compilation time and prerun-time. Using and Modifying table elements Only one element of a table is active at one time. The table name is used to refer to the active element. An index cannot be specified for a table. Searching The LOOKUP operation is specified differently for tables. Different built-in functions are used for searching tables. Note: You cannot define a table in a subprocedure.
4-46
Tables
The following can be used to search a table: v The LOOKUP operation code v The %TLOOKUP built-in function v The %TLOOKUPLT built-in function v The %TLOOKUPLE built-in function v The %TLOOKUPGT built-in function v The %TLOOKUPGE built-in function For more information about the LOOKUP operation code, see: v LOOKUP with One Table v LOOKUP with Two Tables v LOOKUP (Look Up a Table or Array Element) on page 6-220 For more information about the %TLOOKUPxx built-in functions, see %TLOOKUPxx (Look Up a Table Element) on page 6-132.
Definitions
4-47
Tables
*...1....+....2....+....3....+....4....+....5....+....6....+....7... CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq.. C* The LOOKUP operation searches TABEMP for an entry that is equal to C* the contents of the field named EMPNUM. If an equal entry is C* found in TABEMP, indicator 09 is set on, and the TABEMP entry and C* its related entry in TABPAY are made the current elements. C EMPNUM LOOKUP TABEMP TABPAY 09 C* If indicator 09 is set on, the contents of the field named C* HRSWKD are multiplied by the value of the current element of C* TABPAY. C IF *IN09 C HRSWKD MULT(H) TABPAY AMT 6 2 C ENDIF Figure 4-34. Searching for an Equal Entry
4-48
Tables
v v v v Timestamp Data Type on page 4-77 Object Data Type on page 4-77 Basing Pointer Data Type on page 4-79 Procedure Pointer Data Type on page 4-85
In addition, some of the data types allow different data formats. This chapter describes the difference between internal and external data formats, describes each format, and how to specify them.
Internal Format
The default internal format for numeric standalone fields is packed-decimal. The default internal format for numeric data structure subfields is zoned-decimal. To specify a different internal format, specify the format desired in position 40 on the definition specification for the field or subfield. The default format for date, time, and timestamp fields is *ISO. In general, it is recommended that you use the default ISO internal format, especially if you have a mixture of external format types. For date, time, and timestamp fields, you can use the DATFMT and TIMFMT keywords on the control specification to change the default internal format, if desired, for all date-time fields in the program. You can use the DATFMT or TIMFMT keyword on a definition specification to override the default internal format of an individual date-time field.
External Format
If you have numeric, character, or date-time fields in program-described files, you can specify their external format. The external format does not affect the way in which a field is processed. However, you may be able to improve performance of arithmetic operations, depending on the internal format specified. For more information, see Performance Considerations on page 6-15.
Definitions
4-49
Specifying an External Format for a Numeric Field: For any of the fields in Table 4-1, specify one of the following valid external numeric formats: B F I L P R S U Binary Float Integer Left sign Packed decimal Right sign Zoned decimal Unsigned
The default external format for float numeric data is called the external display representation. The format for 4-byte float data is:
+n.nnnnnnnE+ee, where + represents the sign (+ or -) n represents digits in the mantissa e represents digits in the exponent
Note that a 4-byte float value occupies 14 positions and an 8-byte float value occupies 23 positions. For numeric data other than float, the default external format is zoned decimal. The external format for compile-time arrays and tables must be zoned-decimal, left-sign or right-sign. For float compile-time arrays and tables, the compile-time data is specified as either a numeric literal or a float literal. Each element of a 4-byte float array requires 14 positions in the source record; each element of an 8-byte float array requires 23 positions. Non-float numeric fields defined on input specifications, calculation specifications, or output specifications with no corresponding definition on a definition specification are stored internally in packed-decimal format. Specifying an External Format for a Character, Graphic, or UCS-2 Field: For any of the input and output fields in Table 4-1, specify one of the following valid external data formats: A N G Character (valid for character and indicator data) Indicator (valid for character and indicator data) Graphic (valid for graphic data)
4-50
The EXTFMT keyword can be used to specify the data for an array or table in UCS-2 format. Specify the *VAR data attribute in positions 31-34 on an input specification and in positions 53-80 on an output specification for variable-length character, graphic, or UCS-2 data. Specifying an External Format for a Date-Time Field: If you have date, time, and timestamp fields in program-described files, then you must specify their external format. You can specify a default external format for all date, time, and timestamp fields in a program-described file by using the DATFMT and TIMFMT keywords on a file description specification. You can specify an external format for a particular field as well. Specify the desired format in positions 31-34 on an input specification. Specify the appropriate keyword and format in positions 53-80 on an output specification. For more information on each format type, see the appropriate section in the remainder of this chapter.
Character data may contain one or more single-byte or double-byte characters, depending on the format specified. Character, graphic, and UCS-2 fields can also have either a fixed or variable-length format. The following table summarizes the different character data-type formats.
Character Data Type Character Number of Bytes One or more single-byte characters that are fixed or variable in length CCSID If CCSID(*CHAR:*JOBRUN) is specified on the Control specification, the character CCSID is assumed to be the runtime job CCSID. Otherwise, the CCSID is assumed to be the mixed graphic CCSID related to the job CCSID. If CCSID(*CHAR:*JOBRUN) is specified on the Control specification, the character CCSID is assumed to be the runtime job CCSID. Otherwise, the CCSID is assumed to be the mixed graphic CCSID related to the job CCSID. 65535 or a CCSID with the EBCDIC double-byte encoding scheme (x'1200') 13488 or a CCSID with the UCS-2 encoding scheme (X'7200')
Indicator
Graphic UCS-2
One or more double-byte characters that are fixed or variable in length One or more double-byte characters that are fixed or variable in length
For information on the CCSIDs of character data, see Conversion between Character, Graphic and UCS-2 Data on page 4-62.
Character Format
The fixed-length character format is one or more bytes long with a set length. For information on the variable-length character format, see Variable-Length Character, Graphic and UCS-2 Formats on page 4-54.
Definitions
4-51
Indicator Format
The indicator format is a special type of character data. Indicators are all one byte long and can only contain the character values '0' (off) and '1' (on). They are generally used to indicate the result of an operation or to condition (control) the processing of an operation. The default value of indicators is '0'. | | | | You define an indicator field by specifying the IND keyword in a free-form definition or by specifying N in the Data-Type entry of a fixed-form specification. You can also define an indicator field using the LIKE keyword on the definition specification where the parameter is an indicator field. Indicator fields are also defined implicitly with the COMMIT keyword on the file description specification. A special set of predefined RPG IV indicators (*INxx) is also available. For a description of these indicators, see RPG IV Indicators on page 3-40. The rules for defining indicator variables are: v Indicators can be defined as standalone fields, subfields, prototyped parameters, and procedure return values. v If an indicator variable is defined as a prerun-time or compile-time array or table, the initialization data must consist of only '0's and '1's. Note: If an indicator contains a value other than '0' or '1' at runtime, the results are unpredictable. v If the keyword INZ is specified, the value must be one of '0', *OFF, '1', or *ON. v The keyword VARYING cannot be specified for an indicator field. The rules for using indicator variables are: v The default initialization value for indicator fields is '0'. v Operation code CLEAR sets an indicator variable to '0'. v Blank-after function applied to an indicator variable sets it to '0'. v If an array of indicators is specified as the result of a MOVEA(P) operation, the padding character is '0'. v Indicators are implicitly defined with ALTSEQ(*NONE). This means that the alternate collating sequence is not used for comparisons involving indicators. v Indicators may be used as key-fields where the external key is a character of length 1.
Graphic Format
| The graphic format is a character string where each character is represented by 2 bytes where all | characters are part of a specific double-byte characer set. | Note: For information on the UCS-2 format which also uses double-byte Unicode characters, see UCS-2 | Format on page 4-53. Fields defined as graphic data do not contain shift-out (SO) or shift-in (SI) characters. The difference between single byte character and double byte graphic data is shown in the following figure:
4-52
1 byte
1 byte
1 byte
1 char
1 char
1 char
1 char
1 byte
1 byte
1 byte
1 graphic char
1 graphic char
The length of a graphic field, in bytes, is two times the number of graphic characters in the field. The fixed-length graphic format is a character string with a set length where each character is represented by 2 bytes. For information on the variable-length graphic format, see Variable-Length Character, Graphic and UCS-2 Formats on page 4-54. | | | You define a graphic field by specifying the GRAPH or VARGRAPH keyword in a free-form definition or by specifying G in the Data-Type entry of a fixed-form specification. You can also define one using the LIKE keyword on the definition specification where the parameter is a graphic field. The default initialization value for graphic data is X'4040'. The value of *HIVAL is X'FFFF', and the value of *LOVAL is X'0000'. Note: The examples of graphic literals in this manual are not valid graphic literals. They use the letter 'o' to represent the shift-out character and the letter 'i' to represent the shift-in character. Often the graphic data is expressed as D1D2 or AABB; these are not valid double-byte characters. Normally, graphic literals are entered using a DBCS-capable keyboard that automatically enters the shift-out and shift-in characters before and after the DBCS characters are entered.
UCS-2 Format
The Universal Character Set (UCS-2) format is a character string where each character is represented by 2 bytes. This character set can encode the characters for many written languages. Fields defined as UCS-2 data do not contain shift-out (SO) or shift-in (SI) characters. The length of a UCS-2 field, in bytes, is two times the number of UCS-2 characters in the field. The fixed-length UCS-2 format is a character string with a set length where each character is represented by 2 bytes. For information on the variable-length UCS-2 format, see Variable-Length Character, Graphic and UCS-2 Formats on page 4-54. | | | You define a UCS-2 field by specifying the UCS2 or VARUCS2 keyword in a free-form definition or by specifying C in the Data-Type entry of a fixed-form specification. You can also define one using the LIKE keyword on the definition specification where the parameter is a UCS-2 field.
Definitions
4-53
| | | | | |
The unsigned integer length prefix can be either two bytes long or four bytes long. You indicate the size of the prefix by specifying 2 or 4 for the second parameter of the VARCHAR, VARGRAPH, or VARUCS2 keyword of a free-form definition, or using the parameter of the VARYING keyword of a fixed-format specification, either VARYING(2) or VARYING(4). If you specify VARCHAR, VARGRAPH, or VARUCS2 without a second parameter, or VARYING without a parameter, a size of 2 is assumed if the specified length is between 1 and 65535; otherwise, a size of 4 is assumed. Figure 4-38 shows how variable-length graphic fields are stored. UCS-2 fields are stored similarly.
-----------------------------------| current | graphic-data | | length | | -----------------------------------UNS(V) CHAR(N) N = declared maximum length = number of double bytes V = number of bytes specified for the length prefix V + 2(N) = total number of bytes Figure 4-38. Graphic Fields with Variable-Length Format
Note: Only the data up to and including the current length is significant. | | | | You define a variable-length field by specifying the VARCHAR, VARGRAPH, or VARUCS2 keyword on a free-form definition, or by specifying A (character), G (graphic), or C (UCS-2) and the keyword VARYING on a fixed-form definition specification. It can also be defined using the LIKE keyword on a definition specification where the parameter is a variable-length field.
4-54
| | | |
# # # # # # # #
Definitions
4-55
4-56
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
* .. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... DName+++++++++++ETDsFrom+++To/L+++IDc.Functions++++++++++++++++ *------------------------------------------------------------* Graphic fields *------------------------------------------------------------* Standalone fields: D GRA20 S 20G VARYING D MAX_LEN_G S 8386550G VARYING DCL-S free_form_10G VARGRAPH(10); * Prerun-time array: D ARR1 S 100G VARYING FROMFILE(DATAF) * Data structure subfields: D DS1 DS * Subfield defined with length notation: D SF3_20 20G VARYING * Subfield defined using positional notation: G(10)VAR D SF6_10 11 32G VARYING *------------------------------------------------------------* UCS-2 fields *------------------------------------------------------------D MAX_LEN_C S 8386550C VARYING DCL-S free_form_10C VARUCS2(10); D FLD1 S 5C INZ(%UCS2(ABCDE)) VARYING D FLD2 S 2C INZ(U01230123) VARYING D FLD3 S 2C INZ(*HIVAL) VARYING D DS_C DS D SF3_20_C 20C VARYING * Subfield defined using positional notation: C(10)VAR D SF_110_C 11 32C VARYING Figure 4-40. Defining Variable-Length Graphic and UCS-2 Fields
Using Variable-Length Fields: The length part of a variable-length field represents the current length of the field measured in characters. For character fields, this length also represents the current length in bytes. For double-byte fields (graphic and UCS-2), this represents the length of the field in double bytes. For example, a UCS-2 field with a current length of 3 is 3 double-byte characters long, and 6 bytes long. The following sections describe how to best use variable-length fields and how the current length changes when using different operation codes. How the Length of the Field is Set: When a variable-length field is initialized using INZ, the initial length is set to be the length of the initialization value. For example, if a character field of length 10 is initialized to the value 'ABC', the initial length is set to 3. The EVAL operation changes the length of a variable-length target. For example, if a character field of length 10 is assigned the value 'XY', the length is set to 2.
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++ D fld 10A VARYING * It does not matter what length fld has before the * EVAL; after the EVAL, the length will be 2. CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq... C EVAL fld = XY
The DSPLY operation changes the length of a variable-length result field to the length of the value entered by the user. For example, if the result field is a character field of length 10, and the value entered by the user is '12345', the length of the field will be set to 5 by the DSPLY operation. The CLEAR operation changes the length of a variable-length field to 0.
Definitions
4-57
Note: The recommended use for MOVE and MOVEL, as opposed to EVAL, is for changing the value of fields that you want to be temporarily fixed in length. An example is building a report with columns whose size may vary from day to day, but whose size should be fixed for any given run of the program. When a field is read from a file (Input specifications), the length of a variable-length field is set to the length of the input data. The "Blank After" function of Output specifications sets the length of a variable-length field to 0. You can set the length of a variable-length field yourself using the %LEN built-in function on the left-hand-side of an EVAL operation. How the Length of the Field is Used: When a variable-length field is used for its value, its current length is used. For the following example, assume 'result' is a fixed length field with a length of 7.
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++ D fld 10A VARYING * For the following EVAL operation * Value of fld Length of fld result * -------------------------------------* ABC 3 ABCxxx * A 1 Axxx * 0 xxx * ABCDEFGHIJ 10 ABCDEFG CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq... C EVAL result = fld + xxx * For the following MOVE operation, assume result * has the value ....... before the MOVE. * Value of fld Length of fld result * -------------------------------------* ABC 3 ....ABC * A 1 ......A * 0 ....... * ABCDEFGHIJ 10 DEFGHIJ C MOVE fld result
Why You Should Use Variable-Length Fields: Using variable-length fields for temporary variables can improve the performance of string operations, as well as making your code easier to read since you do not have to save the current length of the field in another variable for %SUBST, or use %TRIM to ignore the extra blanks.
4-58
Definitions
4-59
4-60
*..1....+....2....+....3....+....4....+....5....+....6....+....7....+.. A* A* File MASTER contains a variable-length field A* AAN01N02N03T.Name++++++Rlen++TDpBLinPosFunctions+++++++++++++++++++++ A* A R REC A FLDVAR 100 VARLEN *..1....+....2....+....3....+....4....+....5....+....6....+....7....+.. * * * Specify the CVTOPT(*VARCHAR) keyword on a control * specification or compile the ILE RPG program with * CVTOPT(*VARCHAR) on the command. * HKeywords++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * H CVTOPT(*VARCHAR) * * Externally described file name is MASTER. * FFilename++IPEASFRlen+LKlen+AIDevice+.Keywords++++++++++++++++++++++++++++ * FMASTER UF E DISK * * FLDVAR is a variable-length field defined in DDS with * a DDS length of 100. Notice that the RPG field length * is 102. * DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++ * D DS D FLDVAR 1 102 D FLDLEN 5U 0 OVERLAY(FLDVAR:1) D FLDCHR 100 OVERLAY(FLDVAR:3) CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq.. * * A character value is moved to the field FLDCHR. * After the CHECKR operation, FLDLEN has a value of 5. C READ MASTER LR C MOVEL SALES FLDCHR C CHECKR FLDCHR FLDLEN C NLR UPDATE REC Figure 4-42. Converting a Variable-Length Character Field
If you would like to use a converted variable-length graphic field, you can code a 2-byte unsigned integer field to hold the length, and a graphic subfield of length N to hold the data portion of the field.
Definitions
4-61
* * Specify the CVTOPT(*VARGRAPHIC) keyword on a control * specification or compile the ILE RPG program with * CVTOPT(*VARGRAPHIC) on the command. * * The variable-length graphic field VGRAPH is declared in the * DDS as length 3. This means the maximum length of the field * is 3 double bytes, or 6 bytes. The total length of the field, * counting the length portion, is 8 bytes. * DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++ * D DS DVGRAPH 8 D VLEN 4U 0 OVERLAY(VGRAPH:1) D VDATA 3G OVERLAY(VGRAPH:3) * * Assume GRPH is a fixed-length graphic field of length 2 * double bytes. Copy GRPH into VGRAPH and set the length of * VGRAPH to 2. * CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq.. C* C MOVEL GRPH VDATA C Z-ADD 2 VLEN Figure 4-43. Converting a Variable-Length Graphic Field
4-62
# Comparison # Both operands are converted to UCS-2 before comparison. # Assignment # The source value is converted to the type and CCSID of the target value. # Parameters passed by value and by read-only reference # The passed parameter is converted to the type and CCSID of the prototyped parameter. # Note: While implicit conversion is supported for the result of a concatenation expression, all the # operands of the concatenation expression must have the same type and CCSID.
Definitions
4-63
The records that describe the alternate collating sequence must be preceded by a record with ** ( = blank) in positions 1 through 3. The remaining positions in this record can be used for comments.
4-64
Binary-Decimal Format
| | | | | | | | Binary-decimal format means that the sign (positive or negative) is in the leftmost bit of the field and the numeric value is in the remaining bits of the field. Positive numbers have a zero in the sign bit; negative numbers have a one in the sign bit and are in twos complement form. A binary field can be from one to nine digits in length and can be defined with decimal positions. If the length of the field is from one to four digits, the compiler assumes a binary field length of 2 bytes. If the length of the field is from five to nine digits, the compiler assumes a binary field length of 4 bytes. An item with binary-decimal format can only hold a limited range of values. For example, a two-byte binary field with two digits and zero decimal positions can hold values between -99 and 99. Note: The integer and unsigned integer data types are also in binary format, but they can hold the full range of values. A two-byte integer field can hold values between -32768 and 32767. A two-byte unsigned integer field can hold values between 0 and 65535. Processing of a Program-Described Binary Input Field: Every input field read in binary format is assigned a field length (number of digits) by the compiler. A length of 4 is assigned to a 2-byte binary field; a length of 9 is assigned to a 4-byte binary field, if the field is not defined elsewhere in the program. Because of these length restrictions, the highest decimal value that can be assigned to a 2-byte binary field is 9999 and the highest decimal value that can be assigned to a 4-byte binary field is 999 999 999. In general, a binary field of n digits can have a maximum value of n 9s. This discussion assumes zero decimal positions. Because a 2-byte field in binary format is converted by the compiler to a decimal field with 1 to 4 digits, the input value may be too large. If it is, the leftmost digit of the number is dropped. For example, if a four digit binary input field has a binary value of hexadecimal 6000, the compiler converts this to 24 576 in decimal. The 2 is dropped and the result is 4576. Similarly, the input value may be too large for a
Definitions
4-65
Float Format
The float format consists of two parts: v the mantissa and v the exponent. The value of a floating-point field is the result of multiplying the mantissa by 10 raised to the power of the exponent. For example, if 1.2345 is the mantissa and 5 is the exponent then the value of the floating-point field is:
1.2345 * (10 ** 5) = 123450
| You define a floating-point field by specifying the FLOAT keyword in a free-form definition, or by | specifying F in the data type entry of the appropriate specification. The decimal positions must be left blank. However, floating-point fields are considered to have decimal positions. As a result, float variables may not be used in any place where a numeric value without decimal places is required, such as an array index, do loop index, etc. The default initialization and CLEAR value for a floating point field is 0E0. The length of a floating point field is defined in terms of the number of bytes. It must be specified as either 4 or 8 bytes. The range of values allowed for a floating-point field are: 4-byte float (8 digits) -3.4028235E+38 to -1.1754944E-38, 0.0E+0, +1.1754944E-38 to +3.4028235E+38 8-byte float (16 digits) -1.797693134862315E+308 to -2.225073858507201E-308, 0.0E+0, +2.225073858507201E-308 to +1.797693134862315E+308 Note: Float variables conform to the IEEE standard as supported by the IBM i operating system. Since float variables are intended to represent "scientific" values, a numeric value stored in a float variable may not represent the exact same value as it would in a packed variable. Float should not be used when you need to represent numbers exactly to a specific number of decimal places, such as monetary amounts.
4-66
if DECEDIT(,) is specified
Input: When inputting float values, the value is specified just like a float literal. The value does not have to be normalized or adjusted in the field. When float values are defined as array/table initialization data, they are specified in fields either 14 or 23 characters long (for 4F and 8F respectively). Note the following about float fields: v Alignment of float fields may be desired to improve the performance of accessing float subfields. You can use the ALIGN keyword to align float subfields defined on a definition specification. 4-byte float subfields are aligned on a 4-byte boundary and 8-byte float subfields are aligned along a 8-byte boundary. For more information on aligning float subfields, see ALIGN on page 5-94. v Length adjustment is not allowed when the LIKE keyword is used to define a field like a float field. v Float input fields cannot be defined as match or control fields.
Integer Format
The integer format is similar to the binary format with two exceptions: v The integer format allows the full range of binary values v The number of decimal positions for an integer field is always zero. | | | You define an integer field by specifying the INT keyword in a free-form definition, or by specifying I in the Data-Type entry of the appropriate specification. You can also define an integer field using the LIKE keyword on a definition specification where the parameter is an integer field. The length of an integer field is defined in terms of number of digits; it can be 3, 5, 10, or 20 digits long. A 3-digit field takes up 1 byte of storage; a 5-digit field takes up 2 bytes of storage; a 10-digit field takes up 4 bytes; a 20-digit field takes up 8 bytes. The range of values allowed for an integer field depends on its length.
Definitions
4-67
Packed-Decimal Format
Packed-decimal format means that each byte of storage (except for the low order byte) can contain two decimal numbers. The low-order byte contains one digit in the leftmost portion and the sign (positive or negative) in the rightmost portion. The standard signs are used: hexadecimal F for positive numbers and hexadecimal D for negative numbers. The packed-decimal format looks like this:
The sign portion of the low-order byte indicates whether the numeric value represented in the digit portions is positive or negative. Figure 4-46 on page 4-72 shows what the decimal number 21544 looks like in packed-decimal format. Determining the Digit Length of a Packed-Decimal Field: Use the following formula to find the length in digits of a packed-decimal field:
Number of digits = 2n - 1, ...where n = number of packed input record positions used.
This formula gives you the maximum number of digits you can represent in packed-decimal format; the upper limit is 63. Packed fields can be up to 32 bytes long. Table 4-2 on page 4-69 shows the packed equivalents for zoned-decimal fields up to 63 digits long:
4-68
For example, an input field read in packed-decimal format has a length of five bytes (as specified on the input or definition specifications). The number of digits in this field equals 2(5) - 1 or 9. Therefore, when the field is used in the calculation specifications, the result field must be nine positions long. The PACKEVEN on page 5-136 keyword on the definition specification can be used to indicate which of the two possible sizes you want when you specify a packed subfield using from and to positions rather than number of digits.
Unsigned Format
The unsigned integer format is like the integer format except that the range of values does not include negative numbers. You should use the unsigned format only when non-negative integer data is expected. | | | You define an unsigned field by specifying the UNS keyword in a free-form definition, or by specifying U in the Data-Type entry of the appropriate specification. You can also define an unsigned field using the LIKE keyword on the definition specification where the parameter is an unsigned field. The length of an unsigned field is defined in terms of number of digits; it can be 3, 5, 10, or 20 digits long. A 3-digit field takes up 1 byte of storage; a 5-digit field takes up 2 bytes of storage; a 10-digit field takes up 4 bytes; a 20-digit field takes up 8 bytes. The range of values allowed for an unsigned field depends on its length. Field length Range of Allowed Values 3-digit unsigned 0 to 255 5-digit unsigned 0 to 65535 10-digit unsigned 0 to 4294967295 20-digit unsigned 0 to 18446744073709551615 For other considerations regarding the use of unsigned fields, including information on alignment, see Integer Format on page 4-67.
Definitions
4-69
Zoned-Decimal Format
Zoned-decimal format means that each byte of storage can contain one digit or one character. In the zoned-decimal format, each byte of storage is divided into two portions: a 4-bit zone portion and a 4-bit digit portion. The zoned-decimal format looks like this:
The zone portion of the low-order byte indicates the sign (positive or negative) of the decimal number. The standard signs are used: hexadecimal F for positive numbers and hexadecimal D for negative numbers. In zoned-decimal format, each digit in a decimal number includes a zone portion; however, only the low-order zone portion serves as the sign. Figure 4-46 on page 4-72 shows what the number 21544 looks like in zoned-decimal format. You must consider the change in field length when coding the end position in positions 40 through 43 of the Output specifications and the field is to be output in packed format. To find the length of the field after it has been packed, use the following formula:
n Field length = 2 + 1
. . . where n = number of digits in the zoned decimal field. (Any remainder from the division is ignored.)
You can specify an alternative sign format for zoned-decimal format. In the alternative sign format, the numeric field is immediately preceded or followed by a + or - sign. A plus sign is a hexadecimal 4E, and a minus sign is a hexadecimal 60. When an alternative sign format is specified, the field length (specified on the input specification) must include an additional position for the sign. For example, if a field is 5 digits long and the alternative sign format is specified, a field length of 6 positions must be specified.
4-70
Definitions
4-71
Figure 4-46. Representation of the Number 21544 in each of the Numeric Formats
Note the following about the representations in the figure. v To obtain the numeric value of a positive binary or integer number, unsigned number, add the values of the bits that are on (1), but do not include the sign bit (if present). For an unsigned number, add the values of the bits that are on, including the leftmost bit. v The value 21544 cannot be represented in a 2-byte binary field even though it only uses bits in the low-order two bytes. A 2-byte binary field can only hold up to 4 digits, and 21544 has 5 digits. Figure 4-47 on page 4-73 shows the number -21544 in integer format.
4-72
Table 4-3 lists the RPG-defined formats for date data and their separators. For examples on how to code date fields, see the examples in: v Date Operations on page 6-26 v Moving Date-Time Data on page 6-38 v ADDDUR (Add Duration) on page 6-141 v MOVE (Move) on page 6-226 v EXTRCT (Extract Date/Time/Timestamp) on page 6-203 v SUBDUR (Subtract Duration) on page 6-308 v TEST (Test Date/Time/Timestamp) on page 6-314
Table 4-3. RPG-defined date formats and separators for Date data type Format Name Description Format (Default Separator) Valid Separators Length Example
Definitions
4-73
4-Digit Year Formats *ISO *USA *EUR *JIS International Standards Organization IBM USA Standard IBM European Standard Japanese Industrial Standard Christian Era yyyy-mm-dd mm/dd/yyyy dd.mm.yyyy yyyy-mm-dd / . 10 10 10 10 1996-01-15 01/15/1996 15.01.1996 1996-01-15
Table 4-4 lists the *LOVAL, *HIVAL, and default values for all the RPG-defined date formats.
Table 4-4. Date Values Format name Description *LOVAL *HIVAL Default Value
2-Digit Year Formats *MDY *DMY *YMD *JUL Month/Day/Year Day/Month/Year Year/Month/Day Julian 01/01/40 01/01/40 40/01/01 40/001 12/31/39 31/12/39 39/12/31 39/365 01/01/40 01/01/40 40/01/01 40/001
4-Digit Year Formats *ISO *USA *EUR *JIS International Standards Organization 0001-01-01 IBM USA Standard IBM European Standard Japanese Industrial Standard Christian Era 01/01/0001 01.01.0001 0001-01-01 9999-12-31 12/31/9999 31.12.9999 9999-12-31 0001-01-01 01/01/0001 01.01.0001 0001-01-01
Several formats are also supported for fields used by the MOVE, MOVEL, and TEST operations only. This support is provided for compatibility with externally defined values that are already in a 3-digit year format and the 4-digit year *LONGJUL format. It also applies to the 2-digit year formats when *JOBRUN is specified. *JOBRUN should be used when the field which it is describing is known to have the attributes from the job. For instance, a 12-digit numeric result of a TIME operation will be in the job date format. Table 4-5 lists the valid externally defined date formats that can be used in Factor 1 of a MOVE, MOVEL, and TEST operation.
Table 4-5. Externally defined date formats and separators Format Name Description Format (Default Separator) Valid Separators Length Example
2-Digit Year Formats *JOBRUN1 Determined at runtime from the DATFMT, or DATSEP job values. 3-Digit Year Formats2
4-74
4-Digit Year Formats *LONGJUL Note: 1. *JOBRUN is valid only for character or numeric dates with a 2-digit year since the run-time job attribute for DATFMT can only be *MDY, *YMD, *DMY or *JUL. 2. Valid values for the century character 'c' are: c Years ----------------------0 1900-1999 1 2000-2099 . . . . . . 9 2800-2899 Long Julian yyyy/ddd / - . , '&' 8 2001/115
Separators
When coding a date format on a MOVE, MOVEL or TEST operation, separators are optional for character fields. To indicate that there are no separators, specify the format followed by a zero. For more information on how to code date formats without separators see MOVE (Move) on page 6-226, MOVEL (Move Left) on page 6-245 and TEST (Test Date/Time/Timestamp) on page 6-314.
Initialization
To initialize the Date field to the system date at runtime, specify INZ(*SYS) on the definition specification. To initialize the Date field to the job date at runtime, specify INZ(*JOB) on the definition specification. *SYS or *JOB cannot be used with a field that is exported. The Date field can also be initialized to a literal, named constant or figurative constant. Note: Runtime initialization takes place after static intitialization.
4-75
Hours:Minutes:Seconds International Standards Organization IBM USA Standard. AM and PM can be any mix of upper and lower case. IBM European Standard Japanese Industrial Standard Christian Era
8 8 8 8 8
Table 4-7 lists the *LOVAL, *HIVAL, and default values for all the time formats.
Table 4-7. Time Values RPG Format Name *HMS *ISO *USA *EUR *JIS Description Hours:Minutes:Seconds International Standards Organization IBM USA Standard. AM and PM can be any mix of upper and lower case. IBM European Standard Japanese Industrial Standard Christian Era *LOVAL 00:00:00 00.00.00 00:00 AM 00.00.00 00:00:00 *HIVAL 24:00:00 24.00.00 12:00 AM 24.00.00 24:00:00 Default Value 00:00:00 00.00.00 00:00 AM 00.00.00 00:00:00
Separators
When coding a time format on a MOVE, MOVEL or TEST operation, separators are optional for character fields. To indicate that there are no separators, specify the format followed by a zero. For more information on how to code time formats without separators see MOVE (Move) on page 6-226.
Initialization
To initialize the Time field to the system time at runtime, specify INZ(*SYS) on the definition specification. *SYS cannot be used with a field that is exported. The Time field can also be initialized at runtime to a literal, named constant or figurative constant. Note: Runtime initialization takes place after static intitialization.
4-76
*JOBRUN
A special value of *JOBRUN can be used in Factor 1 of a MOVE, MOVEL or TEST operation. This indicates that the separator of the field being described is based on the run-time job attributes, TIMSEP.
Microseconds (.mmmmmm) are optional for timestamp literals and if not provided will be padded on the right with zeros. Leading zeros are required for all timestamp data. The default initialization value for a timestamp is midnight of January 1, 0001 (0001-01-0100.00.00.000000). The *HIVAL value for a timestamp is 9999-12-31-24.00.00.000000. The *LOVAL value for timestamp is 0001-01-01-00.00.00.000000. For examples on how to code timestamp fields, see the examples in v Date Operations on page 6-26 v Moving Date-Time Data on page 6-38 v ADDDUR (Add Duration) on page 6-141 v MOVE (Move) on page 6-226 v SUBDUR (Subtract Duration) on page 6-308
Separators
When coding the timestamp format on a MOVE, MOVEL or TEST operation, separators are optional for character fields. To indicate that there are no separators, specify *ISO0. For an example of how *ISO is used without separators see TEST (Test Date/Time/Timestamp) on page 6-314.
Initialization
To initialize the Timestamp field to the system date at runtime, specify INZ(*SYS) on the definition specification. *SYS cannot be used with a field that is exported. The Timestamp field can also be initialized at runtime to a literal, named constant or figurative constant. Note: Runtime initialization takes place after static intitialization.
In a fixed-form definition, you specify the object data type as follows. In position 40, you specify data type O. In the keyword section, you specify the CLASS keyword to indicate the class of the object.
Definitions
4-77
| | | | | |
* Variable MyString is a Java String object. D MyString S O CLASS(*JAVA D :java.lang.String) D bdcreate PR O EXTPROC(*JAVA D :java.math.BigDecimal D :*CONSTRUCTOR)
| For both the OBJECT keyword and the CLASS keyword, you specify *JAVA for the first parameter, and | the class name for the second parameter. | | | | If the object is the return type of a Java constructor, the class of the returned object is the same as the class of the method so you do not specify the parameters of the OBJECT keyword in a free-form definition, or the CLASS keyword in a fixed-form definition. Instead, you specify the EXTPROC keyword with environment *JAVA, the class name, and procedure name *CONSTRUCTOR. An object cannot be based. It also cannot be a subfield of a data structure. If an object is an array or table, it must be loaded at runtime. Pre-run and compile-time arrays and tables of type Object are not allowed. Every object is initialized to *NULL, which means that the object is not associated with an instance of its class. To change the contents of an object, you must use method calls. You cannot directly access the storage used by the object. Classes are resolved at runtime. The compiler does not check that a class exists or that it is compatible with other objects.
v Equality or inequality with *NULL. An object is equal to *NULL if it is not associated with a particular instance of its class. Free-Form Call Parameter You can code an object as a parameter in a call operation if the parameter in the prototype is an object. Note:
4-78
S S S
O O O
* Since all Java classes are subclasses of class java.lang.Object, * any object can be assigned to a variable of this class. * The following two assignments are valid. C EVAL Obj = Str C EVAL Obj = Num * However, it would probably not be valid to assign Str to Num. Figure 4-48. Object Data Type Example
MY_FIELD is now located in storage starting at the 'G', so its value is 'GHIJK'. If the pointer is moved to
PTR1-------------------. | V ------------------------------------------------------------| A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | -------------------------------------------------------------
point to the 'J', the value of MY_FIELD becomes 'JKLMN': If MY_FIELD is now changed by an EVAL statement to 'HELLO', the storage starting at the 'J' would
PTR1-------------------. | V ------------------------------------------------------------| A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | -------------------------------------------------------------
change:
Definitions
4-79
Use the BASED keyword on the definition specification (see BASED(basing_pointer_name) on page 5-95) to define a basing pointer for a field. Basing pointers have the same scope as the based field. The length of the basing pointer field must be 16 bytes long and must be aligned on a 16 byte boundary. This requirement for boundary alignment can cause a pointer subfield of a data structure not to follow the preceding field directly, and can cause multiple occurrence data structures to have non-contiguous occurrences. For more information on the alignment of subfields, see Aligning Data Structure Subfields on page 4-14. The default initialization value for basing pointers is *NULL. Note: When coding basing pointers, you must be sure that you set the pointer to storage that is large enough and of the correct type for the based field. Figure 4-53 on page 4-85 shows some examples of how not to code basing pointers. Note: You can add or subtract an offset from a pointer in an expression, for example EVAL ptr = ptr + offset. When doing pointer arithmetic be aware that it is your responsibility to ensure that you are still pointing within the storage of the item you are pointing to. In most cases no exception will be issued if you point before or after the item. When subtracting two pointers to determine the offset between them, the pointers must be pointing to the same space, or the same type of storage. For example, you can subtract two pointers in static storage, or two pointers in automatic storage, or two pointers within the same user space. Note: When a data structure contains a pointer, and the data structure is copied to a character field, or to another data structure that does not have a pointer subfield defined, the pointer information may be lost in the copied value. The actual 16-byte value of the pointer will be copied, but there is extra information in the system that indicates that the 16-byte area contains a pointer; that extra information may not be set in the copied value. If the copied value is copied back to the original value, the pointer may be lost in the original value. Passing a data structure containing pointers as a prototyped parameter by read-only reference (CONST keyword) or by value (VALUE keyword) may lose pointer information in the received parameter, if the parameter is prototyped as a character value rather than using the LIKEDS keyword. A similar problem can occur when returning a data structure containing a pointer.
4-80
Examples
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++ * * Define a based data structure, array and field. * If PTR1 is not defined, it will be implicitly defined * by the compiler. * * Note that before these based fields or structures can be used, * the basing pointer must be set to point to the correct storage * location. * D DSbased DS BASED(PTR1) D Field1 1 16A D Field2 2 D D ARRAY S 20A DIM(12) BASED(PRT2) D D Temp_fld S * BASED(PRT3) D D PTR2 S * INZ D PTR3 S * INZ(*NULL) Figure 4-49. Defining based structures and fields
The following shows how you can add and subtract offsets from pointers and also determine the difference in offsets between two pointers.
Definitions
4-81
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+...8 DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++ D.....................................Keywords+++++++++++++++++++++++++++++ * D P1 s * D P2 s * CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq.... CL0N01++++++++++++++Opcode(E)+Extended Factor 2++++++++++++++++++++++++++++ * * Allocate 20 bytes of storage for pointer P1. C ALLOC 20 P1 * Initialize the storage to abcdefghij C EVAL %STR(P1:20) = abcdefghij * Set P2 to point to the 9th byte of this storage. C EVAL P2 = P1 + 8 * Show that P2 is pointing at i. %STR returns the data that * the pointer is pointing to up to but not incuding the first * null-terminator x00 that it finds, but it only searches for * the given length, which is 1 in this case. C EVAL Result = %STR(P2:1) C DSPLY Result 1 * Set P2 to point to the previous byte C EVAL P2 = P2 - 1 * Show that P2 is pointing at h C EVAL Result = %STR(P2:1) C DSPLY Result * Find out how far P1 and P2 are apart. (7 bytes) C EVAL Diff = P2 - P1 C DSPLY Diff 5 0 * Free P1s storage C DEALLOC P1 C RETURN Figure 4-50. Pointer Arithmetic
Figure 4-51 shows how to obtain the number of days in Julian format, if the Julian date is required.
*..1....+....2....+....3....+....4....+....5....+....6....+....7....+.... HKeywords++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ H DATFMT(*JUL) DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++ D.....................................Keywords+++++++++++++++++++++++++++++ * D JulDate S D INZ(D95/177) D DATFMT(*JUL) D JulDS DS BASED(JulPTR) D Jul_yy 2 0 D Jul_sep 1 D Jul_ddd 3 0 D JulDay S 3 0 CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq.... CL0N01++++++++++++++Opcode(E)+Extended Factor 2++++++++++++++++++++++++++++ * * Set the basing pointer for the structure overlaying the * Julian date. C EVAL JulPTR = %ADDR(JulDate) * Extract the day portion of the Julian date C EVAL JulDay = Jul_ddd Figure 4-51. Obtaining a Julian Date
Figure 4-52 on page 4-83 illustrates the use of pointers, based structures and system APIs. This program does the following:
4-82
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++ D.....................................Keywords+++++++++++++++++++++++++++++ * D SPACENAME DS D 10 INZ(LISTSPACE) D 10 INZ(QTEMP) D ATTRIBUTE S 10 INZ(LSTMBR) D INIT_SIZE S 9B 0 INZ(9999999) D AUTHORITY S 10 INZ(*CHANGE) D TEXT S 50 INZ(File member space) D SPACE DS BASED(PTR) D SP1 32767 * * ARR is used with OFFSET to access the beginning of the * member information in SP1 * D ARR 1 OVERLAY(SP1) DIM(32767) * * OFFSET is pointing to start of the member information in SP1 * D OFFSET 9B 0 OVERLAY(SP1:125) * * Size has number of member names retrieved * D SIZE 9B 0 OVERLAY(SP1:133) D MBRPTR S * D MBRARR S 10 BASED(MBRPTR) DIM(32767) D PTR S * D FILE_LIB S 20 D FILE S 10 D LIB S 10 D WHICHMBR S 10 INZ(*ALL ) D OVERRIDE S 1 INZ(1) D FIRST_LAST S 50 INZ( MEMBERS, + D FIRST = , + D LAST = ) D IGNERR DS D 9B 0 INZ(15) D 9B 0 D 7A Figure 4-52. Example of using pointers and based structures with an API
Definitions
4-83
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq.... CL0N01++++++++++++++Opcode(E)+Extended Factor 2++++++++++++++++++++++++++++ * * Receive file and library you want to process * C *ENTRY PLIST C FILE PARM FILEPARM 10 C LIB PARM LIBPARM 10 * * Delete the user space if it exists * C CALL QUSDLTUS 10 C PARM SPACENAME C PARM IGNERR * * Create the user space * C CALL QUSCRTUS C PARM SPACENAME C PARM ATTRIBUTE C PARM INIT_SIZE C PARM INIT_VALUE 1 C PARM AUTHORITY C PARM TEXT * * Call the API to list the members in the requested file * C CALL QUSLMBR C PARM SPACENAME C PARM MBRL0100 MBR_LIST 8 C PARM FILE_LIB C PARM WHICHMBR C PARM OVERRIDE * * Get a pointer to the user-space * C CALL QUSPTRUS C PARM SPACENAME C PARM PTR * * Set the basing pointer for the member array * MBRARR now overlays ARR starting at the beginning of * the member information. * C EVAL MBRPTR = %ADDR(ARR(OFFSET)) C MOVE SIZE CHARSIZE 3 C EVAL %SUBST(FIRST_LAST:1:3) = CHARSIZE C EVAL %SUBST(FIRST_LAST:23:10) = MBRARR(1) C EVAL %SUBST(FIRST_LAST:41:10) = MBRARR(SIZE) C FIRST_LAST DSPLY C EVAL *INLR = 1
When coding basing pointers, make sure that the pointer is set to storage that is large enough and of the correct type for the based field. Figure 4-53 on page 4-85 shows some examples of how not to code basing pointers.
4-84
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++ D.....................................Keywords+++++++++++++++++++++++++++++ * D chr10 S 10a based(ptr1) D char100 S 100a based(ptr1) D p1 S 5p 0 based(ptr1) CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq.... CL0N01++++++++++++++Opcode(E)+Extended Factor 2++++++++++++++++++++++++++++ * * * Set ptr1 to the address of p1, a numeric field * Set chr10 (which is based on ptr1) to abc * The data written to p1 will be unreliable because of the data * type incompatibility. * C EVAL ptr1 = %addr(p1) C EVAL chr10 = abc * * Set ptr1 to the address of chr10, a 10-byte field. * Set chr100, a 100-byte field, all to x * 10 bytes are written to chr10, and 90 bytes are written in other * storage, the location being unknown. * C EVAL ptr1 = %addr(chr10) C EVAL chr100 = *allx Figure 4-53. How Not to Code Basing Pointers
Definitions
4-85
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++ * * Define a basing pointer field and initialize to the address of the * data structure My_Struct. * D My_Struct DS D My_array 10 DIM(50) D D Ptr1 S 16* INZ(%ADDR(My_Struct)) * * Or equivalently, defaults to length 16 if length not defined * D Ptr1 S * INZ(%ADDR(My_Struct)) * * Define a procedure pointer field and initialize to NULL * D Ptr1 S 16* PROCPTR INZ(*NULL) * * Define a procedure pointer field and initialize to the address * of the procedure My_Proc. * D Ptr1 S 16* PROCPTR INZ(%PADDR(My_Proc)) * * Define pointers in a multiple occurrence data structure and map out * the storage. * DDataS DS OCCURS(2) D ptr1 * D ptr2 * D Switch 1A
* * Storage map would be: * * DataS * * * ptr1 * * ptr2 * Switch * * Pad * * ptr1 * * ptr2 * * Switch * * *
Figure 4-54. Defining pointers
4-86
4-87
4-88
*..1....+....2....+....3....+....4....+....5....+....6....+....7....+.... * * * Specify the ALWNULL(*USRCTL) keyword on a control * specification or compile the ILE RPG program with ALWNULL(*USRCTL) * on the command. * HKeywords++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ *H ALWNULL(*USRCTL) * * DISKFILE contains a record REC which has 2 fields: FLD1 and FLD2 * Both FLD1 and FLD2 are null-capable. * FDISKFILE UF A E DISK * * Read the first record. * Update the record with new values for any fields which are not * null. C READ REC 10 C IF NOT %NULLIND(Fld1) C MOVE FLD1 Fld1 C ENDIF C IF NOT %NULLIND(Fld2) C MOVE FLD2 Fld2 C ENDIF C UPDATE REC * * Read another record. * Update the record so that all fields are null. * There is no need to set the values of the fields because they * would be ignored. C READ REC 10 C EVAL %NULLIND(Fld1) = *ON C EVAL %NULLIND(Fld2) = *ON C UPDATE REC * * Write a new record where Fld 1 is null and Fld 2 is not null. * C EVAL %NULLIND(Fld1) = *ON C EVAL %NULLIND(Fld2) = *OFF C EVAL Fld2 = New value C WRITE REC Figure 4-55. Input and output of null-capable fields
Keyed Operations: If you have a null-capable key field, you can search for records containing null values by specifying an indicator in factor 2 of the KFLD operation and setting that indicator on before the keyed input operation. If you do not want a null key to be selected, you set the indicator off. When a record format with null-capable key fields is used on a CHAIN, SETLL, READE, or READPE operation, and a %KDS data structure is used to specify the keys, then the null-key-byte-map information will be taken from the null attributes of the subfields in the data structure specified as the argument of %KDS. When a record format with null-capable key fields is used on a CHAIN, SETLL, READE, or READPE operation, and a list of keyfields is used, then the null-key-byte-map information will be taken from the null attributes of the specified keys. Figure 4-56 on page 4-90 and Figure 4-57 on page 4-91 illustrate how keyed operations are used to position and retrieve records with null keys.
Definitions
4-89
4-90
* Using the same file as the previous example, define two * key lists, one containing three keys and one containing * two keys. CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq. C Full_Kl KLIST C KFLD Key1 C KFLD *IN02 Key2 C KFLD *IN03 Key3 C Partial_Kl KLIST C KFLD Key1 C KFLD *IN05 Key2 * * *IN02 is ON and *IN03 is OFF for the SETLL operation below. * File1 will be positioned at the next record that has a key * that is equal to or greater than AA??CC (where ?? is used * in this example to indicate NULL) * * Because *IN02 is ON, the actual content in the search argument * for Key2 will be ignored. * * If a record exists in File1 with AA in Key1, a null Key2, and * CC in Key3, indicator 90 (the Eq indicator) will be set ON. * C MOVE AA Key1 C MOVE CC Key3 C EVAL *IN02 = 1 C EVAL *IN03 = 0 C Full_Kl SETLL Rec1 90 * * * * * * * * C C C C C * * * * * * * * * * * * * * C C C The CHAIN operation below will retrieve a record with JJ in Key1, KK in Key2, and a null Key3. Again, because *IN03 is ON, even if the programmer had moved some value (say XX) into the search argument for Key3, XX will not be used. This means if File1 actually has a record with a key JJKKXX, that record will not be retrieved. MOVE MOVE EVAL EVAL CHAIN JJ KK *IN02 = 0 *IN03 = 1 Rec1 Key1 Key2 80
Full_Kl
The CHAIN operation below uses a partial key as the search argument. It will retrieve a record with NN in Key1, a null key2, and any value including a null value in Key3. In the database, the NULL value occupies the highest position in the collating sequence. Assume the keys in File1 are in ascending sequence. If File1 has a record with NN??xx as key (where ?? means NULL and xx means any value other than NULL), that record will be retrieved. If such a record does not exist in File1, but File1 has a record with NN???? as key, the NN???? record will be retrieved. The null flags for Key2 and Key3 will be set ON as a result. MOVE SETON CHAIN NN Rec1 Key1 05 70
Partial_Kl
Definitions
4-91
ALWNULL(*NO)
When an externally described file contains null-capable fields and the ALWNULL(*NO) keyword is specified on a control specification, the following conditions apply: v A record containing null values retrieved from a file will cause a data mapping error and an error message will be issued. v Data in the record is not accessible and none of the fields in the record can be updated with the values from the input record containing null values. v With this option, you cannot place null values in null-capable fields for updating or adding a record. If you want to place null values in null-capable fields, use the ALWNULL(*USRCTL) option.
This chapter applies only to non-float numeric fields. To output float fields in the external display representation, specify blank in position 52 of the output specification. To obtain the external display representation of a float value in calculations, use the %EDITFLT built-in function. A field can be edited by edit codes, or edit words. You can print fields in edited format using output specifications or you can obtain the edited value of the field in calulation specifications using the built-in functions %EDITC (edit code) and %EDITW (edit word).
4-92
004765K
004765K
47652-
The unedited alphanumeric field and the unedited positive numeric field are easy to read when printed, but the unedited negative numeric field is confusing because it contains a K, which is not numeric. The K is a combination of the digit 2 and the negative sign for the field. They are combined so that one of the positions of the field does not have to be set aside for the sign. The combination is convenient for storing the field in the computer, but it makes the output hard to read. Therefore, to improve the readability of the printed output, numeric fields should be edited before they are printed.
Edit Codes
Edit codes provide a means of editing numeric fields according to a predefined pattern. They are divided into three categories: simple (X, Y, Z), combination (1 through 4, A through D, J through Q), and user-defined (5 through 9). In output specifications, you enter the edit code in position 44 of the field to be edited. In calculation specifications, you specify the edit code as the second parameter of the %EDITC built-in function.
Definitions
4-93
Edit Codes
the zero balance is to be suppressed, the decimal separator is included only if the field is not zero. If a zero balance is to be suppressed, a zero field is output as blanks. When a zero balance is not to be suppressed and the field is equal to zero, either of the following is output: v A decimal separator followed by n zeros, where n is the number of decimal places in the field v A zero in the units position of a field if no decimal places are specified. You can use a floating currency symbol or asterisk protection with any of the 12 combination edit codes. The floating currency symbol appears to the left of the first significant digit. The floating currency symbol does not print on a zero balance when an edit code is used that suppresses the zero balance. The currency symbol does not appear on a zero balance when an edit code is used that suppresses the zero balance. The currency symbol for the program is a dollar sign ($) unless a currency symbol is specified with the CURSYM keyword on the control specification. To specify a floating currency symbol in output specifications, code the currency symbol in positions 53-55 as well as an edit code in position 44 for the field to be edited. For built-in function %EDITC, you specify a floating currency symbol in the third parameter. To use the currency symbol for the program, specify *CURSYM. To use another currency symbol, specify a character constant of length 1. Asterisk protection causes an asterisk to replace each zero suppressed. A complete field of asterisks replaces the fiield on a zero balance source field. To specify asterisk protection in output specifications, code an asterisk constant in positions 53 through 55 of the output specifications, along with an edit code. To specify asterisk protection using the built-in function %EDITC, specify *ASTFILL as the third parameter. Asterisk fill and the floating currency symbol cannot be used with the simple (X, Y, Z) or with the user-defined (5 through 9) edit codes. A currency symbol can appear before the asterisk fill (fixed currency symbol). You can do this in output specifications with the following coding: 1. Place a currency symbol constant in position 53 of the first output specification. The end position specified in positions 47-51 should be one space before the beginning of the edited field. 2. In the second output specification, place the edit field in positions 30-43, an edit code in position 44, end position of the edit field in positions 47-51, and '*' in positions 53-55. You can do this using the %EDITC built-in function by concatenating the currency symbol to the %EDITC result.
C EVAL X = $ + %EDITC(N: A : *ASTFILL)
In output specifications, when an edit code is used to print an entire array, two blanks precede each element of the array (except the first element). Note: You cannot edit an array using the %EDITC built-in function. Table 4-8 on page 4-95 summarizes the functions of the combination edit codes. The codes edit the field in the format listed on the left. A negative field can be punctuated with no sign, CR, a minus sign (-), or a floating minus sign as shown on the top of the figure.
4-94
Edit Codes
Table 4-8. Combination Edit Codes Negative Balance Indicator Prints with Grouping Separator Yes Yes No No Prints Zero Balance Yes No Yes No No Sign CR Floating Minus
1 2 3 4
A B C D
J K L M
N 0 P Q
Editing Considerations
Remember the following when you specify any of the edit codes: v Edit fields of a non-printer file with caution. If you do edit fields of a non-printer file, be aware of the contents of the edited fields and the effects of any operations you do on them. For example, if you use the file as input, the fields written out with editing must be considered character fields, not numeric fields. v Consideration should be given to data added by the edit operation. The amount of punctuation added increases the overall length of the edited value. If these added characters are not considered when editing in output specifications, the output fields may overlap. v The end position specified for output is the end position of the edited field. For example, if any of the edit codes J through M are specified, the end position is the position of the minus sign (or blank if the field is positive). v The compiler assigns a character position for the sign even for unsigned numeric fields.
Definitions
4-95
Edit Codes
Table 4-9. Edit Codes DECEDIT Keyword Parameter Edit Code 1 2 3 4 5-9 A B C D J K L M N O P Q X2 Y3 Z
4 1
Commas
'.'
','
'0,'
'0.'
Yes Yes
Yes Yes
CR CR CR CR - (minus) - (minus) - (minus) - (minus) - (floating minus) - (floating minus) - (floating minus) - (floating minus)
.00 or 0 Blanks .00 or 0 Blanks .00 or 0 Blanks .00 or 0 Blanks .00 or 0 Blanks .00 or 0 Blanks
,00 or 0 Blanks ,00 or 0 Blanks ,00 or 0 Blanks ,00 or 0 Blanks ,00 or 0 Blanks ,00 or 0 Blanks
0,00 or 0 Blanks 0,00 or 0 Blanks 0,00 or 0 Blanks 0,00 or 0 Blanks 0,00 or 0 Blanks 0,00 or 0 Blanks
0.00 or 0 Blanks 0.00 or 0 Blanks 0.00 or 0 Blanks 0.00 or 0 Blanks 0.00 or 0 Blanks 0.00 or 0 Blanks
Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes
Yes Yes
Yes Yes
Yes Yes
Note: 1. These are the user-defined edit codes. 2. The X edit code ensures a hexadecimal F sign for positive values. Because the system does this for you, normally you do not have to specify this code. 3. The Y edit code suppresses the leftmost zeros of date fields, up to but not including the digit preceding the first separator. The Y edit code also inserts slashes (/) between the month, day, and year according to the following pattern: nn/n nn/nn nn/nn/n nn/nn/nn nnn/nn/nn nn/nn/nnnn nnn/nn/nnnn nnnn/nn/nn nnnnn/nn/nn 4. The Z edit code removes the sign (plus or minus) from a numeric field and suppresses leading zeros.
4-96
Edit Codes
Table 4-10. Examples of Edit Code Usage Positive NumberTwo Decimal Positions 1234567 12,345.67 12,345.67 12345.67 12345.67
1
.00
12,345.67 12.345.67 12345.67 12345.67 12,345.67 12,345,67 12345.67 12345.67 12,345.67 12,345,67 12345.67 12345.67 1234567
1,234,567 1,234,567 1234567 1234567 1,234,567 1,234,567 1234567 1234567 1,234,567 1,234,567 1234567 1234567 1234567
.00
.00
.00
.00
.00
.00
000000 0/00/00
000000 0/00/00
0/01/20 120
Z4 Note:
1. These edit codes are user-defined. 2. The X edit code ensures a hex F sign for positive values. Because the system does this for you, normally you do not have to specify this code. 3. The Y edit code suppresses the leftmost zeros of date fields, up to but not including the digit preceding the first separator. The Y edit code also inserts slashes (/) between the month, day, and year according to the following pattern: nn/n nn/nn nn/nn/n nn/nn/nn nnn/nn/nn nn/nn/nnnn Format used nnn/nn/nnnn Format used nnnn/nn/nn Format used nnnnn/nn/nn Format used
M, D M, D Y in Y in
in position 19 in position 19 19 19
4. The Z edit code removes the sign (plus or minus) from a numeric field and suppresses leading zeros of a numeric field. 5. The represents a blank. This may occur if a negative zero does not correspond to a printable character.
Definitions
4-97
Edit Codes
Table 4-11. Effects of Edit Codes on End Position Negative Number, 2 Decimal Positions. End Position Specified as 10. Output Print Positions Edit Code Unedited 1 2 3 4 5-9 A B C D J K L M N O P Q X Y Z Note: 1. K represents a negative 2. 2. These are user-defined edit codes. 0
2
6 0
7 0 4 4 4 4
8 4 . . . .
9 1 1 1 1 1
10 K
1
11
2 2 2 2
4 4 4 4
. . . . 4 4 4 4 0 /
1 1 1 1 . . . . 4 4 4 4 0 4
2 2 2 2 1 1 1 1 . . . . 4 1 4
C C C C 2 2 2 2 1 1 1 1 1 / 1
R R R R 2 2 2 2 K1 2 2
Edit Words
If you have editing requirements that cannot be met by using the edit codes described above, you can use an edit word. An edit word is a character literal or a named constant specified in positions 53 - 80 of the output specification. It describes the editing pattern for an numeric and allows you to directly specify: v Blank spaces v Commas and decimal points, and their position v Suppression of unwanted zeros v v v v Leading asterisks The currency symbol, and its position Addition of constant characters Output of the negative sign, or CR, as a negative indicator.
The edit word is used as a template, which the system applies to the source data to produce the output.
4-98
Edit Words
The edit word may be specified directly on an output specification or may be specified as a named constant with a named constant name appearing in the edit word field of the output specification. You can obtain the edited value of the field in calulation specifications using the built-in function %EDITW (edit word). Edit words are limited to 115 characters.
To edit using an edit word in calculation specifications, use built-in function %EDITW, specifying the value to be edited as the first parameter, and the edit word as the second parameter.
The body is the space for the digits transferred from the source data field to the edited result. The body begins at the leftmost position of the edit word. The number of blanks (plus one zero or an asterisk) in the edit word body must be equal to or greater than the number of digits of the source data field to be edited. The body ends with the rightmost character that can be replaced by a digit. The status defines a space to allow for a negative indicator, either the two letters CR or a minus sign (-). The negative indicator specified is output only if the source data is negative. All characters in the edit word between the last replaceable character (blank, zero suppression character) and the negative indicator are also output with the negative indicator only if the source data is negative; if the source data is positive, these status positions are replaced by blanks. Edit words without the CR or - indicators have no status positions. The status must be entered after the last blank in the edit word. If more than one CR follows the last blank, only the first CR is treated as a status; the remaining CRs are treated as constants. For the minus sign to be considered as a status, it must be the last character in the edit word.
Definitions
4-99
Edit Words
The expansion is a series of ampersands and constant characters entered after the status. Ampersands are replaced by blank spaces in the output; constants are output as is. If status is not specified, the expansion follows the body. Forming the Body of an Edit Word: The following characters have special meanings when used in the body of an edit word: Blank: Blank is replaced with the character from the corresponding position of the value to be edited. A blank position is referred to as a digit position. Decimals and Commas: Decimals and commas are in the same relative position in the edited output field as they are in the edit word unless they appear to the left of the first significant digit in the edit word. In that case, they are blanked out or replaced by an asterisk. In the following examples below, all the leading zeros will be suppressed (default) and the decimal point will not appear unless there is a significant digit to its left.
Edit Word ' ' ' ' . ' Source Data 0000072 000000012 000000123 Appears in Edited Result as: 72 12 1.23
. '
Zeros: The first zero in the body of the edit word is interpreted as an end-zero-suppression character. This zero is placed where zero suppression is to end. Subsequent zeros put into the edit word are treated as constants (see Constants below). Any leading zeros in the source data are suppressed up to and including the position of the end-zero-suppression character. Significant digits that would appear in the end-zero-suppression character position, or to the left of it, are output.
Edit Word ' ' ' 0 0 0 ' ' ' Source Data 00000004 012345 012345678 Appears in Edited Result as: 000004 012345 12345678
If the leading zeros include, or extend to the right of, the end-zero-suppression character position, that position is replaced with a blank. This means that if you wish the same number of leading zeros to appear in the output as exist in the source data, the edit word body must be wider than the source data.
Edit Word '0 '0 ' ' Source Data 0156 0156 Appears in Edited Result as: 156 0156
Constants (including commas and decimal point) that are placed to the right of the end-zero-suppression character are output, even if there is no source data. Constants to the left of the end-zero-suppression character are only output if the source data has significant digits that would be placed to the left of these constants.
Edit Word ' ' 0. 0. ' ' Source Data 000000001 000000000 Appears in Edited Result as: .01 .00
4-100
Edit Words
Edit Word ' ' , 0 . ' Source Data 00000012 00000123 00000123 Appears in Edited Result as: 0.12 1.23 0,001.23
, 0 . ' . '
' 0 ,
Asterisk: The first asterisk in the body of an edit word also ends zero suppression. Subsequent asterisks put into the edit word are treated as constants (see Constants below). Any zeros in the edit word following this asterisk are also treated as constants. There can be only one end-zero-suppression character in an edit word, and that character is the first asterisk or the first zero in the edit word. If an asterisk is used as an end-zero-suppression character, all leading zeros that are suppressed are replaced with asterisks in the output. Otherwise, the asterisk suppresses leading zeros in the same way as described above for Zeros.
Edit Word '* ' ' . * . * . ' ' **' Source Data 000000123 000000000 000056342 Appears in Edited Result as: * 1.23
******0.00 ****563.42**
Note that leading zeros appearing after the asterisk position are output as leading zeros. Only the suppressed leading zeros, including the one in the asterisk position, are replaced by asterisks. Currency Symbol: A currency symbol followed directly by a first zero in the edit word (end-zero-suppression character) is said to float. All leading zeros are suppressed in the output and the currency symbol appears in the output immediately to the left of the most significant digit.
Edit Word ' ' , , , $0. , $0. ' ' Source Data 000000012 000123456 Appears in Edited Result as: $.12 $1,234.56
If the currency symbol is put into the first position of the edit word, then it will always appear in that position in the output. This is called a fixed currency symbol.
Edit Word '$ , '$ '$ , , , 0. ,0 0. ,* . ' ' ' Source Data 000123456 000000000 000123456 Appears in Edited Result as: $ $ 1,234.56 00.00
$****1,234.56
A currency symbol anywhere else in the edit word and not immediately followed by a zero end-suppression-character is treated as a constant (see Constants below). Ampersand: Causes a blank in the edited field. The example below might be used to edit a telephone number. Note that the zero in the first position is required to print the constant AREA.
Edit Word '0AREA& &NO.& ' Source Data 4165551212 Appears in Edited Result as: AREA 416 NO. 555-1212
Definitions
4-101
Edit Words
Constants: All other characters entered into the body of the edit word are treated as constants. If the source data is such that the output places significant digits or leading zeros to the left of any constant, then that constant appears in the output. Otherwise, the constant is suppressed in the output. Commas and the decimal point follow the same rules as for constants. Notice in the examples below, that the presence of the end-zero-suppression character as well as the number of significant digits in the source data, influence the output of constants. The following edit words could be used to print cheques. Note that the second asterisk is treated as a constant, and that, in the third example, the constants preceding the first significant digit are not output.
Edit Word '$ '$ '$ **DOLLARS& **DOLLARS& &DOLLARS& &CTS' &CTS' &CTS' Source Data 000012345 000000006 000000006 Appears in Edited Result as: $****123*DOLLARS 45 CTS $********DOLLARS 06 CTS $ 6 CTS
Note that any zeros or asterisks following the first occurrence of an edit word are treated as constants. The same is true for - and CR:
Edit Word ' ' 0. *. 000' 000' Source Data 01234 01234 Appears in Edited Result as: 12.34000 *12.34000
Forming the Status of an Edit Word: The following characters have special meanings when used in the status of an edit word: Ampersand: Causes a blank in the edited output field. An ampersand cannot be placed in the edited output field. CR or minus symbol: If the sign in the edited output is plus (+), these positions are blanked out. If the sign in the edited output field is minus (-), these positions remain undisturbed. The following example adds a negative value indication. The minus sign will print only when the value in the field is negative. A CR symbol fills the same function as a minus sign.
Edit Word ' ' . . -' -' Source Data 000000123000000123 Appears in Edited Result as: 1.231.23
Constants between the last replaceable character and the - or CR symbol will print only if the field is negative; otherwise, blanks will appear in these positions. Note the use of ampersands to represent blanks:
Edit Word ' , , 0. &30&DAY&CR' Source Data 000000123Appears in Edited Result as: 1.23 30 DAY CR
4-102
Edit Words
Edit Word ' , , 0. &30&DAY&CR' Source Data 000000123 Appears in Edited Result as: 1.23
Formatting the Expansion of an Edit Word: The characters in the expansion portion of an edit word are always used. The expansion cannot contain blanks. If a blank is required in the edited result, specify an ampersand in the body of the edit word. Constants may be added to appear with any value of the number:
Edit Word ' , ' , 0. &CR&NET' 0. &CR&NET' Source Data 000123000123 Appears in Edited Result as: 1.23 CR NET 1.23 NET
Note that the CR in the middle of a word may be detected as a negative field value indication. If a word such as SECRET is required, use the coding in the example below.
Edit Word ' ' ' 0. 0. 0. &SECRET' &SECRET' &CR&&SECRET' Source Data 1234512345 12345 Appears in Edited Result as: 123.45 SECRET 123.45 123.45 ET SECRET
Definitions
4-103
4-104
Specifications
Coding statements in RPG IV This section describes the RPG IV specifications. First, information common to several specifications, such as keyword syntax and continuation rules is described. Next, the specifications are described in the order in which they must be entered in your program. Each specification description lists all the fields on the specification and explains all the possible entries.
About Specifications
RPG IV source is coded on a variety of specifications. Each specification has a specific set of functions. This reference contains a detailed description of the individual RPG IV specifications. Each field and its possible entries are described. Operations on page 6-1 describes the operation codes that are coded on the calculation specification, which is described in Calculation Specifications on page 5-166.
Note
The RPG IV source must be entered into the system in the order shown in Table 5-1 on page 5-2. Any of the specification types can be absent, but at least one from the main source section must be present. | File Description and Definition specifications may be intermixed.
5-1
| | | | | | | | | | |
Main Source Section H Control F,D File Description and Definition I Input C Calculation O Output Subprocedure Section (Repeated for each procedure) P Procedure F,D File Description and Definition C Calculation P Procedure Program Data when the ** form is used ** File Translation Records ** Alternate Collating Sequence Records ** Compile-Time Array and Table Data Program Data when the **TYPE form is used (Specified in any order) **CTDATA ARRAY1 Compile-Time Array Data **FTRANS File Translation Records **CTDATA TABLE2 Compile-Time Table Data **ALTSEQ Alternate Collating Sequence Records **CTDATA ARRAY3 Compile-Time Array Data
F D
5-2
Subprocedure Specifications
P Procedure specifications describe the procedure-interface definition of a prototyped program or procedure. Refer to Procedure Specifications on page 5-188 for a description of the entries on this specification. File description specifications define the files used locally in the subprocedure. Refer to File Description Specifications on page 5-37for a description of the entries on this specification. Definition specifications define items used in the prototyped procedure. Procedure-interface definitions, entry parameters, and other local items are defined on this specification. Refer to Definition Specifications on page 5-74 for a description of the entries on this specification. Calculation specifications perform the logic of the prototyped procedure. Refer to Calculation Specifications on page 5-166 for a description of the entries on this specification.
F D
Program Data
Source records with program data follow all source specifications. The first line of the data section must start with **. If desired, you can indicate the type of program data that follows the **, by specifying any of these keywords as required: CTDATA on page 5-98, FTRANS{(*NONE | *SRC)} on page 5-28, or ALTSEQ{(*NONE | *SRC | *EXT)} on page 5-17. By associating the program data with the appropriate keyword, you can place the groups of program data in any order after the source records. The first entry for each input record must begin in position 1. The entire record need not be filled with entries. Array elements associated with unused entries will be initialized with the default value. For more information on entering compile-time array records, see Rules for Array Source Records on page 4-36. For more information on file translation, see File Translation on page 3-116. For more information on alternate collating sequences, see Alternate Collating Sequence on page 4-63. | | | | | | | | | | | | | | | | | | |
Free-Form Statements
A free-form statement is coded in columns 8-80. Columns 6-7 must be blank. In most cases, a free-form statement begins with an operation code, such as CTL-OPT, DCL-F, DCL-DS, READE, or DCL-PROC. In some cases, it is not necessary to specify the operation code. v In a calculation statement, the EVAL operation code and the CALLP operation code omitted as long as the first name in the statement is not the same an operation code supported in free-form calculations. For example, the EVAL operation code is required if the target of the assignment has the name READ. v When defining a subfield, the DCL-SUBF operation code may be omitted as long as the name of the subfield is not the same as an operation code supported in free-form calculations. v When defining a parameter, the DCL-PARM operation code may be omitted as long as the name of the parameter is not the as same an operation code supported in free-form calculations. A free-form statement ends with a semicolon. In general, all text following // on a free-form line is considered to be a comment. However, if // appears within a character literal, it is considered to be part of the literal. In the following example, 1 , 2 , and 4 are comments, but 3 is not a comment because // appears within a literal. When // follows non-comment code on the same line, it is often referred to as an end-of-line comment. The comments at 2 and 4 are end-of-line comments.
Specifications
5-3
Free-Form Statements
| | | | |
// comment 1 DCL-S string // comment 2 CHAR(10); string = abc // not-comment 3 + def; // comment 4
| For a list of operation codes supported in free-form calculations, see Operation Codes on page 6-1. | For more information about each type of free-form statement, see | v Free-Form Control Statement on page 5-14 | v Free-Form File Definition Statement on page 5-38 | v Free-Form Definition Statement on page 5-74 | v Free-Form Calculation Statement on page 5-173 | v Free-Form Procedure Statement on page 5-189 | Conditional Directives Within a Free-Form Statement | You can use the /IF, /ELSEIF, /ELSE, and /ENDIF directives within any free-form statement other than a | free-form calculation statement. | However, the following rules apply: | v If a statement begins after an /IF, /ELSEIF, or /ELSE directive, the final semicolon for the statement must be specified before the next directive. | The following code is not valid. The DSPLY statement begins after the /IF directive, so the semicolon | for the DSPLY statement must appear before the /ELSE directive. | | | | | | | |
/IF DEFINED(TRUE) DSPLY /ELSE print /ENDIF (start);
| v If the /IF for a conditional group begins within a statement, the /ENDIF must be specified before the final semicolon for the statement. | | The following is not valid because the /IF directive is specified after the DCL-S statement begins, and the | /ENDIF directive appears after the final semicolon for the DCL-S statement. | | | | | | |
DCL-S name /IF DEFINED(TRUE) CHAR(10); /ELSE VARCHAR(10); /ENDIF
| Differences between fixed-form and free-form to be aware of | Update-capable files are not automatically delete-capable | | | If you specify U in the File-Type entry for a fixed-form file definition, the file is opened to allow both update and delete operations. You must explicitly specify USAGE(*DELETE) for a free-form file definition, if you want the file to be opened to allow delete operations.
5-4
Free-Form Statements
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Unquoted names for the EXTNAME and EXTFLD keywords The interpretation of an unquoted name is different in fixed form and free form. v In fixed form, an unquoted name is interpreted as the external name. v In free form, an unquoted name is interpreted as a named constant. Tip: If you have a mixture of fixed-form and free-form code, consider changing the EXTNAME and EXTFLD keywords in fixed-form to use a literal rather than a name. For example change EXTNAME(myfile) to EXTNAME('MYFILE') and change EXTFLD(myextfld) to EXTFLD('MYEXTFLD'). Unquoted names for the DTAARA keyword The interpretation of an unquoted name in the first operand is different in fixed form and free form. v In fixed form, if the first operand of DTAARA is a name, such as DTAARA(myDtaaara), the operand is interpreted as the name of the data area on the system,*LIBL/MYDTAARA. v In free form, if the first operand of DTAARA is a name, such as DTAARA(myDtaaara), the operand is interpreted as the name of a character field or a named constant containing the name of the data area. To specify the data area name directly, enclose it in quotes: DTAARA('MYDTAARA'). Tip: If you have a mixture of fixed-form and free-form code, consider changing the DTAARA keywords in fixed-form to use a literal rather than a name. Change DTAARA(myDtaara) to DTAARA('MYDTAARA'). Requirement to code END-DS, END-PI, and END-PR For a data structure that allows subfields to be coded (any data structure that does not have the LIKEDS or LIKEDS keyword), you must remember to specify END-DS, either as a separate statement, or at the end of the DCL-DS statement, if you do not code any subfields. For a procedure interface, you must remember to specify END-PI, either as a separate statement, or at the end of the DCL-PI statement, if you do not code any parameters. For a prototype, you must remember to specify END-PR, either as a separate statement, or at the end of the DCL-PR statement, if you do not code any parameters. Ellipsis at the end of definition names If you are accustomed to coding an ellipsis at the end of the names in Definition or Procedure specifications, and then specifying the rest of the statement on the next specification, that will not be possible in free-form. If the name ends with an ellipsis, then the first keyword on the next line will be interpreted as part of the name.
Example dcl-s name... char(10); Valid No Field name NAMECHAR Explanation The programmer does not intend the name to be continued on the second line, but the compiler assumes that CHAR is part of the name. The field name is NAMECHAR and the (10) is considered to be a syntax error. The name is coded without the ellipsis, so the compiler does not search for the end of the name on the next line. The ellipsis at the end of "continued" is valid since the name is continued on the following line.
Yes Yes
NAME CONTINUEDNAME
Specifications
5-5
Common Entries
| | | | | | | | | | | | | |
Common Entries
The following entries are common to all RPG specifications preceding program data: v Positions 1-5 can be used for comments. v If it is a free-form statement, positions 6-7 must be blank. v If it is a fixed-form statement, the specification type is specified in position 6. The following letter codes can be used: Entry H F D I C O Specification Type Control File description Definition Input Calculation Output
P Procedure v Comment Statements Position 7 contains an asterisk (*). This will denote the line as a comment line regardless of any other entry on the specification. In a free-form calculation specification, you can use // for a comment. Any line on any fixed-form specification that begins with // is considered a comment by the compiler. The // can start in any position provided that positions 6 to the // characters contain blanks. Positions 6 to 80 are blank. See free-form comments for more information about comments in free-form specifications. | v Positions 7 to 80 are blank and position 6 contains a valid specification. This is a valid line, not a comment, and sequence rules are enforced.
Syntax of Keywords
Keywords may have no parameters, optional parameters, or required parameters. The syntax for keywords is as follows:
Keyword(parameter1 : parameter2)
where: v Parameter(s) are enclosed in parentheses ( ). Note: Parentheses should not be specified if there are no parameters. v Colons (:) are used to separate multiple parameters. The following notational conventions are used to show which parameters are optional and which are required: v Braces { } indicate optional parameters or optional elements of parameters. v An ellipsis (...) indicates that the parameter can be repeated. v A colon (:) separates parameters and indicates that more than one may be specified. All parameters separated by a colon are required unless they are enclosed in braces. v A vertical bar (|) indicates that only one parameter may be specified for the keyword. v A blank separating keyword parameters indicates that one or more of the parameters may be specified. Note: Braces, ellipses, and vertical bars are not a part of the keyword syntax and should not be entered into your source.
5-6
Common Entries
Table 5-2. Examples of Keyword Notation Notation braces {} braces {} Example of Notation Used PRTCTL (data_struct {:*COMPAT}) TIME(format {separator}) Description Parameter data_struct is required and parameter *COMPAT is optional. Example of Source Entered PRTCTL (data_struct1)
Parameter format{separator} is required, but TIME(*HMS&) the {separator} part of the parameter is optional. Parameters Ext_format and Int_format are required. Parameter recformat is required and can be specified more than once. Specify *NO or *YES or no parameters. RENAME (nameE: nameI) IGNORE (recformat1: recformat2: recformat3) FLTDIV
RENAME(Ext_format :Int_format) IGNORE(recformat {:recformat...}) FLTDIV{(*NO | *YES)} OPTIONS(*OMIT *NOPASS *VARSIZE *STRING *TRIM *RIGHTADJ)
One of *OMIT, *NOPASS, *VARSIZE, OPTIONS(*OMIT : *STRING, *TRIM, or *RIGHTADJ is required *NOPASS : *VARSIZE : *TRIM : *RIGHTADJ) and more than one parameter can be optionally specified.
Continuation Rules
| The fields that may be continued are: v Any free-form statement v v v v v The The The The The keywords field on the control specification keywords field on the file description specification keywords field on the definition specification Extended factor-2 field on the calculation specification constant/editword field on the output specification
v The Name field on the definition or the procedure specification General rules for continuation are as follows: v The continuation line must be a valid line for the specification being continued (H, F, D, C, or O in position 6) v No special characters should be used when continuing specifications across multiple lines, except when a literal or name must be split. For example, the following pairs are equivalent. In the first pair, the plus sign (+) is an operator, even when it appears at the end of a line. In the second pair, the plus sign is a continuation character.
C C C C C C eval eval eval eval x = a + b x = a + b x = abc x = ab+ c
v Only blank lines, empty specification lines or comment lines are allowed between continued lines v The continuation can occur after a complete token. Tokens are Names (for example, keywords, file names, field names) Parentheses The separator character (:) Expression operators Built-in functions
Specifications
5-7
Common Entries
Special words Literals v A continuation can also occur within a literal For character, date, time, and timestamp literals - A hyphen (-) indicates continuation is in the first available position in the continued field - A plus (+) indicates continuation with the first non-blank character in or past the first position in the continued field For graphic literals - Either the hyphen (-) or plus (+) can be used to indicate a continuation. - Each segment of the literal must be enclosed by shift-out and shift-in characters. - When the a graphic literal is assembled, only the first shift-out and the last shift-in character will be included. - Regardless of which continuation character is used for a graphic literal, the literal continues with the first character after the shift-out character on the continuation line. Spaces preceding the shift-out character are ignored. For numeric literals - No continuation character is used - A numeric literal continues with a numeric character or decimal point on the continuation line in the continued field - Continuation for numeric literals is not allowed in free-form statements For hexadecimal and UCS-2 literals - Either a hyphen (-) or a plus (+) can be used to indicate a continuation - The literal will be continued with the first non-blank character on the next line v A continuation can also occur within a name in free-format entries In the name entry for Definition and Procedure specifications. For more information on continuing names in the name entry, see Definition and Procedure Specification Name Field on page 5-11. In the keywords entry for File and Definition specifications. In the extended factor 2 entry of Calculation specifications. You can split a qualified name at a period, as shown below:
C C EVAL dataStructureWithALongName. subfieldWithAnotherLongName = 5
If a name is not split at a period, code an ellipsis (...) at the end of the partial name, with no intervening blanks. Example
5-8
Common Entries
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 DName++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++ D Keywords-cont++++++++++++++++++++++++ * Define a 10 character field with a long name. * The second definition is a pointer initialized to the address * of the variable with the long name. D QuiteLongFieldNameThatCannotAlwaysFitInOneLine... D S 10A D Ptr S * inz(%addr(QuiteLongFieldName... D ThatCannotAlways... D FitInOneLine)) D ShorterName S 5A *.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 CL0N01Factor1+++++++Opcode(E)+Extended-factor2+++++++++++++++++++++++++++++ C Extended-factor2-++++++++++++++++++++++++++++ * Use the long name in an expression * Note that you can split the name wherever it is convenient. C EVAL QuiteLongFieldName... C ThatCannotAlwaysFitInOneLine = abc * You can split any name this way C EVAL P... C tr = %addr(Shorter... C Name)
Control Specification Keyword Field: The rule for continuation on the control specification is: v The specification continues on or past position 7 of the next control specification Example
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 HKeywords++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ H DATFMT( H *MDY& H )
File Description Specification Keyword Field: The rules for continuation on the file description specification are: v The specification continues on or past position 44 of the next file description specification v Positions 7-43 of the continuation line must be blank Example
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 FFilename++IPEASFRlen+LKlen+AIDevice+.Keywords+++++++++++++++++++++++++++++ F.....................................Keywords+++++++++++++++++++++++++++++ F EXTIND F ( F *INU1 F )
Definition Specification Keyword Field: The rules for continuation of keywords on the definition specification are: v The specification continues on or past position 44 of the next Definition specification dependent on the continuation character specified
Specifications
5-9
Common Entries
v Positions 7-43 of the continuation line must be blank Example
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++ D Keywords-cont++++++++++++++++++++++++ DMARY C CONST( D Mary had a little lamb, its * Only a comment or a completely blank line is allowed in here D fleece was white as snow. D ) * Numeric literal, continues with the first non blank in/past position 44 * DNUMERIC C 12345 D 67 * Graphic named constant, must have shift-out in/past position 44 DGRAF C GoAABBCCDDi+ D oEEFFGGi
Calculation Specification Extended Factor-2: The rules for continuation on the Calculation specification are: v The specification continues on or past position 36 of the next calculation specification v Positions 7-35 of the continuation line must be blank Example
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 CL0N01Factor1+++++++Opcode(E)+Extended-factor2+++++++++++++++++++++++++++++ C Extended-factor2-++++++++++++++++++++++++++++ C EVAL MARY=Mary had a little lamb, its + * Only a comment or a completely blank line is allowed in here C fleece was white as snow. * * Arithmetic expressions do not have continuation characters. * The + sign below is the addition operator, not a continuation * character. C C EVAL A = (B*D)/ C + C 24 * The first use of + in this example is the concatenation * operator. The second use is the character literal continuation. C EVAL ERRMSG = NAME + C was not found + C in the file.
Free-Form Specification: The rules for continuation on a free-form calculation specification are: v The free-form line can be continued on the next line. The statement continues until a semicolon is encountered. Example
/FREE time = hours * num_employees + overtime_saved; /END-FREE
5-10
Common Entries
v A continuation character is not used to continue a statement on a subsequent line unless a name or a literal is being continued. See Continuation Rules on page 5-7 for more information about continuing names and literals. v Continuation is not allowed for numeric literals. Numeric literals must be specified on a single line in free-form. Output Specification Constant/Editword Field: The rules for continuation on the output specification are: v The specification continues on or past position 53 of the next output specification v Positions 7-52 of the continuation line must be blank Example
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 O.............N01N02N03Field+++++++++YB.End++PConstant/editword/DTformat+++ O Continue Constant/editword+++ O 80 Mary had a little lamb, its* * Only a comment or a completely blank line is allowed in here O fleece was white as snow.
Definition and Procedure Specification Name Field: The rules for continuation of the name on the definition and procedure specifications are: v Continuation rules apply for names longer than 15 characters. Any name (even one with 15 characters or fewer) can be continued on multiple lines by coding an ellipsis (...) at the end of the partial name. v A name definition consists of the following parts: 1. Zero or more continued name lines. Continued name lines are identified as having an ellipsis as the last non-blank characters in the entry. The name must begin within positions 7 - 21 and may end anywhere up to position 77 (with an ellipsis ending in position 80). There cannot be blanks between the start of the name and the ellipsis (...) characters. If any of these conditions is not true, the line is considered to be a main definition line. 2. One main definition line containing name, definition attributes, and keywords. If a continued name line is coded, the name entry of the main definition line may be left blank. 3. Zero or more keyword continuation lines. Example
Specifications
5-11
Common Entries
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 DName++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++ D Keywords-cont++++++++++++++++++++++++ * Long name without continued name lines: D RatherLongName S 10A * Long name using 1 continued name line: D NameThatIsEvenLonger... D C This is the constant D that the name represents. * Long name using 1 continued name line: D NameThatIsSoLongItMustBe... D Continued S 10A * Compile-time arrays may have long names: D CompileTimeArrayContainingDataRepresentingTheNamesOfTheMonthsOf... D TheYearInGermanLanguage... D S 20A DIM(12) CTDATA PERRCD(1) * Long name using 3 continued name lines: D ThisNameIsSoMuchLongerThanThe... D PreviousNamesThatItMustBe... D ContinuedOnSeveralSpecs... D PR 10A D parm_1 10A VALUE * CL0N01Factor1+++++++Opcode(E)+Extended-factor2+++++++++++++++++++++++++++++ C Extended-factor2-++++++++++++++++++++++++++++ * Long names defined on calc spec: C LongTagName TAG C *LIKE DEFINE RatherLongNameQuiteLongName +5 * PName+++++++++++..B...................Keywords+++++++++++++++++++++++++++++ PContinuedName+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * Long name specified on Procedure spec: P ThisNameIsSoMuchLongerThanThe... P PreviousNamesThatItMustBe... P ContinuedOnSeveralSpecs... P B D ThisNameIsSoMuchLongerThanThe... D PreviousNamesThatItMustBe... D ContinuedOnSeveralSpecs... D PI 10A D parm_1 10A VALUE
Control Specifications
| | | | | The control-specification statements, identified in free-form specifications by the CTL-OPT operation code, or in fixed-form specificiations by an H in position 6, provide information about generating and running programs. However, there are three different ways in which this information can be provided to the compiler and the compiler searches for this information in the following order: 1. Control statements included in your source
| 2. A data area named RPGLEHSPEC in *LIBL | 3. A data area named DFTLEHSPEC in QRPGLE Once one of these sources is found, the values are assigned and keywords that are not specified are assigned their default values. See the description of the individual entries for their default values.
5-12
Common Entries
Note: Compile-option keywords do not have default values. The keyword value is initialized with the value you specify for the CRTBNDRPG or CRTRPGMOD command. Tip: The control specification keywords apply at the module level. This means that if there is more than one procedure coded in a module, the values specified in the control specification apply to all procedures. | | | | | | | |
The data area can be whatever size is required to accommodate the keywords specified. The entire length of the data area can only contain keywords. | | | | | | | | | | Tip: Instead of using a data area to hold your keywords, consider using a copy file instead. When you use a copy file, the keywords in the copy file are used even if there are additional control statements in your source. For example, the following source file will not use the keywords in a data area, because there is a Control statement in the source, preventing the compiler from searching for the data area.
H NOMAIN D fld
10A
The following source file will use the keywords in the DFTCTLKW copy file.
Specifications
5-13
| | |
10A
| A free-form control statement begins with CTL-OPT followed by zero or more keywords, followed by a | semicolon. | Rules for control statements | You can specify zero or more control statements in your source file. | If a control-specification keyword cannot be repeated, it cannot appear more than once in any control | statement. | You can mix free-form and fixed-form control statements. Each contiguous group of fixed-form | specifications constitutes a single control statement. | When the compilation of a program contains any free-form control statements, the presence of the | ACTGRP, BNDDIR, or STGMDL keyword will cause the DFTACTGRP keyword to default to *NO. | The only directives that are allowed within a free-form control statement are /IF, /ELSEIF, /ELSE, and | /ENDIF. | | | | | |
CTL-OPT /IF DEFINED(*CRTBNDRPG) ACTGRP(*CALLER) /ENDIF OPTION(*SRCSTMT);
| Examples of control statements | v Two free-form control statements, each having several keywords | | | | |
ctl-opt datfmt(*iso) timfmt(*iso) alwnull(*usrctl); ctl-opt option(*srcstmt)ccsid(*char:*jobrun);
| v One control statement with no keywords. The only effect of this statement is to prevent the RPG compiler from searching for a control specification data area. | | |
ctl-opt;
| v A mixture of free-form and fixed-form control statements. 1. A fixed-form statement consisting of three specifications | 2. A free-form statement beginning with CTL-OPT and ending with a semicolon | 3. A fixed-form statement consisting of one specification | |
5-14
| | | | | | | |
H OPTION(*SRCSTMT : H *NODEBUGIO) H ACTGRP(*NEW) CTL-OPT ALWNULL(*USRCTL) CCSID(*UCS2 :1200) CCSID(*CHAR:*JOBRUN); H DATFMT(*YMD) TIMFMT(*USA)
1 1 1 2 2 2 2 3
The control-specification keywords are used to determine how the program will deal with devices and how certain types of information will be represented. The control-specification keywords also include compile-option keywords that override the default or specified options on the CRTBNDRPG and CRTRPGMOD commands. These keywords determine the compile options to be used on every compile of the program.
Control-Specification Keywords
Control-specification keywords may have no parameters, optional parameters, or required parameters. The syntax for keywords is as follows:
Keyword(parameter1 : parameter2)
Specifications
5-15
Control-Specification Keywords
Note: Do not specify parentheses if there are no parameters. v Colons (:) are used to separate multiple parameters. The following notational conventions are used to show which parameters are optional and which are required: v Braces { } indicate optional parameters or optional elements of parameters. v An ellipsis (...) indicates that the parameter can be repeated. v A colon (:) separates parameters and indicates that more than one may be specified. All parameters separated by a colon are required unless they are enclosed in braces. v A vertical bar (|) indicates that only one parameter may be specified for the keyword. v A blank separating keyword parameters indicates that one or more of the parameters may be specified. Note: Braces, ellipses, and vertical bars are not a part of the keyword syntax and should not be entered into your source. If additional space is required for control-specification keywords, the keyword field can be continued on subsequent lines. See Traditional Control-Specification Statement on page 5-15 and Control Specification Keyword Field on page 5-9. # ALLOC(*STGMDL | *TERASPACE | *SNGLVL) # The ALLOC keyword specifies the storage model for storage management operations in the module. # If the ALLOC keyword is not specified, ALLOC(*STGMDL) is assumed. # v *STGMDL is used to specify that the storage model for memory management operations will be the same as the storage model of the module. You use the STGMDL keyword on the Control specification # to control the storage model of the module. If the storage model of the module is *INHERIT, the # storage model used for memory management operations is determined at runtime. # # v *SNGLVL is used to specify that the single-level storage model will be used for memory management operations. # # v *TERASPACE is used to specify that the teraspace storage model will be used for memory management operations. # # See Memory Management Operations on page 6-34 for more information on teraspace and single-level # memory management operations.
5-16
Control-Specification Keywords
Note: The name of the activation group created when the program is called will have exactly the same case as the text entered for the activation-group-name. The RCLACTGRP command does not allow lower-case text to be specified for its ACTGRP parameter. If it is required to reclaim an activation group individually using the RCLACTGRP command then do not enter lower-case case text for the activation-group-name.
If ALWNULL(*USRCTL) is specified, then you can read, write, and update records with null values from externally described database files. Records with null keys can be retrieved using keyed operations. You can determine whether a null-capable field is actually null, and you can set a null-capable field to be null for output or update. You are responsible for ensuring that fields containing null values are used correctly. If the ALWNULL keyword is not specified, then the value specified on the command is used.
Specifications
5-17
Control-Specification Keywords
For more information, see Database Null Value Support on page 4-86
BNDDIR('binding-directory-name' {:'binding-directory-name'...})
The BNDDIR keyword specifies the list of binding directories that are used in symbol resolution. A binding directory name can be qualified by a library name followed by a slash delimiter ('library-name/binding-directory-name'). The library name is the name of the library to be searched. If the library name is not specified, *LIBL is used to find the binding directory name. When creating a program using CRTBNDRPG, the library list is searched at the time of the compile. When creating a module using CRTRPGMOD, the library list is searched when the module is used to create a program or service program. If BNDDIR is specified on both the control specification and on the command, all binding directories are used for symbol resolution. The BNDDIR on the control specification does not override the BNDDIR on the command. If the BNDDIR keyword is not specified, then the value specified on the command is used. # You cannot use the BNDDIR, ACTGRP, or STGMDL command parameters or keywords when creating a # program with DFTACTGRP(*YES). | See DFTACTGRP(*YES | *NO) on page 5-25 for information on how the BNDDIR keyword affects the | setting of the DFTACTGRP keyword.
5-18
Control-Specification Keywords
CCSIDCVT(*EXCP | *LIST)
The CCSIDCVT keyword allows you to control how the compiler handles conversions between data with different CCSIDs. When two CCSIDs support different character sets, it is possible for a character in one CCSID not to have a matching character in the other CCSID. For example, the Japanese and Thai character sets each contain many characters that are not part of the other character set. If a UCS-2 variable contains both Japanese and Thai characters, and the UCS-2 variable is converted to a Japanese Graphic variable, the Thai
Specifications
5-19
Control-Specification Keywords
| characters will not have matching characters in the DBCS variable. When the conversion cannot find a | matching character in the target character set, the conversion will place a substitution character in the | target variable. | The substitution character for alphanumeric data is x'3F'. The substitution character for Graphic data is | x'FEFE'. | | | | | | One or both parameters may be specified for the CCSIDCVT keyword. If both parameters are specified, they are separated by a colon. They may be specified in any order. v CCSIDCVT(*EXCP : *LIST) v CCSIDCVT(*LIST : *EXCP) v CCSIDCVT(*LIST) v CCSIDCVT(*EXCP)
| *EXCP | *EXCP indicates that when a conversion results in a substitution character at run time, that it will | cause an RPG exception with status code 452. | *LIST | *LIST indicates that the compiler should add a section to the listing indicating all the implicit and | explicit CCSID conversions, with an indication of which conversions could result in loss of data due | to substitution characters being placed in the result because of the lack of matching characters in the | target character set. | | | | | | | | | | | | | | | | | | | | | | | | | | | Note: The CCSID Conversion Summary section of the listing is only available when the program or module is created. It will not be created if there are compile-time errors or if OPTION(*NOGEN) is specified for the compile. You can use this information for two purposes: v You can improve performance by reducing the number of conversions by changing the data types of some of your variables. v You can improve the reliability of your program by eliminating some of the conversions that have the potential to result in substitution characters. For example, if you have a conversion from UCS-2 to a alphanumeric variable, and that alphanumeric data is later converted back to UCS-2, you may be able to change the type of the alphanumeric variable to UCS-2, to avoid the potential data loss. The following types of conversions can result in substitution characters: v Conversion from UCS-2 to alphanumeric or DBCS v Conversion between two different DBCS CCSIDs v Conversion from alphanumeric to DBCS v Conversion from DBCS to alphanumeric For each CCSID conversion used in the module, there is a list of the statement numbers with that conversion. If the conversion could result in substitution characters, a message number will be shown to the left of the conversion entry. That message will appear in the Message Summary at the end of the compile. The following special values are used for some CCSIDs whose value is not known until runtime: *JOBRUN The job CCSID, or the default job CCSID if the job CCSID is 65535. This is the CCSID for all alphanumeric data in the RPG module if CCSID(*CHAR : *JOBRUN) is specified in the Control specification. *JOBRUN_MIXED The mixed-byte CCSID related to the job CCSID, or related to the default job CCSID if the job CCSID is 65535. This CCSID may be the same as the actual job CCSID, if the job CCSID is a
5-20
Control-Specification Keywords
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | mixed-byte CCSID. This is the CCSID for all alphanumeric data in the RPG module if CCSID(*CHAR : *JOBRUN) is not specified in the Control specification. See CCSID(*GRAPH : parameter | *UCS2 : number | *CHAR : *JOBRUN) on page 5-19 for more information. *JOBRUN_DBCS The double-byte CCSID related to the job CCSID, or related to the default job CCSID if the job CCSID is 65535. This CCSID may be used as the CCSID of the non-shift alphanumeric data for conversions between alphanumeric data and graphic data. *JOBRUN_JAVA The CCSID used for parameters and return values of Java methods when the RPG parameter or return value is defined as alphanumeric. The RPG compiler assumes that this CCSID is related to the job CCSID, so the RPG compiler assumes that there will be no possibility of the conversion resulting in substitution characters. The following example shows a CCSID Conversion Summary. The first entry shows that six statements have conversions from alphanumeric data in the job CCSID to UCS-2 data with CCSID 1200. The second entry shows that three statements have conversions from UCS-2 data with CCSID 1200 to alphanumeric data in the job CCSID. The message RNF7357 preceding the second entry indicates that these conversions could result in substitution characters being placed in the alphanumeric data.
C C S I D C o n v e r s i o To CCSID References 1200 27 552 *JOBRUN 28 O F C C S I D C O N V E R S n s 12 321 426 631 921 1073 I O N S * * * * *
COPYNEST(number)
The COPYNEST keyword specifies the maximum depth to which nesting can occur for /COPY directives. The depth must be greater than or equal to 1 and less than or equal to 2048. The default depth is 32.
COPYRIGHT('copyright string')
The COPYRIGHT keyword provides copyright information that can be seen using the DSPMOD, DSPPGM, or DSPSRVPGM commands. The copyright string is a character literal with a maximum length of 256. The literal may be continued on a continuation specification. (See Continuation Rules on page 5-7 for rules on using continuation lines.) If the COPYRIGHT keyword is not specified, copyright information is not added to the created module or program. Tip: To see the copyright information for a module, use the command:
DSPMOD mylib/mymod DETAIL(*COPYRIGHT)
For a program, use the DSPPGM command with DETAIL(*COPYRIGHT). This information includes the copyright information from all modules bound into the program. Similarly, DSPSRVPGM DETAIL(*COPYRIGHT) gives the copyright information for all modules in a service program.
CURSYM('sym')
The CURSYM keyword specifies a character used as a currency symbol in editing. The symbol must be a single character enclosed in quotes. Any character in the RPG character set (see Symbolic Names and Reserved Words on page 3-1) may be used except:
Specifications
5-21
Control-Specification Keywords
v v v v v v v v v 0 (zero) * (asterisk) , (comma) & (ampersand) . (period) - (minus sign) C (letter C) R (letter R) Blank
If the keyword is not specified, $ (dollar sign) will be used as the currency symbol.
5-22
Control-Specification Keywords
DATEDIT(fmt{separator})
The DATEDIT keyword specifies the format of numeric fields when using the Y edit code. The separator character is optional. The value (fmt) can be *DMY, *MDY, or *YMD. The default separator is /. A separator character of & (ampersand) may be used to specify a blank separator.
DATFMT(fmt{separator})
The DATFMT keyword specifies the internal date format for date literals and the default internal format for date fields within the program. You can specify a different internal date format for a particular field by specifying the format with the DATFMT keyword on the definition specification for that field. If the DATFMT keyword is not specified, the *ISO format is assumed. For more information on internal formats, see Internal and External Formats on page 4-49. Table 4-3 on page 4-73 describes the various date formats and their separators.
Specifying the DEBUG keyword with *NO indicates that no debugging aids should be generated into the module. This is the same as omitting the DEBUG keyword entirely. No other parameters can be specified when *NO is specified. Specifying the DEBUG keyword with *YES or with no parameters is the same as specifying DEBUG(*INPUT : *DUMP). No other parameters can be specified when *YES is specified. The value *YES is retained for compatibility; it is preferable to specify the more granular values *INPUT, *DUMP and *XMLSAX. Examples:
* 1. All of the debugging aids are available H DEBUG(*INPUT : *DUMP : *XMLSAX) * 2. None of the debugging aids are available
Specifications
5-23
Control-Specification Keywords
H DEBUG(*NO) * 3. Only the debugging aid related to input fields is available H DEBUG(*INPUT) * 4. The debugging aids related to the DUMP operation and * to XML-SAX parsing are available H DEBUG(*XMLSAX : *DUMP)
Note: The DEBUG keyword does not control whether the module is created to be debuggable. That is controlled by the DBGVIEW parameter for the CRTBNDRPG or CRTRPGMOD command. The DEBUG keyword controls additional debugging aids.
DECEDIT(*JOBRUN | 'value')
The DECEDIT keyword specifies the character used as the decimal point for edited decimal numbers and whether or not leading zeros are printed. If *JOBRUN is specified, the DECFMT value associated with the job at runtime is used. The possible job decimal formats are listed in the following table:
Table 5-3. DECEDIT with *JOBRUN Job Decimal Format blank I J Decimal Point period (.) comma (,) comma (,) Print Leading Zeros No No Yes Edited Decimal Number .123 ,123 0,123
If a value is specified, then the edited decimal numbers are printed according to the following possible values:
Table 5-4. DECEDIT with 'value' 'Value' '.' ',' '0.' '0,' Decimal Point period (.) comma (,) period (.) comma (,) Print Leading Zeros No No Yes Yes Edited Decimal Number .123 ,123 0.123 0,123
If DECEDIT is not specified, a period (.) is used for editing numeric values. Note: Zeros to the right of a decimal point are always printed.
DECPREC(30|31|63)
Keyword DECPREC is used to specify the decimal precision of decimal (packed, zoned, or binary) intermediate values in arithmetic operations in expressions. Decimal intermediate values are always maintained in the proper precision, but this keyword affects how decimal expressions are presented when used in %EDITC, %EDITW, %CHAR, %LEN, and %DECPOS. DECPREC(30) The default decimal precision. It indicates that the maximum precision of decimal values when used in the affected operations is 30 digits. However, if at least one operand in the expression is a decimal variable with 31 digits, DECPREC(31) is assumed for that expression. If at least one operand in the expression is a decimal variable with 32 or more digits, DECPREC(63) is assumed for that expression.
5-24
Control-Specification Keywords
DECPREC(31) The maximum precision of decimal values when used in the affected operations is 31 digits. However, if at least one operand in the expression is a decimal variable with 32 digits or more, DECPREC(63) is assumed for that expression. DECPREC(63) The number of digits used in the affected operations is always computed following the normal rules for decimal precision, which can be up to the maximum of 63 digits.
DFTACTGRP(*YES | *NO)
The DFTACTGRP keyword specifies the activation group in which the created program will run when it is called. # # # # # # # # If *YES is specified, then this program will always run in the default activation group, which is the activation group where all original program model (OPM) programs are run. This allows ILE RPG programs to behave like OPM RPG programs in the areas of file sharing, file scoping, RCLRSC, and handling of unmonitored exceptions. ILE static binding is not available when a program is created with DFTACTGRP(*YES). This means that you cannot use the BNDDIR, ACTGRP, or STGMDL command parameters or keywords when creating this program. In addition, any call operation in your source must call a program and not a procedure. DFTACTGRP(*YES) is useful when attempting to move an application on a program-by-program basis to ILE RPG. If *NO is specified, then the program is associated with the activation group specified by the ACTGRP command parameter or keyword and static binding is allowed. DFTACTGRP(*NO) is useful when you intend to take advantage of ILE concepts; for example, running in a named activation group or binding to a service program. The DFTACTGRP keyword is valid only if the CRTBNDRPG command is used. | | | | | | | | | | | | | | | | |
In the following example, the STGMDL keyword is specified in a fixed-form Control statement, but there is also a free-form Control statement, so DFTACTGRP(*NO) is assumed.
CTL-OPT; H OPTION(*SRCSTMT) STGMDL(*INHERIT)
In the following example, there is a free-form Control statement, but none of the ACTGRP, BNDDIR, or STGMDL keywords are specified. The value specified for the DFTACTGRP parameter of the CRTBNDRPG command is used.
Specifications
5-25
Control-Specification Keywords
CTL-OPT OPTION(*SRCSTMT);
DFTNAME(rpg_name)
The DFTNAME keyword specifies a default program or module name. When *CTLSPEC is specified on the create command, the rpg_name is used as the program or module name. If rpg_name is not specified, then the default name is RPGPGM or RPGMOD for a program or module respectively. The RPG rules for names (see Symbolic Names on page 3-1) apply.
EXPROPTS(*MAXDIGITS | *RESDECPOS)
The EXPROPTS (expression options) keyword specifies the type of precision rules to be used for an entire program. If not specified or specified with *MAXDIGITS, the default precision rules apply. If EXPROPTS is specified, with *RESDECPOS, the "Result Decimal Position" precision rules apply and force intermediate results in expressions to have no fewer decimal positions than the result. Note: Operation code extenders R and M are the same as EXPROPTS(*RESDECPOS) and EXPROPTS(*MAXDIGITS) respectively, but for single free-form expressions.
EXTBININT{(*NO | *YES)}
| | | | The EXTBININT keyword is used to process externally described fields with binary external format and zero decimal positions as if they had an external integer format. If not specified or specified with *NO, then an externally described binary field is processed with an external binary-decimal format. If EXTBININT is specified, optionally with *YES, then an externally described field is processed as follows:
| DDS Definition RPG external format | | B(n,0) where 1 n 4 I(5) | | | B(n,0) where 5 n 9 I(10) By specifying the EXTBININT keyword, your program can make use of the full range of DDS binary values available. (The range of DDS binary values is the same as for signed integers: -32768 to 32767 for a 5-digit field or -2147483648 to 2147483647 for a 10-digit field.) Note: When the keyword EXTBININT is specified, any externally described subfields that are binary with zero decimal positions will be defined with an internal integer format.
5-26
Control-Specification Keywords
FIXNBR(*{NO}ZONED *{NO}INPUTPACKED)
The FIXNBR keyword specifies whether decimal data that is not valid is fixed by the compiler. You can specify any or all of the data types in any order. However, if a decimal data type is specified, the *NOxxxx parameter for the same data type cannot also be used, and vice versa. For example, if you specify *ZONED you cannot also specify *NOZONED, and vice versa. Separate the parameters with a colon. A parameter cannot be specified more than once. Note: If the keyword FIXNBR does not contain a member from a pair, then the value specified on the command for this particular data type will be used. For example, if the keyword FIXNBR(*NOINPUTPACKED) is specified on the Control specification, then for the pair (*ZONED, *NOZONED), whatever was specified implicitly or explicitly on the command will be used. If *ZONED is specified, then zoned decimal data that is not valid will be fixed by the compiler on the conversion to packed data. Blanks in numeric fields will be treated as zeros. Each decimal digit will be checked for validity. If a decimal digit is not valid, it is replaced with zero. If a sign is not valid, the sign will be forced to a positive sign code of hex 'F'. If the sign is valid, it will be changed to either a positive sign hex 'F' or a negative sign hex 'D', as appropriate. If the resulting packed data is not valid, it will not be fixed. If *NOZONED is specified, then zoned decimal data is not fixed by the compiler on the conversion to packed data and will result in decimal errors during runtime if used. If *INPUTPACKED is specified, then the internal variable will be set to zero if packed decimal data that is not valid is encountered while processing input specifications. If *NOINPUTPACKED is specified, then decimal errors will occur if packed decimal data that is not valid is encountered while processing input specifications. If the FIXNBR keyword is not specified, then the values specified on the command are used.
FLTDIV{(*NO | *YES)}
The FLTDIV keyword indicates that all divide operations within expressions are computed in floating point and return a value of type float. If not specified or specified with *NO, then divide operations are performed in packed-decimal format (unless one of the two operands is already in float format). If FLTDIV is specified, optionally with *YES, then all divide operations are performed in float format (guaranteeing that the result always has 15 digits of precision).
FORMSALIGN{(*NO | *YES)}
The FORMSALIGN keyword indicates that the first line of an output file conditioned with the 1P indicator can be printed repeatedly, allowing you to align the printer. If not specified or specified with *NO, no alignment will be performed. If specified, optionally with *YES, first page forms alignment will occur. Rules for Forms Alignment v The records specified on Output Specifications for a file with a device entry for a printer type device conditioned by the first page indicator (1P) may be written as many times as desired. The line will print once. The operator will then have the option to print the line again or continue with the rest of the program. v All spacing and skipping specified will be performed each time the line is printed. v When the option to continue with the rest of the program is selected, the line will not be reprinted. v The function may be performed for all printer files. v If a page field is specified, it will be incremented only the first time the line is printed.
Specifications
5-27
Control-Specification Keywords
v When the continue option is selected, the line count will be the same as if the function were performed only once when line counter is specified.
FTRANS{(*NONE | *SRC)}
The FTRANS keyword specifies whether file translation will occur. If specified, optionally with *SRC, file translation will take place and the translate table must be specified in the program. If not specified or specified with *NONE, no file translation will take place and the translate table must not be present.
GENLVL(number)
The GENLVL keyword controls the creation of the object. The object is created if all errors encountered during compilation have a severity level less than or equal to the generation severity level specified. The value must be between 0 and 20 inclusive. For errors greater than severity 20, the object will not be created. If the GENLVL keyword is not specified, then the value specified on the command is used.
INDENT(*NONE | 'character-value')
The INDENT keyword specifies whether structured operations should be indented in the source listing for enhanced readability. It also specifies the characters that are used to mark the structured operation clauses. Note: Any indentation that you request here will not be reflected in the listing debug view that is created when you specify DBGVIEW(*LIST). If *NONE is specified, structured operations will not be indented in the source listing. If character-value is specified, the source listing is indented for structured operation clauses. Alignment of statements and clauses are marked using the characters you choose. You can choose any character literal up to 2 characters in length. Note: The indentation may not appear as expected if there are errors in the source. If the INDENT keyword is not specified, then the value specified on the command is used.
INTPREC(10 | 20)
The INTPREC keyword is used to specify the decimal precision of integer and unsigned intermediate values in binary arithmetic operations in expressions. Integer and unsigned intermediate values are always maintained in 8-byte format. This keyword affects only the way integer and unsigned intermediate values are converted to decimal format when used in binary arithmetic operations (+, -, *, /). INTPREC(10), the default, indicates a decimal precision of 10 digits for integer and unsigned operations. However, if at least one operand in the expression is an 8-byte integer or unsigned field, the result of the expression has a decimal precision of 20 digits regardless of the INTPREC value. INTPREC(20) indicates that the decimal precision of integer and unsigned operations is 20 digits.
5-28
Control-Specification Keywords
If *JOB is specified, then the LANGID value associated with the job when the RPG object is created is used. A language identifier can be specified, for example, 'FRA' for French and 'DEU' for German. If the LANGID keyword is not specified, then the value specified on the command is used.
MAIN(main_procedure_name)
The MAIN keyword indicates that this source program is for a linear-main module and contains a linear-main procedure, identified by the main_procedure_name parameter, which will be the program entry procedure for the module. # # # # The main_procedure_name must be the name of a procedure defined in the source program. The linear-main procedure is intended to be called only through the program call interface and not as a bound procedure call; if you make a recursive call to the linear-main procedure, the call will be a dynamic program call. Therefore, the following rules apply: # v # v # # v # If a prototype is specified for the linear-main procedure, it must specify the EXTPGM keyword. If a prototype is not specified for the linear-main procedure, and a procedure interface is specified, the procedure interface must specify the EXTPGM keyword.
If the program has no parameters, and the program is not called from an RPG program, neither a prototype nor a procedure interface is required. v The procedure cannot be exported; the EXPORT keyword may not be specified on the procedure-begin specification for main_procedure_name. A linear-main module will not include logic for the RPG program cycle; thus language features dependent on the cycle may not be specified. Note: The NOMAIN keyword also allows you to create a module that does not contain the RPG program cycle. See Linear Module on page 3-24 for more information.
# The following two examples show a linear-main program and its /COPY file.
The prototype for the linear-main procedure must have the EXTPGM keyword with the name of the actual program. D DisplayCurTime PR EXTPGM(DSPCURTIME) Figure 5-3. /COPY file DSPCURTIME used in the following sample linear-main program * *
Specifications
5-29
Control-Specification Keywords
* The program is named DSPCURTIME, and the module has * a linear-main procedure called DisplayCurTime. * * * * The Control specification MAIN keyword signifies that this is a linear-main module, and identifies which procedure is the special subprocedure which serves as the linear-main procedure, which will act as the program-entry procedure.
H MAIN(DisplayCurTime) * Copy in the prototype for the program /COPY DSPCURTIME *-------------------------------------------------* Procedure name: DisplayCurTime *-------------------------------------------------P DisplayCurTime B D DisplayCurTime PI /FREE dsply (It is now + %char(%time())); /END-FREE P DisplayCurTime E Figure 5-4. A sample linear-main procedure used in a program
# # # # # #
The following example shows a linear main program that does not require a prototype. The program is named PRTCUSTRPT, and the module has a linear-main procedure called PrintCustomerReport. The program is intended to be the command processing program for a *CMD object, so there is no need for an RPG prototype. The Control specification MAIN keyword signifies that this is a linear-main module, and identifies which procedure is the special subprocedure which serves as the linear-main procedure, which will act as the program-entry procedure.
# H MAIN(PrintCustomerReport) # # *-------------------------------------------------# * Program name: PrintCustomerReport (PRTCUSTRPT) # *-------------------------------------------------P PrintCustomerReport... # P B F ... file specifications # D PI EXTPGM(PRTCUSTRPT) # D custName 25A CONST # # ... calculations, using the custName parameter P PrintCustomerReport... # P E # # # # Figure 5-5. A linear main program that is not intended to be called from within any RPG program or procedure #
NOMAIN
The NOMAIN keyword indicates that there is no main procedure in this module. It also means that the module in which it is coded cannot be a program-entry module. Consequently, if NOMAIN is specified, then you cannot use the CRTBNDRPG command to create a program. Instead you must either use the CRTPGM command to bind the module with NOMAIN specified to another module that has a program entry procedure or you must use the CRTSRVPGM command. A no-main module will not include logic for the RPG program cycle; thus language features dependent on the cycle must not be specified. # Note: In addition to the NOMAIN keyword, the MAIN keyword also allows you to create a module that # does not contain the RPG program cycle. See Linear Module on page 3-24 for more information.
5-30
Control-Specification Keywords
OPTION(*{NO}XREF *{NO}GEN *{NO}SECLVL *{NO}SHOWCPY *{NO}EXPDDS *{NO}EXT *{NO}SHOWSKP) *{NO}SRCSTMT) *{NO}DEBUGIO) *{NO}UNREF
The OPTION keyword specifies the options to use when the source member is compiled. You can specify any or all of the options in any order. However, if a compile option is specified, the *NOxxxx parameter for the same compile option cannot also be used, and vice versa. For example, if you specify *XREF you cannot also specify *NOXREF, and vice versa. Separate the options with a colon. You cannot specify an option more than once. Note: If the keyword OPTION does not contain a member from a pair, then the value specified on the command for this particular option will be used. For example, if the keyword OPTION(*XREF : *NOGEN : *NOSECLVL : *SHOWCPY) is specified on the Control specification, then for the pairs, (*EXT, *NOEXT), (*EXPDDS, *NOEXPDDS) and (*SHOWSKP, *NOSHOWSKP), whatever was specified implicitly or explicitly on the command will be used. If *XREF is specified, a cross-reference listing is produced (when appropriate) for the source member. *NOXREF indicates that a cross-reference listing is not produced. If *GEN is specified, a program object is created if the highest severity level returned by the compiler does not exceed the severity specified in the GENLVL option. *NOGEN does not create an object. If *SECLVL is specified, second-level message text is printed on the line following the first-level message text in the Message Summary section. *NOSECLVL does not print second-level message text on the line following the first-level message text. If *SHOWCPY is specified, the compiler listing shows source records of members included by the /COPY compiler directive. *NOSHOWCPY does not show source records of members included by the /COPY compiler directive. If *EXPDDS is specified, the expansion of externally described files in the listing and key field information is displayed. *NOEXPDDS does not show the expansion of externally described files in the listing or key field information.
Specifications
5-31
Control-Specification Keywords
If *EXT is specified, the external procedures and fields referenced during the compile are included on the listing. *NOEXT does not show the list of external procedures and fields referenced during compile on the listing. If *SHOWSKP is specified, then all statements in the source part of the listing are displayed, regardless of whether or not the compiler has skipped them. *NOSHOWSKP does not show skipped statements in the source part of the listing. The compiler skips statements as a result of /IF, /ELSEIF, or /ELSE directives. If *SRCSTMT is specified, statement numbers for the listing are generated from the source ID and SEU sequence numbers as follows:
stmt_num = source_ID * 1000000 + source_SEU_sequence_number
For example, the main source member has a source ID of 0. If the first line in the source file has sequence number 000100, then the statement number for this specification would be 100. A line from a /COPY file member with source ID 27 and source sequence number 000100 would have statement number 27000100. *NOSRCSTMT indicates that line numbers are assigned sequentially. If *DEBUGIO is specified, breakpoints are generated for all input and output specifications. *NODEBUGIO indicates that no breakpoints are to be generated for these specifications. If *UNREF is specified, all variables are generated into the module. If *NOUNREF is specified, unreferenced variables are not generated unless they are needed by some other module. The following rules apply to OPTION(*NOUNREF): v Variables defined with EXPORT are always generated into the module whether or not they are referenced. v Unreferenced variables defined with IMPORT are generated into the module if they appear on Input specifications. v The *IN indicator array and the *INxx indicators are not generated into the module if no *IN indicator is used in the program, either explicitly by a *INxx reference, or implicitly by conditioning or result indicator entries. v For variables not defined with EXPORT or IMPORT: Variables associated with Files, or used in Calculations or on Output specifications are always generated. Variables that appear only on Definition specifications are not generated into the module if they are not referenced. Variables that are referenced only by Input specifications are generated into the module only if DEBUG, DEBUG(*YES) or DEBUG(*INPUT) is specified on the Control specification. If the OPTION keyword is not specified, then the values specified on the command are used.
5-32
Control-Specification Keywords
The PGMINFO setting defaults to the values specified on the PGMINFO and INFOSTMF parameters of the CRTRPGMOD or CRTBNDRPG command. If the PGMINFO keyword conflicts with the PGMINFO and INFOSTMF command parameters, the value of the Control specification keyword overrides the values specified on the command. However, if the requests from the command parameters and the PGMINFO keyword are different but not in conflict, the compiler will merge the values of the command parameters and the PGMINFO keyword. Examples: v If the command parameters, for example PGMINFO(*PCML) and INFOSTMF('mypgm.pcml'), specify that the information should be placed in a stream file, and the PGMINFO(*PCML:*MODULE) keyword specifies that the information should be placed in the module, then both requests will be merged, and the final PGMINFO values will be PGMINFO(*PCML:*ALL) INFOSTMF('mypgm.pcml'). v If the command parameters PGMINFO(*PCML *ALL) INFOSTMF('/home/mypcml/ mypgm.pcml')specify that the information should be placed both in the module and in a stream file, and the PGMINFO(*NO) keyword specifies that no information should be saved, then the PGMINFO keyword will override the command values, and the final PGMINFO value will be PGMINFO(*NO).
PRFDTA(*NOCOL | *COL)
The PRFDTA keyword specifies whether the collection of profiling data is enabled. If *NOCOL is specified, the collection of profiling data is not enabled for this object. If *COL is specified, the collection of profiling is enabled for this object. *COL can be specified only when the optimization level of the object is *FULL. If the PRFDTA keyword is not specified, then the value specified on the command is used.
5-33
Control-Specification Keywords
# v *INHERIT is used to specify the inherit storage model. # v *TERASPACE is used to specify the teraspace storage model. # # # # When a single-level storage model program or service program is activated and run, it is supplied single-level storage for automatic and static storage. A single-level storage program or service program runs only in a single-level storage activation group. A program compiled with DFTACTGRP(*YES) must be a single-level storage model program.
| See DFTACTGRP(*YES | *NO) on page 5-25 for information on how the STGMDL keyword affects the | setting of the DFTACTGRP keyword. # When a teraspace storage model program or service program is activated and run, it is supplied # teraspace storage for automatic and static storage. A teraspace storage program or service program runs # only in a teraspace storage activation group. # # # # When an inherit storage model program or service program is activated, it adopts the storage model of the activation group into which it is activated. An equivalent view is that it inherits the storage model of its caller. When the *INHERIT storage model is selected, *CALLER must be specified for the activation group through the ACTGRP parameter or keyword.
# An inherit storage model module can be bound into programs and service programs with a storage # model of single-level, teraspace or inherit. # A single-level storage model module can only be bound into programs and service programs that use # single-level storage. # A teraspace storage model module can only be bound into programs and service programs that use # teraspace storage. # If the STGMDL keyword is not specified, then the value specified on the command is used.
THREAD(*CONCURRENT | *SERIALIZE)
The THREAD keyword indicates that the ILE RPG module being created is intended to run safely in a multithreaded environment. One of the major thread-safety issues is the handling of static storage. When multiple threads access the same storage location at the same time, unpredictable results can occur. Specifying the THREAD keyword helps you make your module thread-safe with regards to the static storage in the module. You can choose between having separate static storage for each thread, or limiting access to the module to only one thread at a time. You can mix the two types of modules in the same program, or service program. However, you should not omit the THREAD keyword in any module that may run in a multithreaded environment.
5-34
Control-Specification Keywords
You do not have to be concerned about automatic variables. Automatic variables are naturally thread-safe because they are created for each invocation of a procedure. Automatic storage for a procedure is allocated in storage which is unique for each thread. THREAD(*CONCURRENT): If THREAD(*CONCURRENT) is specified, then multiple threads can run in the module at the same time. By default, all the static storage in the module will be in thread-local storage, meaning that each thread will have its own copy of the static variables in the module, including compiler-internal variables. This allows multiple threads to run the procedures within the module at the same time and be completely independent of each other. For example, one thread could be in the middle of a loop that is reading a file in procedure PROCA, at the same time as another thread is running in an earlier part of PROCA, preparing to open the file for its own use. If the module has a global variable NAME, the value of NAME could be 'Jack' in one thread and 'Jill' in another. The thread-local static variables allow the threads to operate independently. You can choose to have some of your static variables shared among all threads by using the STATIC(*ALLTHREAD) keyword. If you use this keyword, you are responsible for ensuring that your procedures use that storage in a thread-safe way. See THREAD(*CONCURRENT | *SERIALIZE) on page 5-34. You can choose to serialize access to individual procedures by specifying the SERIALIZE keyword on the Procedure-Begin specification. If you want to ensure that only one thread is active at one time in a particular part of section of the code, you can move that code to a serialized procedure. THREAD(*SERIALIZE): If THREAD(*SERIALIZE) is specified, access to the procedures in the module is serialized. When called in a multithreaded environment, any code within the module can be used by at most one thread at a time. General thread considerations: To see the advantages and disadvantages of the two types of thread-safety for RPG, see the section on multithreaded applications in Rational Development Studio for i: ILE RPG Programmer's Guide. For a list of system functions that are not allowed or supported in a multithreaded environment, see the Multithreaded Applications document under the Programming topic at the following URL:
http://www.ibm.com/systems/i/infocenter/
You cannot use the following in a thread-safe program: v *INUx indicators v External indicators (*INU1 - *INU8) v The LR indicator for the CALL or CALLB operation When using the THREAD keyword, remember the following: v It is up to the programmer to ensure that storage that is shared across modules or threads is used in a thread-safe manner. This includes: Storage explicitly shared by being exported and imported. Storage shared because a procedure saves the address of a parameter or a pointer parameter, or allocated storage, and uses it on a subsequent call. Storage shared because STATIC(*ALLTHREAD) was specified on the definition of the variable. v If shared files are used by more than one language (RPG and C, or RPG and COBOL), ensure that only one language is accessing the file at one time.
TIMFMT(fmt{separator})
The TIMFMT keyword specifies the internal time format for time literals and the default internal format for time fields within the program. You can specify a different internal time format for a particular field by specifying the format with the TIMFMT keyword on the definition specification for that field.
Specifications
5-35
Control-Specification Keywords
If the TIMFMT keyword is not specified the *ISO format is assumed. For more information on internal formats, see Internal and External Formats on page 4-49. Table 4-6 on page 4-76 shows the time formats supported and their separators.
TRUNCNBR(*YES | *NO)
The TRUNCNBR keyword specifies if the truncated value is moved to the result field or if an error is generated when numeric overflow occurs while running the object. Note: The TRUNCNBR option does not apply to calculations performed within expressions. (Expressions are found in the Extended-Factor 2 field.) If overflow occurs for these calculations, an error will always occur. If *YES is specified, numeric overflow is ignored and the truncated value is moved to the result field. If *NO is specified, a run-time error is generated when numeric overflow is detected. If the TRUNCNBR keyword is not specified, then the value specified on the command is used.
USRPRF(*USER | *OWNER)
The USRPRF keyword specifies the user profile that will run the created program object. The profile of the program owner or the program user is used to run the program and to control which objects can be used by the program (including the authority the program has for each object). This keyword is not updated if the program already exists. If *USER is specified, the user profile of the program's user will run the created program object. If *OWNER is specified, the user profiles of both the program's user and owner will run the created program object. The collective set of object authority in both user profiles is used to find and access objects while the program is running. Any objects created during the program are owned by the program's user. If the USRPRF keyword is not specified, then the value specified on the command is used. The USRPRF keyword is valid only if the CRTBNDRPG command is used. | VALIDATE(*NODATETIME) | The VALIDATE keyword specifies whether Date, Time and Timestamp data must be validated before it is | used. | If this keyword is not specified, then Date, Time and Timestamp data is validated before it is used. | If *NODATETIME is specified, the compiler may omit performing validation for Date, Time and | Timestamp data before it is used. | Specifying this keyword may improve the performance of the RPG program. In some cases, the compiler | may be able to treat the Date, Time, or Timestamp data as though it was Alphanumeric data, avoiding | the costly operations that deal with true Date, Time and Timestamp data. | Some examples of validations that will be omitted with VALIDATE(*NODATETIME): | v When Timestamp fields are being used in comparison, sort or search operations, the Timestamp fields will be not be validated during the comparison. | | v When Date fields with date-format *ISO or *JIS are being used in comparison, sort or search operations, the Date fields will not be validated during the comparison. |
5-36
Control-Specification Keywords
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | v When Time fields with a time-format other than *USA are being used in comparison, sort or search operations, the Time fields not be validated during the comparison. v When Date, Time, or Timestamp data is being assigned, and the formats and separators of the source and target are the same, the source will not be validated before the assignment. This applies to assignment operations, assignments to temporary values for parameters passed by constant reference and parameters passed by value, the RETURN operation, field moves for Input specifications, and field moves for Output specifications. v When Date, Time, or Timestamp data is being compared for Match Field or Control Level processing, the data will not be validated if it has *ISO format. CAUTION: When validation is not done, incorrect data will not be detected. Use this keyword only if you are confident that the data in all your date, time, and timestamp fields is always valid. For example, if you have a data structure that has the default initialization of blanks, the date, time, and timestamp subfields will be initialized with the invalid value of blanks. If you specify VALIDATE(*NODATETIME), and use any of these subfields, the invalid data will be used in the operation, and it may be propagated to other fields in your program through assignments, or you may get meaningless results for comparison operations. This warning applies even for Date, Time and Timestamp operations that do not appear in the list of the validations that will be omitted. In the future, additional validations may be omitted when VALIDATE(*NODATETIME) is specified. Recommendations: v If you are confident that your Date, Time and Timestamp data is always valid, then Where possible, use the *ISO or *JIS format for Date fields, and a format other than *USA for Time fields. This will allow operations involving comparisons and assignment to be done as though the data were alphanumeric. Otherwise, use the same format for all Date and Time fields where possible. This will allow operations involving assignment to be done as though the data were alphanumeric. v If you are not confident that your Date, Time and timestamp data is always valid, do not specify the VALIDATE(*NODATETIME) keyword. This keyword is only intended to eliminate unnecessary validations. It is not intended to allow incorrect Date, Time, or Timestamp data to be used without error.
5-37
Control Specifications
| You can specify file specifications in two different formats: | v Free-Form File Definition Statement | v Traditional File Description Specification Statement on page 5-40 The following limitations apply: v Only one primary file can be specified. It must be specified as a global file. The presence of a primary file is not required. v Only one record-address file is a allowed in a module; it must be defined as a global file. v A maximum of eight PRINTER files is allowed for global files defined in the main source section, and a maximum of eight local PRINTER files is allowed in each procedure. v There is no limit for the maximum number of files allowed. v Local files defined in subprocedures must be full-procedural files. v Files defined in subprocedures do not have Input and Output specifications, so all input and output must be done using data structures. |
| A free-form file definition statement begins with DCL-F, followed by the file name, followed by | keywords, and ended with a semicolon. | If the file name is longer than 10 characters, the EXTDESC keyword must be used. See Rules for File | Names on page 3-94 for more information about how the file name is used at compile-time and | run-time. | The device of a file defaults to the DISK device, with the *EXT parameter indicating that it is an | externally-described file. If you want to specify a different device, or if you want to explicitly specify the | DISK device, you must specify a file-device keyword as the first keyword. | If you want to define the file like another file, you must specify the LIKEFILE keyword as the first | keyword. | The file is opened for input, update, output, or delete, according to the USAGE keyword. | Specify the file as a keyed file using the KEYED keyword. | The only directives that are allowed within a free-form file statement are /IF, /ELSEIF, /ELSE, and | /ENDIF. | The following example shows the definition of several files. | 1. File file1a and file1b are both externally-described DISK files opened for input. The device-type and usage are determined by default for file file1a, while they are specified explicitly for file1b. | | 2. File file2 is an externally-described PRINTER file opened for output. The usage is determined by default. | | 3. File file3 is an externally-described SEQ file opened for input. The usage is determined by default. | 4. File file4 is an externally-described WORKSTN file opened for input and output. The usage is determined by default. | | 5. File file5 is an externally-described keyed DISK file opened for input and update. | DCL-F file1a; 1 | DCL-F file1b DISK(*EXT) USAGE(*INPUT); | | DCL-F file2 PRINTER; 2 | | DCL-F file3 SEQ; 3
5-38
4 5
I T
Device-type Keywords
v DISK{(*EXT | record-length)} on page 5-53 v SEQ{(*EXT | record-length)} on page 5-69 v PRINTER{(*EXT | record-length)} on page 5-66 v SPECIAL{(*EXT | record-length)} on page 5-70 v WORKSTN{(*EXT | record-length)} on page 5-73
| | | | |
I I
File Type F F
Specifications
5-39
| | | | | | | | | | | | | | | | | | | | | | | | | |
U U
File Type F F
In fixed form, Update implies that the file is also Delete-capable. In free form, *DELETE must be explicitly specified for the file to be Delete-capable. If you do not want the file to be Delete-capable, omit *DELETE. USAGE(*OUTPUT) is the default for PRINTER
O O C I or U I or U I or C F P A
Output
USAGE(*OUTPUT)
Output with file addition Not supported in free-form Combined Full-procedural USAGE(*INPUT : *OUTPUT) USAGE(*INPUT : *OUTPUT) is the default for WORKSTN
Input or Update Primary Not supported in free-form file Input or Update Secondary file Not supported in free-form
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 ...+... 9 ...+... 10 FFilename++IPEASFRlen+LKlen+AIDevice+.Keywords+++++++++++++++++++++++++++++Comments++++++++++++ Figure 5-6. File Description Specification Layout
5-40
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 ...+... 9 ...+... 10 F.....................................Keywords+++++++++++++++++++++++++++++Comments++++++++++++ Figure 5-7. File-Description Keyword Continuation Line Layout
Entry | |
Explanation
A valid file name Every file used in a program or procedure must have a unique name. The file name can be from 1 to 10 characters long, and must begin in position 7. See Rules for File Names on page 3-94 for more information about how the file name is used at compile-time and run-time.
| | | | | | | | | | | | | | | | | | | | |
Program-Described File: For program-described files, the file name specified on the file definition must also be entered on: v Input specifications if the file is a global primary, secondary, or full procedural file v Output specifications or an output calculation operation line if the file is an output, update, or combined file, or if file addition is specified for the file v Definition specifications if the file is a table or array file. v Calculation specifications if the file name is required for the operation code specified Externally-Described File: For externally described files, if the EXTDESC keyword is not specified, the file name specified on the file definition is the name used to locate the record descriptions for the file. The following rules apply to externally described files: v Input and output specifications for externally described files are optional. They are required only if you are adding RPG IV functions, such as control fields or record identifying indicators, to the external description retrieved. v When an external description is retrieved, the record definition can be referred to by its record format name on the input, output, or calculation specifications. If the file is qualified, due to the QUALIFIED or LIKEFILE keywords, the qualified record format is referred to by both the file and record format, for example MYFILE.MYFMT. v A record format name must be a unique symbolic name. If the file is qualified, due to the QUALIFIED or LIKEFILE keyword, the name of record format must be unique to the other formats of the file. If the file is not qualified, the name of the record format must be unique to the other names within the module.
Specifications
5-41
This entry must be blank if the LIKEFILE keyword is specified. The File Type of the parent file is used. Entry I O U C Explanation Input file Output file Update file Combined (input/output) file.
Input Files: An input file is one from which a program reads information. It can contain data records, arrays, or tables, or it can be a record-address file. Output Files: An output file is a file to which information is written. Update Files: An update file is an input file whose records can be read and updated. Updating alters the data in one or more fields of any record contained in the file and writes that record back to the same file from which it was read. If records are to be deleted, the file must be specified as an update file. Combined Files: A combined file is both an input file and an output file. When a combined file is processed, the output record contains only the data represented by the fields in the output record. This differs from an update file, where the output record contains the input record modified by the fields in the output record. A combined file is valid for a SPECIAL or WORKSTN file. A combined file is also valid for a DISK or SEQ file if position 18 contains T (an array or table replacement file).
This entry must be blank if the LIKEFILE keyword is specified. The File Designation of the parent file is used. Entry Explanation
Blank Output file P S R T F Primary file Secondary file Record address file Array or table file Full procedural file
You cannot specify P, S, or R if the keyword MAIN or NOMAIN is specified on a control specification. Primary File: When several files are processed by cycle processing, one must be designated as the primary file. In multi-file processing, processing of the primary file takes precedence. Only one primary file is allowed per program.
5-42
Entry E
Explanation All records from the file must be processed before the program can end. This entry is not valid for files processed by a record-address file. All records from all files which use this option must be processed before the LR indicator is set on by the RPG cycle to end the program.
Blank If position 19 is blank for all files, all records from all files must be processed before end of program (LR) can occur. If position 19 is not blank for all files, all records from this file may or may not be processed before end of program occurs in multi-file processing. Use position 19 to indicate whether the program can end before all records from the file are processed. An E in position 19 applies only to input, update, or combined files specified as primary, secondary, or record-address files. If the records from all primary and secondary files must be processed, position 19 must be blank for all files or must contain E's for all files. For multiple input files, the end-of-program (LR) condition occurs
Specifications
5-43
Position 20 indicates whether records are to be added to an input or update file. For output files, this entry is ignored. This entry must be blank if the LIKEFILE keyword is specified. Entry Explanation
Blank No records can be added to an input or update file (see the USAGE keyword for a free-form file definition or position 17 for a fixed-form file definition)). A Records are added to an input or update file when positions 18 through 20 of the output record specifications for the file contain "ADD", or when the WRITE operation code is used in the calculation specification.
See Positions 18-20 (Record Addition/Deletion) on page 5-177 for the relationship between position 17 and position 20 of the file description specifications and positions 18 through 20 of the output specifications.
Position 21 (Sequence)
| | |
Free-Form Syntax (Not supported for a free-form file definition)
Entry
Explanation
A or blank Match fields are in ascending sequence. D Match fields are in descending sequence.
Position 21 specifies the sequence of input fields used with the match fields specification (positions 65 and 66 of the input specifications). Position 21 applies only to input, update, or combined files used as primary or secondary files. Use positions 65 and 66 of the input specifications to identify the fields containing the sequence information. If more than one input file with match fields is specified in the program, a sequence entry in position 21 can be used to check the sequence of the match fields and to process the file using the matching record technique. The sequence need only be specified for the first file with match fields specified. If sequence is specified for other files, the sequence specified must be the same; otherwise, the sequence specified for the first file is assumed.
5-44
This entry must be blank if the LIKEFILE keyword is specified. The File Format of the parent file is used. Entry F E Explanation Program-described file Externally described file
An F in position 22 indicates that the records for the file are described within the program on input/output specifications (except for array/table files and record-address files). An E in position 22 indicates that the record descriptions for the file are external to the RPG IV source program. The compiler obtains these descriptions at compilation time and includes them in the source program.
This entry must be blank if the LIKEFILE keyword is specified. The Record Length of the parent file is used. Use positions 23 through 27 to indicate the length of the logical records contained in a program-described file. The maximum record size that can be specified is 32766; however, record-size constraints of any device may override this value. This entry must be blank for externally described files. If the file being defined is a record-address file and the record length specified is 3, it is assumed that each record in the file consists of a 3-byte binary field for the relative-record numbers starting at offset 0. If the record length is 4 or greater, each relative-record number in the record-address file is assumed to be a 4-byte field starting at offset 1. If the record length is left blank, the actual record length is retrieved at run time to determine how to handle the record-address file. If the file opened at run time has a primary record length of 3, then 3-byte relative-record numbers (one per record) are assumed; otherwise, 4-byte relative-record numbers are assumed. This support can be used to allow ILE RPG programs to use System/36 environment SORT files as record-address files.
Table 5-7. Valid Combinations for a Record Address File containing Relative Record Numbers (RAFRRN) Record Length Positions 23-27 Blank 3 >=4 RAF Length Positions 29-33 Blank 3 4 Type of Support Support determined at run time. System/36 support. Native support.
Specifications
5-45
Entry L
Blank Sequential or random processing Use position 28 to indicate whether the file is processed by a record-address file that contains limits records. A record-address file used for limits processing contains records that consist of upper and lower limits. Each record contains a set of limits that consists of the lowest record key and the highest record key from the segment of the file to be processed. Limits processing can be used for keyed files specified as primary, secondary, or full procedural files. The L entry in position 28 is valid only if the file is processed by a record-address file containing limits records. Random and sequential processing of files is implied by a combination of positions 18 and 34 of the file description specifications, and by the calculation operation specified. The operation codes SETLL (Set Lower Limit) on page 6-298 and SETGT (Set Greater Than) on page 6-295 can be used to position a file; however, the use of these operation codes does not require an L in this position. For more information on limits processing, refer to the Rational Development Studio for i: ILE RPG Programmer's Guide.
This entry must be blank if the LIKEFILE keyword is specified. The Length of Key of the parent file is used. Entry Explanation
1-2000 The number of positions required for the key field in a program described file or the length of the entries in the record-address file (which must be a program-described file). If the program-described file being defined uses keys for record identification, enter the number of positions occupied by each record key. This entry is required for indexed files. If the keys are packed, the key field length should be the packed length; this is the number of digits in DDS divided by 2 plus 1 and ignoring any fractions. If the file being defined is a record-address file, enter the number of positions that each entry in the record-address file occupies. If the keys are graphic, the key field length should be specified in bytes (for example, 3 graphic characters requires 6 bytes). Blank These positions must be blank for externally described files. (The key length is specified in the external description.) For a program-described file, a blank entry indicates that keys are not used. Positions 29-33 can also be blank for a record-address file with a blank in positions 23-27 (record length).
5-46
This entry must be blank if the LIKEFILE keyword is specified. The Record Address Type of the parent file is used. Entry Explanation
Blank Relative record numbers are used to process the file. Records are read consecutively. Record address file contains relative-record numbers. For limits processing, the record-address type (position 34) is the same as the type of the file being processed. A P G K D T Z F Character keys (valid only for program-described files specified as indexed files or as a record-address-limits file). Packed keys (valid only for program-described files specified as indexed files or as a record-address-limits file). Graphic keys (valid only for program-described files specified as indexed files or as a record-address-limits file). Key values are used to process the file. This entry is valid only for externally described files. Date keys are used to process the file. This entry is valid only for program-described files specified as indexed files or as a record-address-limits file. Time keys are used to process the file. This entry is valid only for program-described files specified as indexed files or as a record-address-limits file. Timestamp Keys are used to process the file. This entry is valid only for program-described files specified as indexed files or as a record-address-limits file. Float Key (valid only for program-described files specified as indexed files or as a record-address-limits file).
UCS-2 fields are not allowed as the record address type for program described indexed files or record address files. Blank=Non-keyed Processing: A blank indicates that the file is processed without the use of keys, that the record-address file contains relative-record numbers (a T in position 35), or that the keys in a record-address-limits file are in the same format as the keys in the file being processed. A file processed without keys can be processed consecutively or randomly by relative-record number. Input processing by relative-record number is determined by a blank in position 34 and by the use of the CHAIN, SETLL, or SETGT operation code. Output processing by relative-record number is determined by a blank in position 34 and by the use of the RECNO keyword on the file description specifications. A=Character Keys: The indexed file (I in position 35) defined on this line is processed by character-record keys. (A numeric field used as the search argument is converted to zoned decimal before chaining.) The A entry must agree with the data format of the field identified as the key field (length in positions 29 to 33 and starting position specified as the parameter to the KEYLOC keyword). The record-address-limits file (R in position 18) defined on this line contains character keys. The file being processed by this record address file can have an A, P, or K in position 34.
Specifications
5-47
5-48
Blank The program-described file is processed without keys, or the file is externally described. I T | Indexed file (valid only for program-described files). Record address file that contains relative-record numbers (valid only for program-described files). Note: Record address files are not supported in free-form file definitions Use position 35 to identify the organization of program described files. Blank=Non-keyed Program-Described File: A program-described file that is processed without keys can be processed: v Randomly by relative-record numbers, positions 28 and 34 must be blank. v Entry Sequence, positions 28 and 34 must be blank. v As a record-address file, position 28 must be blank. I=Indexed File: An indexed file can be processed: v Randomly or sequentially by key v By a record-address file (sequentially within limits). Position 28 must contain an L. T=Record Address File: A record-address file (indicated by an R in position 18) that contains relative-record numbers must be identified by a T in position 35. (A record-address file must be program described.) Each record retrieved from the file being processed is based on the relative record number in the record-address file. (Relative record numbers cannot be used for a record-address-limits file.) Each relative-record number in the record-address file is a 4-byte binary field; therefore, each 4-byte unit of a record-address file contains a relative-record number. A minus one (-1 or hexadecimal FFFFFFFF ) relative-record number value causes the record to be skipped. End of file occurs when all record-address file records have been processed. For more information on how to handle record-address files, see the Rational Development Studio for i: ILE RPG Programmer's Guide.
This entry must be blank if the LIKEFILE keyword is specified. The Device entry of the parent file is used. Use positions 36 through 42 to specify the RPG IV device name to be associated with the file. The file name specified in positions 7 through 16 can be overridden at run time, allowing you to change the input/output device used in the program. | | | | | | Note that the RPG IV device names are not the same as the system device names. File device types: PRINTER The file is a printer file, a file with control characters that can be sent to a printer. DISK The file is a disk file. This device supports sequential and random read/write functions. These files can be accessed on a remote system by Distributed Data Management (DDM).
Specifications
5-49
Position 43 (Reserved)
Position 43 must be blank.
Positions 44 to 80 are provided for file-description-specification keywords. Keywords are used to provide additional information about the file being defined.
File-Description Keywords
File-Description keywords may have no parameters, optional parameters, or required parameters. The syntax for keywords is as follows:
Keyword(parameter1 : parameter2)
where: v Parameter(s) are enclosed in parentheses ( ). Note: Do not specify parentheses if there are no parameters. v Colons (:) are used to separate multiple parameters. The following notational conventions are used to show which parameters are optional and which are required: v Braces { } indicate optional parameters or optional elements of parameters. v An ellipsis (...) indicates that the parameter can be repeated. v A colon (:) separates parameters and indicates that more than one may be specified. All parameters separated by a colon are required unless they are enclosed in braces. v A vertical bar (|) indicates that only one parameter may be specified for the keyword. v A blank separating keyword parameters indicates that one or more of the parameters may be specified. Note: Braces, ellipses, and vertical bars are not a part of the keyword syntax and should not be entered into your source. If additional space is required for file-description keywords, the keyword field can be continued on subsequent lines. See File-Description Keyword Continuation Line on page 5-40 and File Description Specification Keyword Field on page 5-9. # ALIAS # When the ALIAS keyword is specified for an externally-described file, the RPG compiler will use the alias # (alternate) names, if present, when determining the subfield names for data structures defined with the
5-50
File-Description Keywords
# LIKEREC keyword. When the ALIAS keyword is not specified for the RPG file, or an external field does # not have an alias name defined, the RPG compiler will use the standard external field name. # Note: If the alternate name for a particular external field is enclosed in quotes, the standard external field # name is used for that field. # The ALIAS keyword is allowed for an externally-described file for which the RPG compiler will not # generate Input or Output specifications. This includes files defined with the TEMPLATE or QUALIFIED # keyword, and local files defined in subprocedures. # # # # When the PREFIX keyword is specified with the ALIAS keyword, the second parameter of PREFIX, indicating the number of characters to be replaced, does not apply to the alias names. In the following discussion, assume that the file MYFILE has fields XYCUSTNM and XYID_NUM, and the XYCUSTNM field has the alias name CUSTOMER_NAME. v If keyword PREFIX(NEW_) is specified, there is no second parameter, so no characters are replaced for any names. The names used for LIKEREC subfields will be NEW_CUSTOMER_NAME and NEW_XYID_NUM. v If keyword PREFIX(NEW_:2) is specified, two characters will be replaced in the names of fields that do not have an alias name. The names used for LIKEREC subfields will be NEW_CUSTOMER_NAME and NEW_ID_NUM. The first two characters, "XY", are replaced in XYID_NUM, but no characters are replaced in CUSTOMER_NAME.
# # # # # # # # v If keyword PREFIX('':2) is specified, two characters will be repaced in the names of fields that do not # have an alias name. The names used for LIKEREC subfields will be CUSTOMER_NAME and ID_NUM. # The first two characters, "XY", are replaced in XYID_NUM, but no characters are replaced in # CUSTOMER_NAME. # v If the first parameter for PREFIX contains a data structure name, for example PREFIX('MYDS.'), the # part of the prefix before the dot will be ignored. # # * The DDS specifications for file MYFILE, using the ALIAS keyword * for the first field to associate the alias name CUSTOMER_NAME # * with the CUSTNM fieldA R CUSTREC # CUSTNM 25A ALIAS(CUSTOMER_NAME) # A ID_NUM 12P 0 # A # * The RPG source, using the ALIAS keyword: # if e disk ALIAS QUALIFIED * The subfields of the LIKEREC data structure are # Fmyfile * CUSTOMER_NAME (using the ALIAS name) # * ID_NUM (using the standard name) # ds LIKEREC(myfile.custRec) # D myDs /free # read myfile myDs; # if myDs.customer_name <> *blanks # and myDs.id_num > 0; # ... # # # # Figure 5-8. Using the ALIAS keyword for an externally-described file #
BLOCK(*YES |*NO)
The BLOCK keyword controls the blocking of records associated with the file. The keyword is valid only for DISK or SEQ files. If this keyword is not specified, the RPG compiler unblocks input records and blocks output records to improve run-time performance in SEQ or DISK files when the following conditions are met: 1. The file is program-described or, if externally described, it has only one record format. 2. Keyword RECNO is not used in the file description specification.
Specifications
5-51
File-Description Keywords
Note: If RECNO is used, the ILE RPG compiler will not allow record blocking. However, if the file is an input file and RECNO is used, Data Management may still block records if fast sequential access is set. This means that updated records might not be seen right away. 3. One of the following is true: a. The file is an output file. b. If the file is a combined file, then it is an array or table file. c. The file is an input-only file; it is not a record-address file or processed by a record-address file; and none of the following operations are used on the file: READE, READPE, SETGT, SETLL, and CHAIN. (If any READE or READPE operations are used, no record blocking will occur for the input file. If any SETGT, SETLL, or CHAIN operations are used, no record blocking will occur unless the BLOCK(*YES) keyword is specified for the input file.) If BLOCK(*YES) is specified, record blocking occurs as described above except that the operations SETLL, SETGT, and CHAIN can be used with an input file and blocking will still occur (see condition 3c above). To prevent the blocking of records, BLOCK(*NO) can be specified. Then no record blocking is done by the compiler.
COMMIT{(rpg_name)}
The COMMIT keyword allows the processing of files under commitment control. An optional parameter, rpg_name, may be specified. The parameter is implicitly defined as a field of type indicator (that is, a character field of length one), and is initialized by RPG to '0'. By specifying the optional parameter, you can control at run time whether to enable commitment control. If the parameter contains a '1', the file will be opened with the COMMIT indication on, otherwise the file will be opened without COMMIT. The parameter must be set prior to opening the file. If the file is opened at program initialization, the COMMIT parameter can be passed as a call parameter or defined as an external indicator. If the file is opened explicitly, using the OPEN operation in the calculation specifications, the parameter can be set prior to the OPEN operation. Use the COMMIT and ROLBK operation codes to group changes to this file and other files currently under commitment control so that changes all happen together, or do not happen at all. Note: If the file is already open with a shared open data path, the value for commitment control must match the value for the previous OPEN operation.
DATFMT(format{separator})
The DATFMT keyword allows the specification of a default external date format and a default separator (which is optional) for all date fields in the program-described file. If the file on which this keyword is specified is indexed and the key field is a date, then this also provides the default external format for the key field. For a Record-Address file this specifies the external date format of date limits keys read from the record-address file. You can specify a different external format for individual input or output date fields in the file by specifying a date format/separator for the field on the corresponding input specification (positions 31-35) or output specification (positions 53-57). See Table 4-3 on page 4-73 for valid formats and separators. For more information on external formats, see Internal and External Formats on page 4-49.
DEVID(fieldname)
The DEVID keyword specifies the name of the program device that supplied the record processed in the file. The field is updated each time a record is read from a file. Also, you may move a program device
5-52
File-Description Keywords
name into this field to direct an output or device-specific input operation (other than a READ-by-file-name or an implicit cycle read) to a different device. The fieldname is implicitly defined as a 10-character alphanumeric field. The device name specified in the field must be left-justified and padded with blanks. Initially, the field is blank. A blank field indicates the requester device. If the requester device is not acquired for your file, you must not use a blank field. The DEVID field is maintained for each call to a program. If you call program B from within program A, the DEVID field for program A is not affected. Program B uses a separate DEVID field. When you return to program A, its DEVID field has the same value as it had before you called program B. If program B needs to know which devices are acquired to program A, program A must pass this information (as a parameter list) when it calls program B. If the DEVID keyword is specified but not the MAXDEV keyword, the program assumes a multiple device file (MAXDEV with a parameter of *FILE). To determine the name of the requester device, you may look in the appropriate area of the file information data structure (see File Information Data Structure on page 3-68). Or, you may process an input or output operation where the fieldname contains blanks. After the operation, the fieldname has the name of the requester device. | | | | | | | | | |
DISK{(*EXT | record-length)}
The DISK keyword is a device-type keyword. It is used in a free-form file definition to indicate that the file device is DISK. It must be the first keyword. The parameter is optional. It defaults to *EXT. *EXT Specify *EXT to indicate that the file is externally described. This is the default. record-length Specify a record-length to indicate that the file is program described. The record length must be between 1 and 32766. It can be a literal or a named constant. If it is a named constant, the constant must be defined prior to the file definition statement.
EXTDESC(external-filename)
The EXTDESC keyword can be specified to indicate which file the compiler should use at compile time to obtain the external descriptions for the file. The file specified by the EXTDESC keyword is used only at compile time. At runtime, the file is found using the same rules as would be applied if the EXTDESC keyword was not specified. You can use additional keyword EXTFILE(*EXTDESC) if you also want the file specified by the EXTDESC keyword to be used at runtime. The EXTDESC keyword must be specified before any keywords that have record format names as parameters such as IGNORE, INCLUDE, RENAME, and SFILE, and before any keywords whose validity depends on the actual file, such as INDDS and SLN. The parameter for EXTDESC must be a literal specifying a valid file name. You can specify the value in any of the following forms:
filename libname/filename *LIBL/filename
Note: 1. You cannot specify *CURLIB as the library name. 2. If you specify a file name without a library name, *LIBL is used.
Specifications
5-53
File-Description Keywords
3. The name must be in the correct case. For example, if you specify EXTDESC('qtemp/myfile'), the file will not be found. Instead, you should specify EXTDESC('QTEMP/MYFILE'). 4. If you have specified an override for the file that RPG will use for the external descriptions, that override will be in effect. If the EXTDESC('MYLIB/MYFILE') is specified, RPG will use the file MYLIB/MYFILE for the external descriptions. If the command OVRDBF MYFILE OTHERLIB/OTHERFILE has been used before compiling, the actual file used will be OTHERLIB/OTHERFILE. Note that any overrides for the name specified in positions 7-15 will be ignored, since that name is only used internally within the RPG source member.
* At compile time, file MYLIB/MYFILE1 will be used to * get the definition for file "FILE1", as specified by * the EXTDESC keyword. * At runtime, file *LIBL/FILE1 will be opened. Since * the EXTFILE keyword is not specified, the file name * defaults to the RPG name for the file. Ffile1 if e disk F extdesc(MYLIB/MYFILE1) * At compile time, file MYLIB/MYFILE2 will be used to * get the definition for file "FILE2", as specified by * the EXTDESC keyword. * At runtime, file MYLIB/MYFILE2 will be opened, as * specified by the EXTFILE(*EXTDESC) keyword. Ffile2 if e disk F extdesc(MYLIB/MYFILE2) F extfile(*extdesc) Figure 5-9. Example of the EXTDESC keyword.
EXTFILE(filename | *EXTDESC)
The EXTFILE keyword specifies which file, in which library, is opened. filename can be a literal or a variable. You can specify the value in any of the following forms:
filename libname/filename *LIBL/filename
Special value *EXTDESC can be used to indicate that the parameter for the EXTDESC keyword should also be used for the EXTFILE keyword. Note: 1. You cannot specify *CURLIB as the library name. 2. If you specify a file name without a library name, *LIBL is used. 3. The name must be in the correct case. For example, if you specify EXTFILE(filename) and variable filename has the value qtemp/myfile, the file will not be found. Instead, it should have the value QTEMP/MYFILE. 4. This keyword is not used to find an externally-described file at compile time. Use the EXTDESC keyword to locate the file at compile-time. # 5. When EXTFILE(*EXTDESC) is specified, the EXTDESC keyword must also be specified for the file, or # for the parent file if the file is defined with the LIKEFILE keyword. 6. If a variable name is used, it must be set before the file is opened. For files that are opened automatically during the initialization part of the cycle, the variable must be set in one of the following ways: v Using the INZ keyword on the D specification v Passing the value in as an entry parameter v Using a program-global variable that is set by another module.
5-54
File-Description Keywords
If you have specified an override for the file that RPG will open, that override will be in effect. In the following code, for the file named INPUT within the RPG program, the file that is opened at runtime depends on the value of the filename field.
Finput if f 10 disk extfile(filename)
If the filename field has the value MYLIB/MYFILE at runtime, RPG will open the file MYLIB/MYFILE. If the command OVRDBF MYFILE OTHERLIB/OTHERFILE has been used, the actual file opened will be OTHERLIB/OTHERFILE. Note that any overrides for the name INPUT will be ignored, since INPUT is only the name used within the RPG source member.
* The name of the file is known at compile time Ffile1 IF F 10 DISK EXTFILE(MYLIB/FILE1) Ffile2 IF F 10 DISK EXTFILE(FILE2) * The name of the file is in a variable which is * in the correct form when the program starts. * Variable "filename3" must have a value such as * MYLIB/MYFILE or MYFILE when the file is * opened during the initialization phase of the * RPG program. Ffile3 IF F 10 DISK EXTFILE(filename3) * The library and file names are in two separate variables * The USROPN keyword must be used, so that the "filename4" * variable can be set correctly before the file is opened. Ffile4 IF F 10 DISK EXTFILE(filename4) F USROPN D filename4 S 21A * EXTFILE variable "filename4" is set to the concatenated * values of the "libnam" and "filnam" variables, to form * a value in the form "LIBRARY/FILE". C EVAL filename4 = %trim(libnam) + / + filnam C OPEN file4 * At compile time, file MYLIB/MYFILE5 will be used to * get the external definition for the file "file5", * due to the EXTDESC keyword. * At runtime, the file MYLIB/MYFILE5 will be opened, * due to the EXTFILE(*EXTDESC) keyword. Ffile5 if e DISK F EXTFILE(*EXTDESC) F EXTDESC(MYLIB/MYFILE5) Figure 5-10. Examples of the EXTFILE keyword
EXTIND(*INUx)
The EXTIND keyword indicates whether the file is used in the program depending on the value of the external indicator. EXTIND lets the programmer control the operation of input, output, update, and combined files at run time. If the specified indicator is on at program initialization, the file is opened. If the indicator is not on, the file is not opened and is ignored during processing. The *INU1 through *INU8 indicators can be set as follows: v By the IBM i control language. v When used as a resulting indicator for a calculation operation or as field indicators on the input specifications. Setting the *INU1 through *INU8 indicators in this manner has no effect on file conditioning. See also USROPN on page 5-72.
Specifications
5-55
File-Description Keywords
EXTMBR(membername)
The EXTMBR keyword specifies which member of the file is opened. You can specify a member name, *ALL, or *FIRST. Note that '*ALL' and '*FIRST' must be specified in quotes, since they are member "names", not RPG special words. The value can be a literal or a variable. The default is *FIRST. The name must be in the correct case. For example, if you specify EXTMBR(mbrname) and variable mbrname has the value mbr1, the member will not be found. Instead, it should have the value MBR1. If a variable name is used, it must be set before the file is opened. For files that are opened automatically during the initialization part of the cycle, the variable must be set in one of the following ways: v Using the INZ keyword on the D specification v Passing the value in as an entry parameter v Using a program-global variable that is set by another module.
FORMLEN(number)
The FORMLEN keyword specifies the form length of a PRINTER file. The form length must be greater than or equal to 1 and less than or equal to 255. The parameter specifies the exact number of lines available on the form or page to be used. Changing the form length does not require recompiling the program. You can override the number parameter of FORMLEN by specifying a new value for the PAGSIZE parameter of the Override With Printer File (OVRPRTF) command. When the FORMLEN keyword is specified, the FORMOFL keyword must also be specified.
FORMOFL(number)
The FORMOFL keyword specifies the overflow line number that will set on the overflow indicator. The overflow line number must be less than or equal to the form length. When the line that is specified as the overflow line is printed, the overflow indicator is set on. Changing the overflow line does not require recompiling the program. You can override the number parameter of FORMOFL by specifying a new value for the OVRFLW parameter of the Override With Printer File (OVRPRTF) command. When the FORMOFL keyword is specified, the FORMLEN keyword must also be specified. | HANDLER(program-or-procedure { : communication-area)}) | The HANDLER keyword indicates that the file is an Open Access file. It can be specified for files with | device DISK, PRINTER, SEQ, or WORKSTN. | The first parameter specifies the program or procedure that handles the input and output operations for | the file. It can be specified in the following ways: | v A character literal containing the name of a program or a library-qualified program. The names are | case-sensitive. | MYPGM | *LIBL/MYPGM | MYLIB/MYPGM | For example, the handler for this file is program *LIBL/MYPGM. | #
DCL-F myfile HANDLER(MYPGM);
5-56
File-Description Keywords
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | v A character literal containing the name of a procedure in a service program. The service program is specified first either as simply a service-program name, or a library-qualified service program name. The service program is followed by the name of the procedure in parentheses. The names are case-sensitive.
MYSRVPGM(myProcecedure) *LIBL/MYSRVPGM(myProcedure) MYLIB/MYSRVPGM(myProcedure)
For example, the handler for this file is procedure MyProc in service program MYLIB/MYSRVPGM.
DCL-F myfile HANDLER(MYLIB/MYSRVPGM(MyProc));
v A character variable holding the name of a program or a procedure in a service program. For example, the handler for this file is character variable handlerName. The file is opened twice with different handlers.
DCL-F myfile HANDLER(handlerName) USROPN; DCL-S handlerName CHAR(50); handlerName = MYLIB/MYPGM; OPEN myfile; READ myfile; CLOSE myfile; handlerName = MYLIB/MYSRVPGM(myHandler); OPEN myfile; READ myfile; CLOSE myfile;
v A procedure pointer. For example, the handler for this file is procedure pointer handlerPointer. The file is opened twice with different handlers.
DCL-F myfile HANDLER(handlerPointer) USROPN; DCL-S handlerPointer POINTER(*PROC); handlerPointer = %PADDR(proc_a); OPEN myfile; READ myfile; CLOSE myfile; handlerPointer = %PADDR(proc_b); OPEN myfile; READ myfile; CLOSE myfile;
v A prototype name. For example, the handler for this file is prototype myHandler.
Specifications
5-57
File-Description Keywords
| | | | | |
DCL-F myfile HANDLER(myproc); /COPY QOAR/QRPGLESRC,QRNOPENACC DCL-PR myproc; parm LIKEDS(QrnOpenAccess_T); END-PR;
| Note: | v If the first parameter is a variable, it must be set before the file is opened. | v If the handler procedure is in the same module as the Open Access file, the file must be defined with the USROPN keyword. | | The second parameter is optional. It specifies a variable that is passed to the handler to allow the RPG | program to share additional information directly with the handler. | In the following example, the handler expects the communication area to be a data structure with a | 10-character option subfield. | | | | | | | | | | | | | | | | | | | | Note: It is up to the RPG programmer to define the communication area variable the way the handler expects it. Usually, a copy file would be used to define a template data structure for the communication area. See Example of an Open Access Handler on page 3-97 for a complete example of an Open Access file that shows how to use a copy file to ensure that the RPG program and the handler use the same definition for the communication area.
DCL-F myfile HANDLER(MYPGM : options) USROPN; DCL-DS options QUALIFIED; detail CHAR(10); END-DS; options.detail = FULL; OPEN myfile; . . . CLOSE myfile; options.detail = NONE; OPEN myfile; . . .
IGNORE(recformat{:recformat...})
The IGNORE keyword allows a record format from an externally described file to be ignored. The external name of the record format to be ignored is specified as the parameter recformat. One or more record formats can be specified, separated by colons (:). The program runs as if the specified record format(s) did not exist. All other record formats contained in the file will be included. When the IGNORE keyword is specified for a file, the INCLUDE keyword cannot be specified. Remember that for a qualified file, the unqualified form of the record format name is used for the IGNORE keyword.
INCLUDE(recformat{:recformat...})
The INCLUDE keyword specifies those record format names that are to be included; all other record formats contained in the file will be ignored. For WORKSTN files, the record formats specified using the SFILE keyword are also included in the program, they need not be specified twice. Multiple record formats can be specified, separated by colons (:).
5-58
File-Description Keywords
When the INCLUDE keyword is specified for a file, the IGNORE keyword cannot be specified. Remember that for a qualified file, the unqualified form of the record format name is used for the INCLUDE keyword.
INDDS(data_structure_name)
The INDDS keyword 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. Rules: v This keyword is allowed only for externally described PRINTER files and externally and program-described WORKSTN files. v For a program-described file, the PASS(*NOIND) keyword must not be specified with the INDDS keyword. v The same data structure name may be associated with more than one file. v The data structure name must be defined as a data structure on the definition specifications and can be a multiple-occurrence data structure. v The length of the indicator data structure is always 99. v The indicator data structure is initialized by default to all zeros ('0's). v The SAVEIND keyword cannot be specified with this keyword. If this keyword is not specified, the *IN array is used to communicate indicator values for all files defined with the DDS keyword INDARA. For additional information on indicator data structures, see Special Data Structures on page 4-15.
INFDS(DSname)
The INFDS keyword lets you define and name a data structure to contain the feedback information associated with the file. The data structure name is specified as the parameter for INFDS. If INFDS is specified for more than one file, each associated data structure must have a unique name. An INFDS must be coded in the same scope as the file; for a global file, it must be coded in the main source section, and for a local file, it must be coded in the same subprocedure as the file. Furthermore, it must have the same storage type, static or automatic, as the file. For additional information on file information data structures, see File Information Data Structure on page 3-68.
INFSR(SUBRname)
The INFSR keyword identifies the file exception/error subroutine that may receive control following file exception/errors. The subroutine name may be *PSSR, which indicates the user-defined program exception/error subroutine is to be given control for errors on this file. The INFSR keyword cannot be specified for a global file that is accessed by a subprocedure. The INFSR subroutine must be coded in the same scope as the file; for a local file, it must be coded in the same subprocedure as the file, and for a global file in a cycle module, it must be coded in the main source section. | | | |
KEYED{(*CHAR : key-length)}
The KEYED keyword is used in a free-form file definition to specify that the file is to be opened in keyed sequence, and that keyed file operations are allowed for the file. For an externally-described file, the KEYED keyword has no parameter.
Specifications
5-59
File-Description Keywords
|
DCL-F file1 DISK(*EXT) KEYED;
| For a program-described file, only alphanumeric keys are supported. The KEYED keyword must have | two parameters, *CHAR and the length of the key. DCL-F file2 DISK(100) KEYED(*CHAR : 10); | | If you want to define a program-described file with a different type of key, you can specify | KEYED(*CHAR:key_length) to define the key as alphanumeric, and use a data structure as the search | argument in keyed operations where the data structure has a subfield of the required data type.
KEYLOC(number)
The KEYLOC keyword specifies the record position in which the key field for a program-described indexed-file begins. The parameter must be between 1 and 32766. The key field of a record contains the information that identifies the record. The key field must be in the same location in all records in the file.
LIKEFILE(parent-filename)
The LIKEFILE keyword is used to define one file like another file. Note: In the following discussion, the term new file is used for the file defined using the LIKEFILE keyword, and the term parent file is used for the parameter of the LIKEFILE keyword whose definition is used to derive the definition of the new file. Rules for the LIKEFILE keyword:: v When a file is defined with the LIKEFILE keyword, the QUALIFIED keyword is assumed. Record formats are automatically qualified for a file defined with the LIKEFILE keyword. If the record formats of the parent file FILE1 are RECA and RECB, then the record formats of the new file FILE2 must be referred to in the RPG program by FILE2.RECA and FILE2.RECB. v The QUALIFIED keyword cannot be specified with the LIKEFILE keyword. v All non-ignored record formats from the parent file are available for the new file. v If the LIKEFILE keyword is specified, the file specified as a parameter must have already been defined in the source file. v If the LIKEFILE keyword is specified in a subprocedure, and the file specified as the parameter is defined in the global definitions, the compiler will locate the global definition at the time of scanning the LIKEFILE definition. v Input and output specifications are not generated or allowed for files defined with LIKEFILE. All input and output operations must be done with result data structures. v When a file is defined with LIKEFILE, the File specifications for the parent file must make it clear whether or not the file is blocked. It may be necessary to specify the BLOCK keyword for the parent file. For example, for an input DISK file, the BLOCK keyword is required if the file is used in a LIKEFILE keyword since the file is blocked depending on which calculation operations are used for the file. For an Input-Add DISK file, the file can never be blocked, so the BLOCK keyword is not required. v If BLOCK(*YES) is specified for a file, and the file is used as a parent file for files defined with the LIKEFILE keyword, the READE, READPE and READP operations are not allowed for the parent file, or for any files related to the parent file through the LIKEFILE keyword. v Some properties of the parent file are inherited by the new file, and some are not. Of the properties which are inherited, some can be overridden by File specification keywords. The properties which are not inherited can be specified for the new file by File specification keywords, see Table 5-8 on page 5-61.
5-60
File-Description Keywords
Table 5-8. File properties which are inherited and which can be overridden Property or keyword File type (Input, update, output, combined) File addition Record address type (RRN, keyed) Record length (Program-described files) Key length (Program-described files) File organization (Program-described files) Device BLOCK COMMIT DATFMT DEVID Inherited from parent file Yes Yes Yes Yes Yes Yes Yes Yes No N/A, see Note 1 No Yes Yes Yes, see Note 2 No Yes, see Note 2 Yes Yes Yes No No Yes Yes Yes Yes Yes Can be specified for new file No No No No No No No No Yes
| |
N/A, the HANDLER keyword is not supported for either the new file or the parent file. Yes Yes No No No Yes Yes Yes Yes No Yes Yes No Yes Yes No No No Yes Yes Yes No No N/A Yes Yes No Yes Yes No No Yes
KEYED KEYLOC
# LIKEFILE
MAXDEV OFLIND PASS PGMNAME PLIST PREFIX
N/A, QUALIFIED is always implied for new file N/A, see Note 3
# RAFDATA
Specifications
5-61
File-Description Keywords
Table 5-8. File properties which are inherited and which can be overridden (continued) Property or keyword Inherited from parent file No Yes No No Yes Yes, see Note 4 No Yes No No N/A, see Note 1 Yes No Yes No Yes No Can be specified for new file Yes No Yes Yes No Yes, see Note 4 Yes No Yes Yes
# RECNO # RENAME
SAVEDS SAVEIND
SEQ
# SFILE
SLN
SPECIAL
# STATIC # TEMPLATE
TIMFMT
| |
Note: 1. The DATFMT and TIMFMT keywords relate to Date and Time fields coded on program-described Input specifications for the file, but Input specifications are not relevant for files defined with the LIKEFILE keyword. 2. The external file associated with the RPG file depends on the EXTFILE and EXTMBR keywords specified for both the parent file and the new file. By default, the external file associated with each file is the name specified in the Name entry for the file. The new file inherits the EXTFILE or EXTMBR keywords from the parent file if the parameters are constants, but these keywords may also be specified for the new file. If the parameter for EXTFILE or EXTMBR is not a constant, the EXTFILE or EXTMBR keyword is not inherited. The following table shows the external files that would be used at runtime for some examples of EXTFILE and EXTMBR values for a parent file and a new file that is defined LIKEFILE the parent file.
Table 5-9. File specification examples: EXTFILE and EXTMBR File Specifications Examples where the EXTFILE and EXTMBR values are both constants FFILE1 FFILE2 FFILE1 FFILE2 FFILE1 FFILE2 FFILE1 FFILE2 FFILE1 FFILE2 FFILE1 FFILE2 FFILE1 FFILE2 IF IF IF IF IF IF IF E E E E E E E DISK LIKEFILE(FILE1) DISK DISK LIKEFILE(FILE1) EXTFILE(MYLIB/MYFILE) DISK DISK DISK LIKEFILE(FILE1) EXTMBR(MBR1) DISK EXTMBR(MBR1) LIKEFILE(FILE1) EXTFILE(MYLIB/MYFILE2) EXTFILE(MYLIB/MYFILE1) LIKEFILE(FILE1) EXTFILE(MYLIB/MYFILE2) EXTMBR(MBR1) LIKEFILE(FILE1) EXTFILE(MYLIB/MYFILE) LIKEFILE(FILE1) *LIBL/FILE1(*FIRST) *LIBL/FILE2(*FIRST) MYLIB/MYFILE(*FIRST) MYLIB/MYFILE(*FIRST) *LIBL/FILE1(*FIRST) MYLIB/MYFILE(*FIRST) MYLIB/MYFILE1(*FIRST) MYLIB/MYFILE2(*FIRST) *LIBL/FILE1(MBR1) *LIBL/FILE2(MBR1) *LIBL/FILE1(*FIRST) *LIBL/FILE2(MBR1) *LIBL/FILE1(MBR1) MYLIB/MYFILE2(MBR1) External files used at runtime (Inherited values appear in bold)
5-62
File-Description Keywords
Table 5-9. File specification examples: EXTFILE and EXTMBR (continued) File Specifications Examples where the EXTFILE and EXTMBR values are both variable FFILE1 IF E DISK EXTFILE(extfileVariable) FFILE2 LIKEFILE(FILE1) Value of extfileVariable: MYLIB/MYFILE FFILE1 IF E DISK FFILE2 LIKEFILE(FILE1) EXTFILE(extfileVariable) Value of extfileVariable: MYLIB/MYFILE FFILE1 IF E DISK EXTFILE(extfileVariable1) FFILE2 LIKEFILE(FILE1) EXTFILE(extfileVariable2) Value of extfileVariable1: MYLIB/MYFILE1 Value of extfileVariable2: MYLIB/MYFILE2 FFILE1 IF E DISK EXTMBR(extmbrVariable) FFILE2 LIKEFILE(FILE1) Value of extmbrVariable: MBR1 FFILE1 IF E DISK FFILE2 LIKEFILE(FILE1) EXTMBR(extmbrVariable) Value of extmbrVariable: MBR1 FFILE1 IF E DISK EXTMBR(extmbrVariable) FFILE2 LIKEFILE(FILE1) EXTFILE(extfileVariable) Value of extmbrVariable: MBR1 Value of extfileVariable: MYLIB/MYFILE2 MYLIB/MYFILE(*FIRST) *LIBL/FILE2(*FIRST) *LIBL/FILE1(*FIRST) MYLIB/MYFILE(*FIRST) MYLIB/MYFILE1(*FIRST) MYLIB/MYFILE2(*FIRST) External files used at runtime (Inherited values appear in bold)
Examples where the EXTFILE and EXTMBR values are mixed variables and constants FFILE1 IF E DISK EXTFILE(extfileVariable1) EXTMBR(MBR1) FFILE2 LIKEFILE(FILE1) Value of extfileVariable1: MYLIB/MYFILE1 FFILE1 IF E DISK EXTMBR(extmbrVariable) FFILE2 LIKEFILE(FILE1) Value of extmbrVariable: MBR1 FFILE1 IF E DISK EXTFILE(MYLIB/MYFILE1) EXTMBR(extmbrVariable) FFILE2 LIKEFILE(FILE1) Value of extmbrVariable: MBR1 MYLIB/MYFILE1(MBR1) *LIBL/FILE2(MBR1) *LIBL/FILE1(MBR1) *LIBL/FILE2(*FIRST) MYLIB/MYFILE1(MBR1) MYLIB/MYFILE1(*FIRST)
3. The RAFDATA keyword is relevant only for Primary and Secondary files, but the parent file must be a Full Procedural file. 4. The SFILE keyword indicates that the record format is a subfile record format, and it also indicates the name of the variable used to specify the relative record number for the subfile. The new file automatically inherits the fact that a particular record format is a subfile record format; however, it does not inherit the name of the variable used to specify the RRN. The SFILE keyword must be specified for the new file to indicate which variable is to be used to specify the relative record number for the subfile.
MAXDEV(*ONLY | *FILE)
The MAXDEV keyword specifies the maximum number of devices defined for the WORKSTN file. The default, *ONLY, indicates a single device file. If *FILE is specified, the maximum number of devices (defined for the WORKSTN file on the create-file command) is retrieved at file open, and SAVEIND and SAVEDS space allocation will be done at run time. With a shared file, the MAXDEV value is not used to restrict the number of acquired devices. When you specify DEVID, SAVEIND, or SAVEDS but not MAXDEV, the program assumes the default of a multiple device file (MAXDEV with a parameter of *FILE).
Specifications
5-63
File-Description Keywords
OFLIND(indicator)
The OFLIND keyword specifies an overflow indicator to condition which lines in the PRINTER file will be printed when overflow occurs. This entry is valid only for a PRINTER device. Default overflow processing (that is, automatic page eject at overflow) is done if the OFLIND keyword is not specified. Valid Parameters: *INOA-*INOG, *INOV: Specified overflow indicator conditions the lines to be printed when overflow occurs on a program described printer file. *IN01-*IN99: Set on when a line is printed on the overflow line, or the overflow line is reached or passed during a space or skip operation. name: The name of a variable that is defined with type indicator and is not an array. This indicator is set on when the overflow line is reached and the program must handle the overflow condition. The behavior is the same as for indicators *IN01 to *IN99. Note: Indicators *INOA through *INOG, and *INOV are not valid for externally described files. # Only one overflow indicator can be assigned to a file. If more than one PRINTER file in a module is # assigned an overflow indicator, that indicator must be unique for each file. A global indicator cannot be # used on more than one file even if one of the files is defined in a different procedure.
PASS(*NOIND)
The PASS keyword determines whether indicators are passed under programmer control or based on the DDS keyword INDARA. This keyword can only be specified for program-described files. To indicate that you are taking responsibility for passing indicators on input and output, specify PASS(*NOIND) on the file description specification of the corresponding program-described WORKSTN file. When PASS(*NOIND) is specified, the ILE RPG compiler does not pass indicators to data management on output, nor does it receive them on input. Instead you pass indicators by describing them as fields (in the form *INxx, *IN(xx), or *IN) in the input or output record. They must be specified in the sequence required by the data description specifications (DDS). You can use the DDS listing to determine this sequence. If this keyword is not specified, the compiler assumes that INDARA was specified in the DDS. Note: If the file has the INDARA keyword specified in the DDS, you must not specify PASS(*NOIND). If it does not, you must specify PASS(*NOIND).
PGMNAME(program_name)
The PGMNAME keyword identifies the program that is to handle the support for the special I/O device (indicated by a Device-Entry of SPECIAL). Note: The parameter must be a valid program name and not a bound procedure name. See Positions 36-42 (Device) on page 5-49 and PLIST(Plist_name) for more information.
PLIST(Plist_name)
The PLIST keyword identifies the name of the parameter list to be passed to the program for the SPECIAL file. The parameters identified by this entry are added to the end of the parameter list passed by the program. (The program is specified using the PGMNAME keyword, see PGMNAME(program_name).) This keyword can only be specified when the Device-Entry (positions 36 to 42) in the file description line is SPECIAL.
5-64
File-Description Keywords
PREFIX(prefix{:nbr_of_char_replaced})
| | | | | | | | | The PREFIX keyword is used to partially rename the fields in an externally described file.The characters specified in the first parameter are prefixed to the names of all fields defined in all records of the externally-described file. The characters can be specified as a name, for example PREFIX(F1_), or as a character literal, for example PREFIX('F1_'). A character literal must be used if the prefix contains a period, for example PREFIX('F1DS.') or PREFIX('F1DS.A'). To remove characters from the beginning of every name, specify an empty string as the first parameter: PREFIX('':number_to_remove). In addition, you can optionally specify a numeric value to indicate the number of characters, if any, in the existing name to be replaced. If the 'nbr_of_char_replaced' is not specified, then the string is attached to the beginning of the name. If the 'nbr_of_char_replaced' is specified, it must be a numeric constant containing a value between 0 and 9 with no decimal places. For example, the specification PREFIX(YE:3) would change the field name 'YTDTOTAL' to 'YETOTAL'. Specifying a value of zero is the same as not specifying 'nbr_of_char_replaced' at all. # The 'nbr_of_char_replaced' parameter is not used when applying the prefix to an alias name. See the # ALIAS keyword for information on how the PREFIX keyword interacts with the ALIAS keyword. Rules: v To explicitly rename a field on an Input specification when the PREFIX keyword has been specified for a file you must choose the correct field name to specify for the External Field Name (positions 21 - 30) of the Input specification. The name specified depends on whether the prefixed name has been used prior to the rename specification. If there has been a prior reference made to the prefixed name, the prefixed name must be specified. If there has not been a prior reference made to the prefixed name, the external name of the input field must be specified. Once the rename operation has been coded then the new name must be used to reference the input field. For more information, see External Field Name of the Input specification. The total length of the name after applying the prefix must not exceed the maximum length of an RPG field name. The number of characters in the name to be prefixed must not be less than or equal to the value represented by the 'nbr_of_char_replaced' parameter. That is, after applying the prefix, the resulting name must not be the same as the prefix string. If the prefix is a character literal, it can contain a period or end in a period. In this case, the field names must all be subfields of the same qualified data structure. The data structure must be defined as a qualified data structure. For example, for PREFIX('F1DS.'), data structure F1DS must be define as a qualified data structure; if the file has fields FLD1 and FLD2, the data structure must have subfields F1DS.FLD1 and F1DS.FLD2. Similarly, for PREFIX('F2DS.A'), data structure F2DS must be a qualified data structure; if the file has fields FLD1 and FLD2, the data structure must have subfields F2DS.AFLD1 and F2DS.AFLD2. If the prefix is a character literal, it must be uppercase.
v v
v If an externally-described data structure is used to define the fields in the file, care must be taken to ensure that the field names in the file are the same as the subfield names in the data structure. The following table shows the prefix required for an externally-described file and externally-described data structure for several prefixed versions of the name "XYNAME". When the "Internal name" column contains a dot, for example D1.NAME, the externally-described data structure is defined as QUALIFIED, and the PREFIX for the File specification must contain a dot.
PREFIX for file PREFIX(A) PREFIX(A:2) PREFIX for externally-described data structure PREFIX(A) PREFIX(A:2) Internal name AXYNAME ANAME
Specifications
5-65
File-Description Keywords
PREFIX for externally-described data structure None PREFIX('' : 2) PREFIX(A) PREFIX(A : 2) PREFIX('' : 2)
Examples: The following example adds the prefix "NEW_" to the beginning of the field names for file NEWFILE, and the prefix "OLD_" to the beginning of the field names for file OLDFILE.
Fnewfile Foldfile C C C C o if e e READ EVAL EVAL WRITE disk disk OLDREC NEWIDNO NEWABAL NEWREC prefix(NEW_) prefix(OLD_) = OLD_IDNO = OLD_ABAL
The following example uses PREFIX(N:2) on both file FILE1 and the externally-described data structure DS1. The File-specification prefix will cause the FILE1 fields XYIDNUM and XYCUSTNAME to be known as NIDNUM and NCUSTNAME in the program; the Data-specification prefix will cause the data structure to have subfields NIDNUM and NCUSTNAME. During the READ operation, data from the record will be moved to the subfields of DS1, which can then be passed to the subprocedure processRec to process the data in the record.
Ffile1 D ds1 C C if e e ds READ CALLP disk prefix(N:2) extname(file1) prefix(N:2)
The following example uses prefix 'MYDS.' to associate the fields in MYFILE with the subfields of qualified data structure MYDS.
Fmyfile D myds if e e ds disk prefix(MYDS.) qualified extname(myfile)
The next example uses prefix 'MYDS.F2':3 to associate the fields in MYFILE with the subfields of qualified data structure MYDS2. The subfields themselves are further prefixed by replacing the first three characters with 'F2'. The fields used by this file will be MYDS2.F2FLD1 and MYDS2.F2FLD2. (Data structure MYDS2 must be defined with a similar prefix. However, it is not exactly the same, since it does not include the data structure name.)
A A A Fmyfile2 D myds2 D R REC ACRFLD1 ACRFLD2 if e e ds 10A 5S 0 disk
| PRINTER{(*EXT | record-length)} | The PRINTER keyword is a device-type keyword. It is used in a free-form file definition to indicate that | the file device is PRINTER. It must be the first keyword. | The parameter is optional. It defaults to *EXT. | *EXT Specify *EXT to indicate that the file is externally described. This is the default. |
5-66
File-Description Keywords
| | | | record-length Specify a record-length to indicate that the file is program described. The record length must be between 1 and 32766. It can be a literal or a named constant. If it is a named constant, the constant must be defined prior to the file definition statement.
PRTCTL(data_struct{:*COMPAT})
The PRTCTL keyword specifies the use of dynamic printer control. The data structure specified as the parameter data_struct refers to the forms control information and line count value. The PRTCTL keyword is valid only for a program described file. The optional parameter *COMPAT indicates that the data structure layout is compatible with RPG III. The default, *COMPAT not specified, will require the use of the extended length data structure. Extended Length PRTCTL Data Structure: A minimum of 15 bytes is required for this data structure. Layout of the PRTCTL data structure is as follows: Data Structure Positions Subfield Contents 1-3 4-6 7-9 10-12 13-15 A three-position character field that contains the space-before value (valid entries: blank or 0-255) A three-position character field that contains the space-after value (valid entries: blank or 0-255) A three-position character field that contains the skip-before value (valid entries: blank or 1-255) A three-position character field that contains the skip-after value (valid entries: blank or 1-255) A three-digit numeric (zoned decimal) field with zero decimal positions that contains the current line count value.
*COMPAT PRTCTL Data Structure: Data Structure Positions Subfield Contents 1 2 3-4 5-6 7-9 A one-position character field that contains the space-before value (valid entries: blank or 0-3) A one-position character field that contains the space-after value (valid entries: blank or 0-3) A two-position character field that contains the skip-before value (valid entries: blank, 1-99, A0-A9 for 100-109, B0-B2 for 110-112) A two-position character field that contains the skip-after value (valid entries: blank, 1-99, A0-A9 for 100-109, B0-B2 for 110-112) A three-digit numeric (zoned decimal) field with zero decimal positions that contains the current line count value.
The values contained in the first four subfields of the extended length data structure are the same as those allowed in positions 40 through 51 (space and skip entries) of the output specifications. If the space and skip entries (positions 40 through 51) of the output specifications are blank, and if subfields 1 through 4 are also blank, the default is to space 1 after. If the PRTCTL option is specified, it is used only for the output records that have blanks in positions 40 through 51. You can control the space and skip value (subfields 1 through 4) for the PRINTER file by changing the values in these subfields while the program is running. Subfield 5 contains the current line count value. The ILE RPG compiler does not initialize subfield 5 until after the first output line is printed. The compiler then changes subfield 5 after each output operation to the file.
QUALIFIED
The QUALIFIED keyword controls how the record formats for the file are specified in your RPG source.
Specifications
5-67
File-Description Keywords
If this keyword is specified, the record formats must be qualified with the file name when they are specified in the RPG source; for example format FMT1 in qualified file FILE1 must be specified as FILE1.FMT1. The record format names can be the same as other names used within the RPG source. If this keyword is not specified, the record formats must not be qualified with the file name; format FMT1 is specified as FMT1. The record format names must be unique names within the RPG source. Rules for the QUALIFIED keyword:: v When a file is qualified, its record names must be qualified everywhere in the source except when specified as parameters of the File specification keywords RENAME, INCLUDE, IGNORE, and SFILE. The name must not be qualified when specified as the parameter of those keywords. v When a file is qualified, Input and Output specifications are not allowed or generated for the file. This means that external fields from the file are not automatically defined as fields in the program. All I/O must be done with result data structures. v The QUALIFIED keyword is valid only for externally-described files. v The QUALIFIED keyword cannot be specified with the LIKEFILE keyword; files defined with LIKEFILE always have qualified record formats.
* * * *
file1 has formats HDR, INFO, ERR. file2 has format INFO. The QUALIFIED keyword is used for both files, making it unnecessary to rename one of the "INFO" formats.
* Note that the record format names are not qualified when * specified in keywords of the File specification. Ffile1 if e disk qualified F ignore(hdr) F rename(err:errorRec) Ffile2 o e disk qualified * The record formats must be qualified on all specifications other * than the File specification for the file. D ds1 ds likerec(file1.info : *input) D errDs ds likerec(file1.errorRec : *input) D ds2 ds likerec(file2.info : *output) /free read file1.info ds1; eval-corr ds2 = ds1; write file2.info ds2; read file1.errorRec errDs; Figure 5-11. Example of the QUALIFIED keyword
RAFDATA(filename)
The RAFDATA keyword identifies the name of the input or update file that contains the data records to be processed for a Record Address File (RAF) (an R in position 18). See Record Address File (RAF) on page 5-43 for further information.
RECNO(fieldname)
The RECNO keyword specifies that a DISK file is to be processed by relative-record number. The RECNO keyword must be specified for output files processed by relative-record number, output files that are referenced by a random WRITE calculation operation, or output files that are used with ADD on the output specifications. The RECNO keyword can be specified for input/update files. The relative-record number of the record retrieved is placed in the 'fieldname', for all operations that reposition the file (such as READ, SETLL, or OPEN). It must be defined as numeric with zero decimal positions. The field length must be sufficient to contain the longest record number for the file.
5-68
File-Description Keywords
The compiler will not open a SEQ or DISK file for blocking or unblocking records if the RECNO keyword is specified for the file. Note that the keywords RECNO and BLOCK(*YES) cannot be specified for the same file. Note: When the RECNO keyword is specified for input or update files with file-addition (see the USAGE keyword for a free-form file definition or position 17 and position 20 for a fixed-form file definition)), the value of the fieldname parameter must refer to a relative-record number of a deleted record, for the output operation to be successful.
RENAME(Ext_format:Int_format)
The RENAME keyword allows you to rename record formats in an externally described file. The external name of the record format that is to be renamed is entered as the Ext_format parameter. The Int_format parameter is the name of the record as it is used in the program. The external name is replaced by this name in the program. To rename all fields by adding a prefix, use the PREFIX keyword. Remember that for a qualified file, the unqualified form of the record format name is used for both parameters of the RENAME keyword.
SAVEDS(DSname)
The SAVEDS keyword allows the specification of the data structure saved and restored for each device. Before an input operation, the data structure for the device operation is saved. After the input operation, the data structure for the device associated with this current input operation is restored. This data structure cannot be a data area data structure, file information data structure, or program status data structure, and it cannot contain a compile-time array or prerun-time array. If the SAVEDS keyword is not specified, no saving and restoring is done. SAVEDS must not be specified for shared files. When you specify SAVEDS but not MAXDEV, the ILE RPG program assumes a multiple device file (MAXDEV with a parameter of *FILE).
SAVEIND(number)
The SAVEIND keyword specifies the number of indicators that are to be saved and restored for each device attached to a mixed or multiple device file. Before an input operation, the indicators for the device associated with the previous input or output operation are saved. After the input operation, the indicators for the device associated with this current input operation are restored. Specify a number from 1 through 99, as the parameter to the SAVEIND keyword. No indicators are saved and restored if the SAVEIND keyword is not specified, or if the MAXDEV keyword is not specified or specified with the parameter *ONLY. If you specified the DDS keyword INDARA, the number you specify for the SAVEIND keyword must be less than any response indicator you use in your DDS. For example, if you specify INDARA and CF01(55) in your DDS, the maximum value for the SAVEIND keyword is 54. The SAVEIND keyword must not be used with shared files. The INDDS keyword cannot be specified with this keyword. When you specify the SAVEIND keyword but not the MAXDEV keyword, the ILE RPG program assumes a multiple device file. | | |
SEQ{(*EXT | record-length)}
The SEQ keyword is a device-type keyword. It is used in a free-form file definition to indicate that the file device is SEQ. It must be the first keyword.
Specifications
5-69
File-Description Keywords
| The parameter is optional. It defaults to *EXT. | *EXT | Specify *EXT to indicate that the file is externally described. This is the default. | record-length | Specify a record-length to indicate that the file is program described. The record length must be | between 1 and 32766. It can be a literal or a named constant. If it is a named constant, the constant | must be defined prior to the file definition statement.
SFILE(recformat:rrnfield)
The SFILE keyword is used to define internally the subfiles that are specified in an externally described WORKSTN file. The recformat parameter identifies the RPG IV name of the record format to be processed as a subfile. The rrnfield parameter identifies the name of the relative-record number field for this subfile. You must specify an SFILE keyword for each subfile in the DDS. If you define a display file like another file using the LIKEFILE keyword, and the parent file has subfiles, then you must specify the SFILE keyword for each subfile in the new file, so that you can provide the names of the relative record number fields for the subfiles. # If a file is defined with the TEMPLATE keyword, the rrnfield parameter of the SFILE keyword is not # specified. The relative-record number of any record retrieved by a READC or CHAIN operation is placed into the field identified by the rrnfield parameter. This field is also used to specify the record number that RPG IV uses for a WRITE operation to the subfile or for output operations that use ADD. The field name specified as the rrnfield parameter must be defined as numeric with zero decimal positions. The field must have enough positions to contain the largest record number for the file. (See the SFLSIZ keyword in the IBM i Information Center database and file systems category.) Relative record number processing is implicitly defined as part of the SFILE definition. If multiple subfiles are defined, each subfile requires the specification of the SFILE keyword. Do not use the SFILE keyword with the SLN keyword. Remember that for a qualified file, the unqualified form of the record format name is used for the first parameter of the SFILE keyword.
SLN(number)
The SLN (Start Line Number) keyword determines where a record format is written to a display file. The main file description line must contain WORKSTN in positions 36 through 42 and a C or O in positions 17. The DDS for the file must specify the keyword SLNO(*VAR) for one or more record formats. When you specify the SLN keyword, the parameter will automatically be defined in the program as a numeric field with length of 2 and with 0 decimal positions. Do not use the SLN keyword with the SFILE keyword. | SPECIAL{(*EXT | record-length)} | The SPECIAL keyword is a device-type keyword. It is used in a free-form file definition to indicate that | the file device is SPECIAL. It must be the first keyword. | The parameter is optional. It defaults to *EXT. | *EXT Specify *EXT to indicate that the file is externally described. This is the default. | | record-length Specify a record-length to indicate that the file is program described. The record length must be |
5-70
File-Description Keywords
| | between 1 and 99999. It can be a literal or a named constant. If it is a named constant, the constant must be defined prior to the file definition statement.
STATIC
The STATIC keyword indicates that the RPG file control information is kept in static storage; all calls to the subprocedure use the same RPG file control information. The RPG file control information holds its state across calls to the subprocedure. If the file is open when the subprocedure ends, then the file will still be open on the next call to the subprocedure. When the STATIC keyword is not specified, the RPG file control information is kept in automatic storage; each call to the subprocedure uses its own version of the RPG file control information. The RPG file control information is initialized on every call to the subprocedure. If the file is open when the subprocedure ends, then the file will be closed when the subprocedure ends. Rules for the STATIC keyword:: v The STATIC keyword can only be specified for file definitions in subprocedures. The STATIC keyword is implied for files defined in global definitions. v A file defined with the STATIC keyword will remain open until it is explicitly closed by a CLOSE operation, or until the activation group ends. v If a File Information Data Structure (INFDS) is defined for the file, the specification of the STATIC keyword for the data structure must match the specification of the STATIC keyword for the file.
P numInStock b export * File "partInfo" is defined as STATIC. The file will be * opened the first time the procedure is called, because * the USROPN keyword is not specified. * Since there is no CLOSE operation for the file, it * will remain open until the activation group ends. FpartInfo if e k disk static * File "partErrs" is not defined as STATIC, and the USROPN * keyword is used. The file will be opened by the OPEN * operation, and it will be closed automatically when the * procedure ends. FpartErrs o e disk usropn D numInStock D id_no D partInfoDs D partErrDs /free pi ds ds 10i 0 10i 0 value likerec(partRec:*input) likerec(errRec:*output)
// Search for the input value in the file chain id_no partRrec partInfoDs; if not %found(partInfo); // write a record to the partErrs file indicating // that the id_no record was not found. The // file must be opened before the record can // be written, since the USROPN keyword was // specified. partErrDs.id_no = id_no; open partErrs; write errRec partErrDs; return -1; // unknown id endif; return partInfoDs.qty; /end-free P numInStock e Figure 5-12. Example of the STATIC keyword for a File specification
TEMPLATE
The TEMPLATE keyword indicates that this file definition is to be used only at compile time. Files defined with the TEMPLATE keyword are not included in the program. The template file can only be used as a basis for defining other files later in the program using the LIKEFILE keyword.
Specifications
5-71
File-Description Keywords
Rules for the TEMPLATE keyword:: v The RPG symbol name for the template file can be used only as the parameter of a LIKEFILE keyword on a file specification, or a LIKEFILE keyword on a Definition specification. v The RPG symbol name of a record format of a template file can be used only as the parameter of a LIKEREC Definition keyword. v Keywords that are not inherited by LIKEFILE definitions are not allowed for a template file. See Table 5-9 on page 5-62 for more information.
TIMFMT(format{separator})
The TIMFMT keyword allows the specification of a default external time format and a default separator (which is optional) for all time fields in the program-described file. If the file on which this keyword is specified is indexed and the key field is a time, then the time format specified also provides the default external format for the key field. For a Record-Address file this specifies the external time format of time limits keys read from the record-address file. You can specify a different external format for individual input or output time fields in the file by specifying a time format/separator for the field on the corresponding input specification (positions 31-35) or output specification (positions 53-57). See Table 4-6 on page 4-76 for valid format and separators. For more information on external formats, see Internal and External Formats on page 4-49. | USAGE(*INPUT *OUTPUT *UPDATE *DELETE) | The USAGE keyword is used in a free-form file definition to specify the way the file can be used. | The USAGE keyword is optional, but if it is specified, it must have at least one parameter. | *INPUT input | | *OUTPUT output | | *UPDATE input and update | | *DELETE input, update, and delete | | Some values imply more than one usage. For example, *UPDATE implies both input and update. The | following USAGE keywords have the same meaning: | USAGE(*INPUT : *UPDATE) | USAGE(*UPDATE) | The default | v For a file | v For a file | v For a file usage for a file depends on the device-type of the file. with device-type DISK, SEQ, or SPECIAL, the default usage is *INPUT. with device-type PRINTER, the default usage is *OUTPUT. with device-type WORKSTN, the default usage is *INPUT and *OUTPUT.
USROPN
The USROPN keyword causes the file not to be opened at program initialization. This gives the programmer control of the file's first open. The file must be explicitly opened using the OPEN operation in the calculation specifications. This keyword is not valid for input files designated as primary, secondary, table, or record-address files, or for output files conditioned by the 1P (first page) indicator.
5-72
File-Description Keywords
The USROPN keyword is required for programmer control of only the first file opening. For example, if a file is opened and later closed by the CLOSE operation, the programmer can reopen the file (using the OPEN operation) without having specified the USROPN keyword on the file description specification. See also EXTIND(*INUx) on page 5-55. | | | | | | | | | |
WORKSTN{(*EXT | record-length)}
The WORKSTN keyword is a device-type keyword. It is used in a free-form file definition to indicate that the file device is WORKSTN. It must be the first keyword. The parameter is optional. It defaults to *EXT. *EXT Specify *EXT to indicate that the file is externally described. This is the default. record-length Specify a record-length to indicate that the file is program described. The record length must be between 1 and 32766. It can be a literal or a named constant. If it is a named constant, the constant must be defined prior to the file definition statement.
Free-form syntax: (No keyword is necessary) Sequential Key READ READE READP READPE cycle READ READE READP READPE cycle READ cycle Blank Blank I
Sequential
Within Limits
A, P, G, D, T, Z, or F
Free-form syntax: (Not supported for a free-form file definition) Blank Blank T
Access by key sequentially controlled by recordaddress-limits file Access sequentially restricted to RRN numbers in record-address file
Sequential
RRN
For further information on the various file processing methods, see the section entitled "Methods for Processing Disk Files", in the chapter "Accessing Database Files" in the Rational Development Studio for i: ILE RPG Programmer's Guide.
Specifications
5-73
Definition Specifications
Definition specifications can be used to define: v Standalone fields v Named constants v Data structures and their subfields v Prototypes v Procedure interface v Prototyped parameters For more information on data structures, constants, prototypes, and procedure interfaces, see also Defining Data and Prototypes on page 4-1 For more information on data types and data formats, see also Data Types and Data Formats on page 4-48. Arrays and tables can be defined as either a data-structure subfield or a standalone field. For additional information on defining and using arrays and tables, see also Using Arrays and Tables on page 4-31. Definition specifications can appear in two places within a module or program: in the main source section and in a subprocedure. Within the main source section, you define all global definitions. Within a subprocedure, you define the procedure interface and its parameters as required by the prototype. You also define any local data items that are needed by the prototyped procedure when it is processed. Any definitions within a prototyped procedure are local. They are not known to any other procedures (including the cycle-main procedure). For more information on scope, see Scope of Definitions on page 3-19. A built-in function (BIF) can be used in the keyword field as a parameter to a keyword. It is allowed on the definition specification only if the values of all arguments are known at compile time. When specified as parameters for the definition specification keywords DIM, OCCURS, OVERLAY, and PERRCD, all arguments for a BIF must be defined earlier in the program. For further information on using built-in functions, see Built-in Functions on page 6-8. |
| A free-form data definition statement begins with one of the declaration operation codes, followed by a | name, or by *N if the item does not have a name, followed by keywords, and finally a semicolon. | The following are the declaration operation codes: | DCL-C Define a named constant | | DCL-DS and END-DS Define a data structure | | {DCL-PARM} Define a parameter | | DCL-PI and END-PI Define a procedure interface | | DCL-PR and END-PR Define a prototype | | DCL-S Define a standalone field | | {DCL-SUBF} Define a subfield |
5-74
The definition may be split across multiple lines if necessary. The following are equivalent definitions: 1. The definition is specified on a single line. 2. The definition is split across multiple lines. 3. The name is split across two lines, and the keyword is specified on the same line as the second part of the name. 4. The name is split across two lines, and the keyword is specified on line following the second part of the name. Note: An ellipsis is not used following the last part of the name. In free-form specifications, an ellipsis is only used to join two parts of a name that are specified on different lines. It is not used to join a name to the remainder of the statement.
| | | | | | |
| |
| | | | | | | | | | | | | | | | | | |
The only directives that are allowed within a free-form data definition statement are /IF, /ELSEIF, /ELSE, and /ENDIF.
DCL-S G_Working_Date DATE(*ISO) /IF DEFINED(main_module) EXPORT INZ(*SYS) /ELSE IMPORT /ENDIF ;
Note: Specifying DCL-PARM or DCL-SUBF is optional unless the name of the item is the same as an operation code allowed in free-form calculations. If a data structure defined without the LIKEREC or LIKEDS keywords begins with a free-form statement, or any of the subfields are specified with free-form statements, the data structure must end with an END-DS statement.
Specifications
5-75
| | | | | | | | | | |
DCL-DS ds1; subf1 CHAR(10); END-DS; D ds2 DS subf2 CHAR(10); END-DS; D DCL-DS ds3; subf3 END-DS; 10a
| Similarly, if a prototype or procedure interface begins with a free-form statement, or any of the | parameters are specified with free-form statements, the prototype or procedure interface must end with | an END-PR or END-PI statement. | | | | | | | | | | | |
DCL-PR pr1; subf1 CHAR(10); END-PR; D pr2 PR parm2 CHAR(10); END-PR; D DCL-PI pi3; parm3 END-PI; 10a
| If a data structure has no subfields, END-DS may be specified as part of the DCL-DS statement, | immediately before the semicolon. | |
DCL-DS ds1 LEN(100) END-DS;
| Similarly, if a procedure interface or prototype has no parameters, the END-PI or END-PR may be | specified as part of the DCL-PI or DCL-PR statement, immediately before the semicolon. | |
DCL-PR pr1 LEN(100) END-PR;
| | | |
Data-type Keywords
BINDEC(digits {: decimal-positions}) on page 5-96 CHAR(length) on page 5-96 DATE{(format{separator})} on page 5-98 FLOAT(bytes) on page 5-111 GRAPH(length) on page 5-112 IND on page 5-113 INT(digits) on page 5-113 OBJECT{(*JAVA:class-name)} on page 5-122 PACKED(digits {: decimal-positions}) on page 5-136 POINTER{(*PROC)} on page 5-137 TIME{(format{separator})} on page 5-145
IBM i: ILE RPG Reference
v v v | v | v | v | v | | | | v v v v
5-76
Table 5-12. Keyword differences between free-form and fixed-form definitions Keyword DTAARA EXPORT EXTFLD Difference See Free-form DTAARA keyword for a data structure on page 5-101 and Free-form DTAARA keyword for a field or subfield on page 5-100. In a free-form definition, the external name can be specified using *DCLCASE. In a free-form definition, the external field name must be specified as a character literal or a previously defined named constant representing a character literal. In a free-form definition, the external file and external record format must be specified as character literals or previously-defined named constants representing a character literals. In a free-form definition, the external name can be specified using *DCLCASE. In a free-form definition, the external name can be specified using *DCLCASE. In a free-form definition, the length adjustment is specified as the second parameter of the LIKE keyword. In a free-form definition, the parameter of the OVERLAY keyword cannot be the name of the data structure. To explicitly specify the starting position of a subfield within the data structure, use the POS keyword.
OVERLAY
Specifications
5-77
| v The following example shows a named constant array_total_size that is defined with the value of a | built-in function. | | | |
DCL-S array CHAR(25) DIM(100); DCL-C array_total_size %SIZE(array:*ALL);
| Free-Form Standalone Field Definition | A free-form standalone field begins with DCL-S, followed by the name of the field, followed by | keywords, and finally a semicolon. | If a data-type keyword is specified, it must be the first keyword. | Examples of free-form standalone field definitions | v A packed field named limit with five digits and zero decimal positions, initialized to 100. The PACKED keyword must be first because it is the data-type keyword. | | |
DCL-S limit PACKED(5) INZ(100);
| v A field named num defined with the LIKE keyword, initialized to 0. There is no data-type keyword. The LIKE keyword can appear anywhere. | | | |
DCL-S num INZ(0) LIKE(limit);
| Free-Form Data Structure Definition | A data structure begins with a DCL-DS statement. | If the LIKEDS or LIKEREC keyword is not specified for the DCL-DS statement, the DCL-DS statement is | followed by zero or more subfields, followed by an END-DS statement.
5-78
DCL-DS statement
The first statement begins with DCL-DS, followed by the name of the data structure or *N if it does not have a name, followed by keywords, and finally a semicolon.
Subfields
Note: Subfields are not specified for a data structure defined with the LIKEDS or LIKEREC keyword. See Free-Form Subfield Definition on page 5-82.
END-DS statement
v END-DS is not specified for a data structure defined with the LIKEDS or LIKEREC keyword. v END-DS may be followed by the name of the data structure.
DCL-DS custInfo QUALIFIED; id INT(10); name VARCHAR(50); city VARCHAR(50); orders LIKEDS(order_t) DIM(100); numOrders INT(10); END-DS custInfo;
v If the data structure does not have a name, END-DS must be specified without an operand. v If there are no subfields, END-DS may be specified as part of the DCL-DS statement, following the keywords and before the semicolon. In this case, END-DS cannot be followed by the name of the data structure.
DCL-DS prtDs LEN(132) END-DS;
If you specify the EXT keyword, you can also specify the EXTNAME keyword as a later keyword.
DCL-DS extds2 EXT INZ(*EXTDFT) EXTNAME(MYFILE) END-DS;
Specifications
5-79
| | | | |
DCL-DS pgm_stat PSDS; status *STATUS; routine *ROUTINE; library CHAR(10) POS(81); END-DS;
| See Program Status Data Structure on page 3-85 for a list of all the predefined subfields for a PSDS. | File Information Data Structure (INFDS) | The name of an INFDS is specified as the parameter for the INFDS keyword of a file definition. | For predefined subfields such as *STATUS, specify the reserved word in place of the data-type keyword. | | | | | | |
DCL-F myfile DISK(*EXT) INFDS(myfileInfo); DCL-DS myfileInfo; status *STATUS; opcode *OPCODE; msgid CHAR(7) POS(46); END-DS;
| See File Feedback Information on page 3-69 for a list of all the predefined subfields for an INFDS. | File Information Data Structure | Specify the *AUTO parameter for the DTAARA keyword. | | | |
DCL-DS dtaara_ds DTAARA(*AUTO) LEN(100); name CHAR(10); END-DS;
| Examples of free-form data structures | 1. Data structures defined with LIKEDS and LIKEREC are coded as a single statement without END-DS. | | |
DCL-DS info LIKEDS(info_T); DCL-DS inputDs LIKEREC(custFmt : *INPUT);
| 2. A data structure cust_info with three subfields. The END-DS statement is specified without a name. | | | | | |
DCL-DS cust_info; id INT(10); name VARCHAR(25); startDate DATE(*ISO); END-DS;
| 3. A data structure using DCL-SUBF to define some of its subfields. v Subfield select has the same name as an operation code allowed in free-form calculations. | DCL-SUBF is required for this subfield. See Table 6-1 on page 6-2. | v Subfield name does not have the same name as an operation code, so DCL-SUBF is not required. |
5-80
v Subfield address does not have the same name as an operation code, so DCL-SUBF is not required, but it is valid.
6. An externally-described data structure whose name is the same as the name of the external file, 'CUSTINFO'. The data structure has external subfields identified by the EXTFLD keyword. The EXTFLD keyword is specified without a parameter when the subfield name is the same as the external name.
DCL-DS custInfo EXT; cust_name EXTFLD(CSTNAM); id_no EXTFLD INZ(0); END-DS;
Specifications
5-81
| Free-Form Subfield Definition | A free-form subfield definition begins with the subfield name, or it begins with the DCL-SUBF operation | code followed by the subfield name. | The DCL-SUBF operation code must be specified if the subfield name is the same as an operation code | allowed in free-format calculations. See Table 6-1 on page 6-2. | The subfield name is followed by keywords, and finally a semicolon. | Program-described subfield | Specify *N for the subfield name if the subfield does not have a name. | If a data-type keyword is specified, it must be the first keyword. | If the subfield is a predefined subfield in the Program Status Data Structure or a File Information Data | Structure, specify the subfield reserved word in place of the data type keyword. | In a free-form definition, the OVERLAY keyword can only be used to overlay one subfield on another | subfield. If you don't want the subfield to be placed at the next available position in the data structure, | use the POS keyword to specify the starting position. | Externally-described subfield | The first keyword for an externally-described subfield must be the EXTFLD keyword. If the subfield | name is the same as the external name of the subfield, the parameter of the EXTFLD keyword may be | omitted. | Subfield examples | See Free-Form Data Structure Definition on page 5-78 for examples of free-form subfield definitions. | Equivalent Free-form Coding for Subfield Entries: | | | | | | | | | | | | | |
Table 5-15. Free-form equivalents for fixed-form externally-described subfield entries Fixed-form-entry External Free-form equivalent EXTFLD keyword specified as the first keyword
Table 5-16. Free-form equivalents for fixed-form program-described subfield entries Fixed-form-entry From with numeric value Free-form equivalent POS keyword
From with special value such as Specify the special value in place of the data type keyword *STATUS To Length, Internal data type, and Decimal Positions entries There is no exact equivalent. The end-position of the subfield is determined from the POS keyword combined with the length of the item See Equivalent Free-form Coding for Standalone Field Entries on page 5-78
5-82
Prototype parameters
See Free-Form Parameter Definition on page 5-86.
2. A prototype addNewOrder with three parameters. The END-PR statement is specified without a name.
DCL-PR addNewOrder; id INT(10) CONST; quantity INT(10) CONST; price PACKED(7 : 2) CONST; END-PR; 2
4. The prototype has no parameters, so the END-PR is specified as part of the DCL-PR statement.
DCL-PR getCurrentUser CHAR(10) END-PR; 4
5. A prototype using DCL-PARM to define some of its subfields. a. Parameter select has the same name as an operation code allowed in free-form calculations. DCL-PARM is required for this parameter. See Table 6-1 on page 6-2.
Specifications
5-83
b. Parameter name does not have the same name as an operation code, so DCL-PARM is not required. c. Parameter address does not have the same name as an operation code, so DCL-PARM is not required, but it is valid.
| 6. See Specifying *DCLCASE as the External Name on page 5-111 for more examples. | Equivalent Free-form Coding for Prototype Entries: | | | | |
Table 5-17. Free-form equivalents for fixed-form prototype entries Fixed-form-entry Length, Internal data type, and Decimal Positions entries Free-form equivalent See Equivalent Free-form Coding for Standalone Field Entries on page 5-78
| Free-Form Procedure Interface Definition | A procedure interface begins with a DCL-PI statement. | The DCL-PI statement is followed by zero or more parameters, followed by an END-PI statement. | DCL-PI statement to begin the procedure interface | | | | | | The first statement begins with DCL-PI, followed by the name of the procedure or *N if you do not want to repeat the name of the procedure, followed by keywords, and finally a semicolon. v If you do not specify a prototype for a cycle-main procedure, you use *N as the name for the procedure interface. v If you do not specify a prototype for a linear-main procedure, you can specify the EXTPGM keyword without a parameter for the procedure interface.
| Procedure interface parameters | See Free-Form Parameter Definition on page 5-86. | END-PI statement to end the procedure interface | v END-PI may be followed by the name of the procedure. | v If there are no parameters, END-PI may be specified as part of the DCL-PI statement, following the keywords and before the semicolon. In this case, END-PI cannot be followed by the name of the | procedure. | | Examples of free-form procedure interfaces | 1. A procedure interface for a cycle-main procedure where there is no prototype. *N is specified for the procedure-interface name. One parameter, name is specified in the procedure interface. (This example | shows a complete program with a cycle-main procedure.) | |
5-84
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
CTL-OPT OPTION(*SRCSTMT); DCL-PI *N; 1 name CHAR(10) CONST; END-PI; DSPLY (Hello + name); RETURN;
2. A procedure interface for a linear-main procedure where there is no prototype. The EXTPGM keyword is specified without a parameter. (This example shows a complete program with a linear-main procedure.)
CTL-OPT MAIN(sayHello) OPTION(*SRCSTMT); DCL-PROC sayHello; DCL-PI *N EXTPGM; 2 name CHAR(10) CONST; END-PI; DSPLY (Hello + name); END-PROC;
3. A procedure interface with three parameters. The END-PI statement is specified without a name.
DCL-PROC addNewOrder; DCL-PI *N; id INT(10) VALUE; quantity INT(10) CONST; price PACKED(7 : 2) CONST; END-PI; 3 ... END-PROC;
5. END-PI is specified as part of the DCL-PI statement. (This example shows a complete procedure.)
DCL-PROC getCurrentUser; DCL-PI *N CHAR(10) END-PI;
Specifications
5-85
| 7. See Specifying *DCLCASE as the External Name on page 5-111 for more examples. | Equivalent Free-form Coding for Procedure Interface Entries: | | | | |
Table 5-18. Free-form equivalents for fixed-form procedure interface entries Fixed-form-entry Length, Internal data type, and Decimal Positions entries Free-form equivalent See Equivalent Free-form Coding for Standalone Field Entries on page 5-78
| Free-Form Parameter Definition | A free-form parameter definition begins with the parameter name, or it begins with the DCL-PARM | operation code followed by the parameter name. | The DCL-PARM operation code must be specified if the parameter name is the same as an operation code | allowed in free-format calculations. See Table 6-1 on page 6-2. | The parameter name is followed by keywords, and finally a semicolon. | If you do not want to specify the name for a parameter in a prototype definition, specify *N for the | parameter name. | If a data-type keyword is specified, it must be the first keyword. | See Free-Form Procedure Interface Definition on page 5-84 and Free-Form Prototype Definition on | page 5-83 for examples of free-form parameter definitions. | Equivalent Free-form Coding for Parameter Entries: | | | | | |
Table 5-19. Free-form equivalents for fixed-form parameter entries Fixed-form-entry Length, Internal data type, and Decimal Positions entries Free-form equivalent See Equivalent Free-form Coding for Standalone Field Entries on page 5-78
5-86
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 ...+... 9 ...+... 10 DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++Comments++++++++++++ Figure 5-13. Definition Specification Layout
If additional space is required for keywords, the keywords field can be continued on subsequent lines as follows: v Position 6 of the continuation line must contain a D v Positions 7 to 43 of the continuation line must be blank v The specification continues on or past position 44
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 ...+... 9 ...+... 10 D.....................................Keywords+++++++++++++++++++++++++++++Comments++++++++++++ Figure 5-14. Definition Specification Keyword Continuation Line Layout
A name that is up to 15 characters long can be specified in the Name entry of the definition specification without requiring continuation. Any name (even one with 15 characters or fewer) can be continued on multiple lines by coding an ellipsis (...) at the end of the partial name. A name definition consists of the following parts: 1. Zero or more continued name lines. Continued name lines are identified as having an ellipsis as the last non-blank character in the entry. The name must begin within positions 7 to 21 and may end anywhere up to position 77 (with an ellipsis ending in position 80). There cannot be blanks between the start of the name and the ellipsis character. If any of these conditions is not true, the line is parsed as a main definition line. 2. One main definition line, containing a name, definition attributes, and keywords. If a continued name line is coded, the Name entry of the main definition line may be left blank. 3. Zero or more keyword continuation lines.
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 ...+... 9 ...+... 10 DContinuedName+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++Comments++++++++++++ Figure 5-15. Definition Specification Continued Name Line Layout
5-87
Entry
Explanation
Name The name of the item being defined. Blank Specifies filler fields in data-structure subfield definitions, or an unnamed data structure in data-structure definitions. The normal rules for RPG IV symbolic names apply; reserved words cannot be used (see Symbolic Names on page 3-1). The name can begin in any position in the space provided. Thus, indenting can be used to indicate the shape of data in data structures. For continued name lines, a name is specified in positions 7 through 80 of the continued name lines and positions 7 through 21 of the main definition line. As with the traditional definition of names, case of the characters is not significant. For an externally described subfield, a name specified here replaces the external-subfield name specified on the EXTFLD keyword. For a prototype parameter definition, the name entry is optional. If a name is specified, the name is ignored. (A prototype parameter is a definition specification with blanks in positions 24-25 that follows a PR specification or another prototype parameter definition.) Tip: If you are defining a prototype and the name specified in positions 7-21 cannot serve as the external name of the procedure, use the EXTPROC keyword to specify the valid external name. For example, the external name may be required to be in lower case, because you are defining a prototype for a procedure written in ILE C.
This position is used to identify a data structure or data-structure subfield as externally described. If a data structure or subfield is not being defined on this specification, then this field must be left blank. Entry E Explanation for Data Structures Identifies a data structure as externally described: subfield definitions are defined externally. If the EXTNAME keyword is not specified, positions 7-21 must contain the name of the externally described file containing the data structure definition.
Blank Program described: subfield definitions for this data structure follow this specification.
Entry E
Explanation for Subfields Identifies a data-structure subfield as externally described. The specification of an externally described subfield is necessary only when keywords such as EXTFLD and INZ are used.
IBM i: ILE RPG Reference
5-88
This entry is used to identify the type of data structure being defined. If a data structure is not being defined, this entry must be left blank. Entry Explanation
Blank The data structure being defined is not a program status or data-area data structure; or a data structure is not being defined on this specification S U Program status data structure. Only one data structure may be designated as the program status data structure. Data-area data structure. RPG IV retrieves the data area at initialization and rewrites it at end of program. v If the DTAARA keyword is specified, the parameter to the DTAARA keyword is used as the name of the external data area. If the name is a variable, the value must be set before the program begins. This can be done by: Passing the variable as a parameter. Explicitly initializing the variable with the INZ keyword. Sharing the variable with another module using the IMPORT and EXPORT |keywords, and ensuring the value is set prior to the call. v If the DTAARA keyword is not specified, the name in positions 7-21 is used as the name of the external data area. v If a name is not specified either by the DTAARA keyword, or by positions 7-21, *LDA (the local data area) is used as the name of the external data area.
Entry
Explanation
Blank The specification defines either a data structure subfield or a parameter within a prototype or procedure interface definition. C DS PR PI S The specification defines a constant. Position 25 must be blank. The specification defines a data structure. The specification defines a prototype and the return value, if any. The specification defines a procedure interface, and the return value if any. The specification defines a standalone field, array or table. Position 25 must be blank.
Definitions of data structures, prototypes, and procedure interfaces end with the first definition specification with non-blanks in positions 24-25, or with the first specification that is not a definition specification. For a list of valid keywords, grouped according to type of definition, please refer to Table 5-21 on page 5-150.
Specifications
5-89
Positions 26-32 may only contain an entry if the location of a subfield within a data structure is being defined. Entry Explanation
Blank A blank FROM position indicates that the value in the TO/LENGTH field specifies the length of the subfield, or that a subfield is not being defined on this specification line. nnnnnnn Absolute starting position of the subfield within a data structure. The value specified must be from 1 to 9999999, and right-justified in these positions. Reserved Words Reserved words for the program status data structure or for a file information data structure are allowed (left-justified) in the FROM-TO/LENGTH fields (positions 26-39). These special reserved words define the location of the subfields in the data structures. Reserved words for the program status data structure are *STATUS, *PROC, *PARM, and *ROUTINE. Reserved words for the file information data structure (INFDS) are *FILE, *RECORD, *OPCODE, *STATUS, and *ROUTINE.
Blank If positions 33-39 are blank: v a named constant is being defined on this specification line, or v v v v the standalone field, parameter, or subfield is being defined LIKE another field, or the standalone field, parameter, or subfield is of a type where a length is implied, or the subfield's attributes are defined elsewhere, or a data structure is being defined. The length of the data structure is the maximum value of the subfield To-Positions. The data structure may be defined using the LIKEDS or LIKEREC keyword.
nnnnnnn Positions 33-39 may contain a (right-justified) numeric value, from 1 to 9999999, as follows: v If the From field (position 26-32) contains a numeric value, then a numeric value in this field specifies the absolute end position of the subfield within a data structure. v If the From field is blank, a numeric value in this field specifies : the length of the entire data structure, or the length of the standalone field, or the length of the parameter, or the length of the subfield. Within the data structure, this subfield is positioned such that its starting position is greater than the maximum to-position of all previously defined subfields in the data structure. Padding is inserted if the subfield is defined with type basing pointer or procedure pointer to ensure that the subfield is aligned properly.
5-90
This entry allows you to specify how a standalone field, parameter, or data-structure subfield is stored internally. This entry pertains strictly to the internal representation of the data item being defined, regardless of how the data item is stored externally (that is, if it is stored externally). To define variable-length character, graphic, and UCS-2 formats, you must specify the keyword VARYING; otherwise, the format will be fixed length. Entry Explanation
Blank When the LIKE keyword is not specified: v If the decimal positions entry is blank, then the item is defined as character v If the decimal positions entry is not blank, then the item is defined as packed numeric if it is a standalone field or parameter; or as zoned numeric if it is a subfield. Note: The entry must be blank whenever the LIKE, LIKEDS and LIKEREC keywords are specified. A B Character (Fixed or Variable-length format) Numeric (Binary format)
Specifications
5-91
Positions 41-42 are used to indicate the number of decimal positions in a numeric subfield or standalone field. If the field is non-float numeric, there must always be an entry in these positions. If there are no decimal positions enter a zero (0) in position 42. For example, an integer or unsigned field (type I or U in position 40) requires a zero for this entry. Entry Explanation
Blank The value is not numeric (unless it is a float field) or has been defined with the LIKE keyword. 0-63 Decimal positions: the number of positions to the right of the decimal in a numeric field.
This entry can only be supplied in combination with the TO/Length field. If the TO/Length field is blank, the value of this entry is defined somewhere else in the program (for example, through an externally described data base file).
Position 43 (Reserved)
Position 43 must be blank.
Positions 44 to 80 are provided for definition specification keywords. Keywords are used to describe and define data and its attributes. Use this area to specify any keywords necessary to fully define the field.
Definition-Specification Keywords
Definition-specification keywords may have no parameters, optional parameters, or required parameters. The syntax for keywords is as follows:
Keyword(parameter1 : parameter2)
5-92
Definition-Specification Keywords
Note: Do not specify parentheses if there are no parameters. v Colons (:) are used to separate multiple parameters. The following notational conventions are used to show which parameters are optional and which are required: v Braces { } indicate optional parameters or optional elements of parameters. v An ellipsis (...) indicates that the parameter can be repeated. v A colon (:) separates parameters and indicates that more than one may be specified. All parameters separated by a colon are required unless they are enclosed in braces. v A vertical bar (|) indicates that only one parameter may be specified for the keyword. v A blank separating keyword parameters indicates that one or more of the parameters may be specified. Note: Braces, ellipses, and vertical bars are not a part of the keyword syntax and should not be entered into your source. If additional space is required for definition-specification keywords, the keyword field can be continued on subsequent lines. See Definition Specification Keyword Continuation Line on page 5-87 and Definition Specification Keyword Field on page 5-9. # # # # # # # # # # # #
ALIAS
When the ALIAS keyword is specified for an externally-described data structure, the RPG compiler will use the alias (alternate) names for the subfields, if present. If the ALIAS keyword is not specified for the data structure, or an external field does not have an alias name defined, the RPG compiler will use the standard external field name. When alias names are being used and you want to rename a subfield, you specify the alias name as the parameter to the EXTFLD keyword. The EXTFLD keyword does not support continuation, so you must specify the entire name on one source specification. Figure 5-16 on page 5-94 shows an example with two data structures, defined for the same file. The data structure that has the ALIAS keyword coded uses the alias name, CUSTOMER_ADDRESS, as the parameter for the EXTFLD keyword. The data structure that does not have the ALIAS keyword coded uses the standard name, CUSTAD, as the parameter for the EXTFLD keyword.
# Note: If the alternate name for a particular external field is enclosed in quotes, the standard external field # name is used for that field. # # # # # # # # # # # # # # # # When the PREFIX keyword is specified with the ALIAS keyword, the second parameter of PREFIX, indicating the number of characters to be replaced, does not apply to the alias names. In the following discussion, assume that the external file MYFILE has fields XYCUSTNM and XYID_NUM, and the XYCUSTNM field has the alias name CUSTOMER_NAME. v If keyword PREFIX(NEW_) is specified, there is no second parameter, so no characters will be replaced for any names. The names used for the RPG subfields will be NEW_CUSTOMER_NAME and NEW_XYID_NUM. v If keyword PREFIX(NEW_:2) is specified, two characters will be removed from the names of fields that do not have an alias name. The names used for the RPG subfields will be NEW_CUSTOMER_NAME and NEW_ID_NUM. The first two characters, "XY", are replaced in XYID_NUM, but no characters are replaced in CUSTOMER_NAME. v If keyword PREFIX('':2) is specified, two characters will be removed the names of fields that do not have an alias name. The names used for the RPG subfields will be CUSTOMER_NAME and ID_NUM. The first two characters, "XY", are replaced in XYID_NUM, but no characters are replaced in CUSTOMER_NAME.
Specifications
5-93
Definition-Specification Keywords
# * The DDS specifications for file MYFILE, using the ALIAS keyword * for the first two fields, to associate alias name CUSTOMER_NAME # * with the CUSTNM field and alias name CUSTOMER_ADDRESS # * with the CUSTAD field.A R CUSTREC # CUSTNM 25A ALIAS(CUSTOMER_NAME) # A CUSTAD 25A ALIAS(CUSTOMER_ADDRESS) # A ID_NUM 12P 0 # A # * The RPG source, using the ALIAS keyword. # * The customer-address field is renamed to CUST_ADDR # * for both data structures.D aliasDs e ds ALIAS # QUALIFIED EXTNAME(myfile) # D EXTFLD(CUSTOMER_ADDRESS) # D cust_addr e e ds # D noAliasDs QUALIFIED EXTNAME(myfile) # D EXTFLD(CUSTAD) # D cust_addr e /free # // The ALIAS keyword is specified for data structure "aliasDs" # // so the subfield corresponding to the "CUSTNM" field has # // the alias name "CUSTOMER_NAME" aliasDs.customer_name = John Smith; # aliasDs.cust_addr = 123 Mockingbird Lane; # aliasDs.id_num = 12345; # # // The ALIAS keyword is not specified for data structure # // "noAliasDs", so the subfield corresponding to the "CUSTNM" # // field does not use the alias name noAliasDs.custnm = John Smith; # aliasDs.cust_addr = 123 Mockingbird Lane; # noAliasDs.id_num = 12345; # # # # Figure 5-16. Using the ALIAS keyword for an externally-described data structure #
ALIGN
The ALIGN keyword is used to align float, integer, and unsigned subfields. When ALIGN is specified, 2-byte subfields are aligned on a 2-byte boundary, 4-byte subfields are aligned on a 4-byte boundary and 8-byte subfields are aligned on an 8-byte boundary. Alignment may be desired to improve performance when accessing float, integer, or unsigned subfields. Specify ALIGN on the data structure definition. However, you cannot specify ALIGN for either the file information data structure (INFDS) or the program status data structure (PSDS). Alignment occurs only to data structure subfields defined with length notation and without the keyword OVERLAY. A diagnostic message is issued if subfields that are defined either with absolute notation or using the OVERLAY keyword are not properly aligned. Pointer subfields are always aligned on a 16-byte boundary whether or not ALIGN is specified. See Aligning Data Structure Subfields on page 4-14 for more information.
ALT(array_name)
The ALT keyword is used to indicate that the compile-time or pre-runtime array or table is in alternating format. The array defined with the ALT keyword is the alternating array and the array name specified as the parameter is the main array. The alternate array definition may precede or follow the main array definition. The keywords on the main array define the loading for both arrays. The initialization data is in alternating order, beginning with the main array, as follows: main/alt/main/alt/...
5-94
Definition-Specification Keywords
In the alternate array definition, the PERRCD, FROMFILE, TOFILE, and CTDATA keywords are not valid.
ALTSEQ(*NONE)
When the ALTSEQ(*NONE) keyword is specified, the alternate collating sequence will not be used for comparisons involving this field, even when the ALTSEQ keyword is specified on the control specification. ALTSEQ(*NONE) on Data Definition specifications will be meaningful only if one of ALTSEQ, ALTSEQ(*SRC) or ALTSEQ(*EXT) is coded in the control specifications. It is ignored if this is not true. ALTSEQ(*NONE) is a valid keyword for: v Character standalone fields v Character arrays v v v v v Character tables Character subfields Data structures Character return values on Procedure Interface or Prototype definitions Character Prototyped Parameters
ASCEND
The ASCEND keyword is used to describe the sequence of the data in any of the following: v An array v A table loaded at prerun-time or compile time v A prototyped parameter See also DESCEND on page 5-98. Ascending sequence means that the array or table entries must start with the lowest data entry (according to the collating sequence) and go to the highest. Items with equal value are allowed. A prerun-time array or table is checked for the specified sequence at the time the array or table is loaded with data. If the array or table is out of sequence, control passes to the RPG IV exception/error handling routine. A run-time array (loaded by input and/or calculation specifications) is not sequence checked. When ALTSEQ(*EXT) is specified, the alternate collating sequence is used when checking the sequence of compile-time arrays or tables. If the alternate sequence is not known until run-time, the sequence is checked at run-time; if the array or table is out of sequence, control passes to the RPG IV exception/error handling routine. A sequence (ascending or descending) must be specified if the LOOKUP operation, %LOOKUPxx built-in, or %TLOOKUPxx built-in is used to search an array or table for an entry to determine whether the entry is high or low compared to the search argument. If the SORTA operation code is used with an array, and no sequence is specified, an ascending sequence is assumed.
BASED(basing_pointer_name)
When the BASED keyword is specified for a data structure or standalone field, a basing pointer is created using the name specified as the keyword parameter. This basing pointer holds the address (storage location) of the based data structure or standalone field being defined. In other words, the name specified in positions 7-21 is used to refer to the data stored at the location contained in the basing pointer. Note: Before the based data structure or standalone field can be used, the basing pointer must be assigned a valid address.
Specifications
5-95
Definition-Specification Keywords
If an array is defined as a based standalone field it must be a run-time array. If a based field is defined within a subprocedure, then both the field and the basing pointer are local. | BINDEC(digits {: decimal-positions}) | The BINDEC keyword is a numeric data type keyword. It is used in a free-form definition to indicate that | the item has binary-decimal format. | It must be the first keyword. | The first parameter is required. It specifies the total number of digits. It can be a value between 1 and 9. | The second parameter is optional. It specifies the number of decimal positions. It can be a value between | zero and the number of digits. It defaults to zero. | Each parameter can be a literal or a named constant. If it is a named constant, the constant must be | defined prior to the definition statement. | In the following example | v field salary is defined as a binary-decimal field with 5 digits and 2 decimal places | v field age is defined as a binary-decimal field with 3 digits and the default of 0 decimal places | v field price is defined as a binary-decimal field with 7 digits and 3 decimal positions. The number of | decimal positions is defined using named constant NUM_DEC_POS. | | | | |
DCL-S DCL-S DCL-C DCL-S salary BINDEC(5 : 2); age BINDEC(3); NUM_DEC_POS 3; price BINDEC(7 : NUM_DEC_POS);
CCSID(number | *DFT)
This keyword sets the CCSID for graphic and UCS-2 definitions. number must be an integer between 0 and 65535. It must be a valid graphic or UCS-2 CCSID value. A valid graphic CCSID is 65535 or a CCSID with the EBCDIC double-byte encoding scheme (X'1200'). A valid UCS-2 CCSID has the UCS-2 encoding scheme (x'7200'). For program-described fields, CCSID(number) overrides the defaults set on the control specification with the CCSID(*GRAPH: *SRC), CCSID(*GRAPH: number), or CCSID(*UCS2: number) keyword. CCSID(*DFT) indicates that the default CCSID for the module is to be used. This is useful when the LIKE keyword is used since the new field would otherwise inherit the CCSID of the source field. If the keyword is not specified, the default graphic or UCS-2 CCSID of the module is assumed. (This keyword is not allowed for graphic fields when CCSID(*GRAPH : *IGNORE) is specified or assumed). If this keyword is not specified and the LIKE keyword is specified, the new field will have the same CCSID as the LIKE field. | CHAR(length) | The CHAR keyword is used in a free-form definition to indicate that the item is fixed-length character. | It must be the first keyword. | The parameter specifies the length in bytes. It can be between 1 and 16,773,104
5-96
Definition-Specification Keywords
| | The parameter can be a literal or a named constant. If it is a named constant, the constant must be defined prior to the definition statement.
| In the following example | v field cust_name is defined as a fixed-length character field with 100 characters. | v field message is defined as a fixed-length character field with 5000 characters. The length is defined | using named constant MSG_LEN. | | | |
DCL-S cust_name CHAR(100); DCL-C MSG_LEN 5000; DCL-S message CHAR(MSG_LEN);
| For information on defining a variable-length character item, see VARCHAR(length {:2 | 4}) on page | 5-147.
CLASS(*JAVA:class-name)
This keyword indicates the class for an object definition. class-name must be a constant character value. | | Note: The CLASS keyword is not used in a free-form definition. Instead, the class information is specified by the OBJECT keyword.
CONST{(constant)}
The CONST keyword is used v To specify the value of a named constant v To indicate that a parameter passed by reference is read-only. When specifying the value of a named constant, the CONST keyword itself is optional. That is, the constant value can be specified with or without the CONST keyword. The parameter must be a literal, figurative constant, or built-in-function. The constant may be continued on subsequent lines by adhering to the appropriate continuation rules (see Continuation Rules on page 5-7 for further details). If a named constant is used as a parameter for the keywords DIM, OCCURS, PERRCD, or OVERLAY, the named constant must be defined prior to its use. When specifying a read-only reference parameter, you specify the keyword CONST on the definition specification of the parameter definition on both the prototype and procedure interface. No parameter to the keyword is allowed. When the keyword CONST is specified, the compiler may copy the parameter to a temporary and pass the address of the temporary. Some conditions that would cause this are: the passed parameter is an expression or the passed parameter has a different format.
Attention!
Do not use this keyword on a prototype definition unless you are sure that the parameter will not be changed by the called program or procedure. If the called program or procedure is compiled using a procedure interface with the same prototype, you do not have to worry about this, since the compiler will check this for you.
Specifications
5-97
Definition-Specification Keywords
Although a CONST parameter cannot be changed by statements within the procedure, the value may be changed as a result of statements outside of the procedure, or by directly referencing a global variable. Passing a parameter by constant value has the same advantages as passing by value. In particular, it allows you to pass literals and expressions.
CTDATA
The CTDATA keyword indicates that the array or table is loaded using compile-time data. The data is specified at the end of the program following the ** or **CTDATA(array/table name) specification. When an array or table is loaded at compilation time, it is compiled along with the source program and included in the program. Such an array or table does not need to be loaded separately every time the program is run. | DATE{(format{separator})} | The DATE keyword is used in a free-form definition to indicate that the item has type date. | It must be the first keyword. | The parameter is optional. It specifies the date format and separator. See Date Data Type on page 4-73 | for information on the default format for date items. | In the following example, field date_dft is defined as a date field with the default format for the module, | and field date_mdy is defined with *MDY as the format and hyphen as the separator. | | |
DCL-S date_dft DATE; DCL-S date_mdy DATE(*MDY-);
DATFMT(format{separator})
The DATFMT keyword specifies the internal date format, and optionally the separator character, for any of these items of type Date: standalone field; data-structure subfield; prototyped parameter; or return value on a prototype or procedure-interface definition. This keyword will be automatically generated for an externally described data structure subfield of type Date and determined at compile time. If DATFMT is not specified, the Date field will have the date format and separator as specified by the DATFMT keyword on the control specification, if present. If none is specified on the control specification, then it will have *ISO format. | Note: The DATFMT keyword is not used in a free-form definition. Instead, the date format is specified as | the parameter of the DATE keyword. See Table 4-3 on page 4-73 for valid formats and separators. For more information on internal formats, see Internal and External Formats on page 4-49.
DESCEND
The DESCEND keyword describes the sequence of the data in any of the following: v An array v A table loaded at prerun-time or compile time v A prototyped parameter See also ASCEND on page 5-95. Descending sequence means that the array or table entries must start with the highest data entry (according to the collating sequence) and go to the lowest. Items with equal value are allowed.
5-98
Definition-Specification Keywords
A prerun-time array or table is checked for the specified sequence at the time the array or table is loaded with data. If the array or table is out of sequence, control passes to the RPG IV exception/error handling routine. A run-time array (loaded by input and/or calculation specifications) is not sequence checked. When ALTSEQ(*EXT) is specified, the alternate collating sequence is used when checking the sequence of compile-time arrays or tables. If the alternate sequence is not known until run-time, the sequence is checked at run-time; if the array or table is out of sequence, control passes to the RPG IV exception/error handling routine. A sequence (ascending or descending) must be specified if the LOOKUP operation, %LOOKUPxx built-in, or %TLOOKUPxx built-in is used to search an array or table for an entry to determine whether the entry is high or low compared to the search argument. If the SORTA operation code is used with an array, and no sequence is specified, an ascending sequence is assumed.
DIM(numeric_constant)
The DIM keyword defines the number of elements in an array, table, a prototyped parameter, array data structure, or a return value on a prototype or procedure-interface definition. The numeric constant must have zero (0) decimal positions. It can be a literal, a named constant or a built-in function. The constant value does not need to be known at the time the keyword is processed, but the value must be known at compile-time. When DIM is specified on a data structure definition, the data structure must be a qualified data structure, and subfields must be referenced as fully qualified names, i.e. "dsname(x).subf". Other array keywords, such as CTDATA, FROMFILE, TOFILE, and PERRCD are not allowed with an array data structure definition.
DTAARA keyword
The syntax of the DTAARA keyword is different in free-form and fixed-form specifications. Free-form standalone field or subfield DTAARA{(name)}. See Free-form DTAARA keyword for a field or subfield on page 5-100. Free-form data structure DTAARA{{(name)} {*AUTO} {*USRCTL}}. See Free-form DTAARA keyword for a data structure on page 5-101. Fixed-form DTAARA{({*VAR:} data_area_name)}. See Fixed-form DTAARA keyword on page 5-102. | | | | Note: An unquoted name is handled differently in free-form and fixed-form definitions. Consider the DTAAARA(name) keyword. If it is in a free-form definition, name is assumed to be the name of a named constant or variable, where the named constant or variable holds the name of the data area at runtime. If it is in a fixed-form definition, *LIBL/NAME is assumed to be the name of the data area at runtime. The DTAARA keyword is used to associate a standalone field, data structure, data-structure subfield or data-area data structure with an external data area. The DTAARA keyword has the same function as the *DTAARA DEFINE operation code (see *DTAARA DEFINE on page 6-175). The DTAARA keyword can only be used in the main source section. It cannot be used in a subprocedure.
Specifications
5-99
Definition-Specification Keywords
You can create three kinds of data areas: v *CHAR Character v *DEC Numeric v *LGL Logical You can also create a DDM data area (type *DDM) that points to a data area on a remote system of one of the three types above. | | | | | Only character, numeric (excluding float numeric), and indicator types are allowed to be associated with data areas. The actual data area on the system must be of the same type as the field in the program, with the same length and decimal positions. Indicator fields can be associated with either a logical data area or a character data area. If you want to store other types in a data area, you can use a data structure for the data area, and code the subfields of any type, except pointers. Pointers cannot be stored in data areas.
Note: 1. You cannot specify *CURLIB as the library name. 2. If you specify a data area name without a library name, *LIBL is used. | 3. The name must be in the correct case. For example, if the data area name is in a variable, and the | variable has the value 'qtemp/mydta', the data area will not be found. Instead, it should have the | value 'QTEMP/MYDTA'. | | | | Attention: If you specify a variable for the name of a data area data structure, then this variable must have the value set before the program starts. This can be done by initializing the variable, passing the variable as an entry parameter, or sharing the variable with another program through the IMPORT and EXPORT keywords.
| Free-form DTAARA keyword for a field or subfield: The optional parameter of the DTAARA keyword | for a free-form field or subfield definition is the external name of the data area. If the parameter is not | specified, the name of the field or subfield is used as the external name. | Examples | In the following example, the data area is defined without a parameter, so the field name is used as the | external name. Data area *LIBL/MYDTAARA will be used at runtime. | |
DCL-DS mydtaara CHAR(100) DTAARA;
| In the following example, the DTAARA keyword is specified without a parameter, so the subfield name | is used as the external name. Data area *LIBL/MYDTAARA will be used at runtime. | | | |
DCL-DS data_struct; mydtaara CHAR(100) DTAARA; END-DS;
5-100
Definition-Specification Keywords
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Free-form DTAARA keyword for a data structure: The parameters of the DTAARA keyword for a free-form data structure definition are *AUTO The data structure is a data area data structure. If *AUTO is specified, and you want to use the data area with the IN, OUT, or UNLOCK operation codes, you must also specify the *USRCTL parameter. *USRCTL The data structure is a user-controlled data area, meaning that it can be used with the IN, OUT, or UNLOCK operation codes. If the *AUTO parameter is not specified, *USRCTL is the default. If the data structure does not have a name, the data structure can only be affected when the operand of the IN, OUT, or UNLOCK operation is *DTAARA, meaning that the operation will work with all the user-controlled data areas in the module. data area name The name parameter can be a literal, named constant, or variable. See Specifying the name of a data area in a literal or variable on page 5-100 for more information. If the name parameter is specified, it must be the last parameter. If the name parameter is not specified, the data structure name is used. If the data structure name is also not specified, the *LDA data area is used at runtime. Examples In the following example, the data area is defined only with the *AUTO parameter, so it is a data area data structure. It cannot be used with the IN, OUT, or UNLOCK operation codes. The name is not specified, so data area *LIBL/MYDTAARA is used at runtime.
DCL-DS info DTAARA(*AUTO); company CHAR(50); city CHAR(25); END-DS;
In the following example, the data area is defined with both the *AUTO and *USRCTL parameters, so it is a data area data structure that can also be used with the IN, OUT, or UNLOCK operation codes. The name parameter is specified, so data area 'MYLIB/MYDTAARA' will be used at runtime.
DCL-DS info DTAARA(*AUTO : *USRCTL : MYLIB/MYDTAARA); company CHAR(50); city CHAR(25); END-DS;
In the following example, the data area is defined without a name. The DTAARA keyword is specified with only the *AUTO parameter. Since the data area name is not specified in either the data structure name or the DTAARA keyword, the *LDA data area is used at runtime.
DCL-DS *N DTAARA(*AUTO); company CHAR(50); city CHAR(25); END-DS;
In the following example, the data structure does not have a name, and the *AUTO parameter is not used for the DTAARA keyword. The IN operation specifies *DTAARA, so data area MYLIB/MYDTAARA will be read into the unnamed data area when the IN operation is used at runtime. After the IN operation,
Specifications
5-101
Definition-Specification Keywords
| subfield subf will hold the contents of the data area. | | | | | | |
DCL-DS *N DTAARA(MYDTAARA); subf CHAR(50); END-DS; IN *DTAARA; DSPLY subf;
| Fixed-form DTAARA keyword: In a fixed-form specification, the DTAARA keyword can be specified in | the following ways: DTAARA The external name of the data area is not specified, so the name specified in positions 7-21 is also the name of the external data area. If neither the parameter nor the data-structure name is specified, then the default is *LDA. DTAARA(name> The name parameter is used as the external name of the data area at runtime. For example, if you specify DTAARA(mydtaara), then data area *LIBL/MYDTAARA will be used at runtime. You can also specify *LDA or *PDA as the parameter of the DTAARA keyword. DTAARA(character-literal> The value of character-literal parameter is to determine the name of the data area at runtime. See Specifying the name of a data area in a literal or variable on page 5-100 for more information. DTAARA(*VAR : name> The name parameter can be a named constant or a variable. See Specifying the name of a data area in a literal or variable on page 5-100 for more information. When the DTAARA keyword is specified, the IN, OUT, and UNLOCK operation codes can be used on the data area. If position 23 of the Definition specification for a data structure contains a U, the data structure is a data area data structure.
EXPORT{(external_name)}
The specification of the EXPORT keyword allows a globally defined data structure or standalone field defined within a module to be used by another module in the program. The storage for the data item is allocated in the module containing the EXPORT definition. The external_name parameter, if specified, must be a character literal or constant. | In a free-form definition, you can specify *DCLCASE for the external_name parameter, indicating that the | external name of the item is the same as the name of the item, in the same case as the name is specified. | See Specifying *DCLCASE as the External Name on page 5-111. The EXPORT keyword on the definition specification is used to export data items and cannot be used to export procedure names. To export a procedure name, use the EXPORT keyword on the procedure specification. Note: The initialization for the storage occurs when the program entry procedure (of the program containing the module) is first called. RPG IV will not do any further initialization on this storage, even if the procedure ended with LR on, or ended abnormally on the previous call. The following restrictions apply when EXPORT is specified: v Only one module may define the data item as exported v You cannot export a field that is specified in the Result-Field entry of a PARM in the *ENTRY PLIST
5-102
Definition-Specification Keywords
v Unnamed data structures cannot be exported v BASED data items cannot be exported v The same external field name cannot be specified more than once per module and also cannot be used as an external procedure name v IMPORT and EXPORT cannot both be specified for the same data item. For a multiple-occurrence data structure or table, each module will contain its own copy of the occurrence number or table index. An OCCUR or LOOKUP operation in any module will have only a local impact since the occurrence number or index is local to each module. See also IMPORT{(external_name)} on page 5-112. Tip: The keywords IMPORT and EXPORT allow you to define a "hidden" interface between modules. As a result, use of these keywords should be limited only to those data items which are global throughout the application. It is also suggested that this global data be limited to things like global attributes which are set once and never modified elsewhere. | | | | |
EXT
The EXT keyword is used in a free-form data structure definition to indicate that the data structure is externally-described. If the EXTNAME keyword is not also specified, the name of the data structure is used to locate the external file that provides the subfield definitions. If the EXT keyword is specified, it must be the first keyword.
EXTFLD{(field_name)}
| | The EXTFLD keyword is used to rename a subfield in an externally described data structure. In a free-form definition, it is also used to indicate that the subfield is an external subfield. Enter the external name of the subfield as the parameter to the EXTFLD keyword. v In a free-form definition, the EXTFLD keyword must be the first keyword. If the name of the subfield is the same as the external name of the field, the parameter is optional. If specified, the external name must be specified as a character literal or a named constant. If it is a named constant, the constant must be defined prior to the definition statement. v In a fixed-form definition, enter the external name of the subfield as the parameter to the EXTFLD keyword, and specify the name to be used in the program in the Name field (positions 7-21). The external name can be either a simple name or a character literal. If a character literal is specified, the external name must be specified in the correct case. For example, if the external name is MYFIELD, the file-name parameter could be specified in a fixed-form definition as a name in mixed case such as myField or myfield, but if specified as a literal it must be 'MYFIELD'. In the following example, three of the external field names in the file are NAME, ADR, and ID. 1. Subfield name is initialized to 'UNKNOWN'. a. In the free-form version of the code, the parameter for EXTFLD is not needed because the subfield name is the same as the external name. b. In the fixed-form version of the code, the EXTFLD keyword is not specified, because the subfield is not being renamed. 2. Subfield address is renamed from external field ADR. a. In the free-form version of the code, the external name is specified as a literal. b. In the fixed-form version of the code, the external name is specified as a simple name. 3. Subfield id_number is renamed from external field ID and initialized to -1.
Specifications
| | | | | | |
5-103
Definition-Specification Keywords
a. In the free-form version of the code, the external name is specified as a named constant, ID_EXT_NAME whose value is 'ID'. b. In the fixed-form version of the code, the external name is specified as a literal.
DCL-C ID_EXT_NAME ID; 3a DCL-DS custInfo EXTNAME(CUSTMAST); name EXTFLD INZ(UNKNOWN); 1a address EXTFLD(ADR); 2a id_number EXTFLD(ID_EXT_NAME) INZ(-1); END-DS; D custInfo D name D address D id_number E DS E E E
3a
3b
# If the name is not a valid simple RPG name, it must be specified as a literal. For example, to rename # external field A.B, specify EXTFLD('A.B'). The keyword is optional. If not specified, the name extracted from the external definition is used as the data-structure subfield name. If the PREFIX keyword is specified for the data structure, the prefix will not be applied to fields renamed with EXTFLD. Figure 5-16 on page 5-94 shows an example of the EXTFLD keyword with the ALIAS keyword.
EXTFMT(code)
The EXTFMT keyword is used to specify the external data type for compile-time and prerun-time numeric arrays and tables. The external data type is the format of the data in the records in the file. This entry has no effect on the format used for internal processing (internal data type) of the array or table in the program. Note: The values specified for EXTFMT will apply to the files identified in both the TOFILE and FROMFILE keywords, even if the specified names are different. The possible values for the parameter are: B C I L R P S U F Note: 1. If the EXTFMT keyword is not specified, the external format defaults to 'S' for non-float arrays and tables, and to the external display float representation for float pre-runtime arrays and tables. 2. For compile-time arrays and tables, the only values allowed are S, L, and R, unless the data type is float, in which case the EXTFMT keyword is not allowed. The data for the array or table is in binary format. The data for the array or table is in UCS-2 format. The data for the array or table is in integer format. The data for a numeric array or table element has a preceding (left) plus or minus sign. The data for a numeric array or table element has a following (right) plus or minus sign. The data for the array or table is in packed decimal format. The data for the array or table is in zoned decimal format. The data for the array or table is in unsigned format. The data for the array or table is in float numeric format.
5-104
Definition-Specification Keywords
3. When EXTFMT(I) or EXTFMT(U) is used, arrays defined as having 1 to 5 digits will occupy 2 bytes per element. Arrays defined as having 6 to 10 digits will occupy 4 bytes per element. Arrays defined as having 11 to 20 digits will occupy 8 bytes per element. 4. The default external format for UCS-2 arrays is character. The number of characters allowed for UCS-2 compile-time data is the number of double-byte characters in the UCS-2 array. If graphic data is included in the data, the presence of double-byte data and the shift-out and shift-in characters in the data will reduce the actual amount of data that can be placed in the array element; the rest of the element will be padded with blanks. For example, for a 4-character UCS-2 array, only one double-byte character can be specified in the compile-time data; if the compile-time data were 'oXXi', where 'XX' is converted to the UCS-2 character U'yyyy', the UCS-2 element would contain the value U'yyyy002000200020'.
EXTNAME(file-name{:format-name}{:*ALL| *INPUT|*OUTPUT|*KEY})
The EXTNAME keyword is used to specify the name of the file which contains the field descriptions used as the subfield description for the data structure being defined. The file_name parameter is required. Optionally a format name may be specified to direct the compiler to a specific format within a file. If format_name parameter is not specified the first record format is used. v In a free-form definition, the file-name and format-name parameters must be character literals or named constants representing character literals. If a parameter is a named constant, the constant must be defined prior to the definition statement. v In a fixed-form definition, the file-name and format-name parameters can be either names or character literals. If a character literal is specified, the file or format name name must be specified in the correct case. For example, if the external file is MYFILE, the file-name parameter could be specified as a name in mixed case such as myFile or myfile, but if specified as a literal it must be 'MYFILE'. If the file-name is a character literal, it can be in any of the following forms
LIBRARY/FILE FILE *LIBL/FILE
| | | | |
The last parameter specifies which fields in the external record to extract: v *ALL extracts all fields. v *INPUT extracts just input capable fields. v *OUTPUT extracts just output capable fields. v *KEY extracts just key fields. If this parameter is not specified, the compiler extracts the fields of the input buffer. Note: 1. If the format-name is not specified, the record defaults to the first record in the file. 2. For *INPUT and *OUTPUT, subfields included in the data structure occupy the same start positions as in the external record description. | If an externally-described data structure (EXT keyword for an free-form definition, or E in position 22 for | a free-form definition, and the EXTNAME keyword is not specified, the data structure name is used for | the external name. The compiler will generate the following definition specification entries for all fields of the externally described data structure: # v Subfield name (Name will be the same as the external name, unless the ALIAS keyword is specified for the data structure, or the is field renamed by the EXTFLD keyword, or the PREFIX keyword on a # definition specification is used to apply a prefix). #
Specifications
5-105
Definition-Specification Keywords
v Subfield length v Subfield internal data type (will be the same as the external type, unless the CVTOPT control specification keyword or command parameter is specified for the type. In that case the data type will be character). All data structure keywords except LIKEDS and LIKEREC are allowed with the EXTNAME keyword.
EXTPGM{(name)}
| The EXTPGM keyword indicates that the prototype represents a dynamic call to a program. | The parameter specifies the external name of the program whose prototype is being defined. The name | can be a character constant or a character variable. | The parameter is optional if the prototype name is not longer than 10 characters. If the parameter is not | specified, the external program name is the same as the upper-case form of the prototype name. The | following example defines a prototype for program 'QCMDEXC'. | | |
DCL-PR qcmdExc EXTPGM; ...
| If neither EXTPGM or EXTPROC is specified for a prototype, then the compiler assumes that you are | defining a prototype for a procedure, and assigns the external procedure name to be the upper-case form | of the prototype name. # Any parameters defined by a prototype or procedure interface with EXTPGM must be passed by # reference. In addition, you cannot define a return value.
EXTPROC({*CL|*CWIDEN|*CNOWIDEN| {*JAVA:class-name:}}name)
The EXTPROC keyword can have one of the following formats:
EXTPROC(*CL:name) Specifies an external procedure that is written in ILE CL, or an RPG procedure to be called by ILE CL. Use *CL if your program uses return values with data types that CL handles differently from RPG. For example, use *CL when prototyping an RPG procedure that is to be called by a CL procedure when the return value is 1A. EXTPROC(*CWIDEN:name|*CNOWIDEN:name) Specifies an external procedure that is written in ILE C, or an RPG procedure to be called by ILE C. # # # # # Use *CNOWIDEN or *CWIDEN if your program uses return values or parameters passed by value with data types that C handles differently from RPG. Use *CWIDEN or *CNOWIDEN when defining an RPG procedure that is to be called by C, or when defining the prototype for a C procedure, where the returned value or a parameter passed by value is 1A, 1G or 1C, 5U, 5I, or 4F. Use *CNOWIDEN if the ILE C source contains #pragma argument(procedure-name,nowiden) for the procedure; otherwise, use *CWIDEN. EXTPROC(*JAVA:class-name:name) Specifies a method that is written in Java, or an RPG native method to be called by Java. The first parameter is *JAVA. The second parameter is a character constant containing the class of the method. The third parameter is a character constant containing the method name. The special method name *CONSTRUCTOR means that the method is a constructor; this method can be used to instantiate a class (create a new class instance).
5-106
Definition-Specification Keywords
For more information about invoking Java procedures, see Rational Development Studio for i: ILE RPG Programmer's Guide. EXTPROC(name) Specifies an external procedure that is written in or to be called by RPG or COBOL. This format should also be used for a procedure that can be called by any of RPG, COBOL, C, or CL; in this case, you must ensure that the return value and the parameters do not have any of the problems listed above for *CL, *CWIDEN, and *CNOWIDEN. The EXTPROC keyword indicates the external name of the procedure whose prototype is being defined. The name can be a character constant, or procedure pointer. | In a free-form definition, you can specify *DCLCASE as the name indicating that the external name is | derived from the name of item being defined, in the same case as the name was specified. See | Specifying *DCLCASE as the External Name on page 5-111. When EXTPROC is specified, a bound call will be done. If neither EXTPGM or EXTPROC is specified, then the compiler assumes that you are defining a procedure, and assigns it the external name found in positions 7-21. # # # # If the name specified for EXTPROC (or the prototype or procedure name, if neither EXTPGM or EXTPROC is specified or if EXTPROC(*DCLCASE) is specified) starts with "CEE" or an underscore ('_'), the compiler will treat this as a system built-in. To avoid confusion with system provided APIs, you should not name your procedures starting with "CEE". For example, to define the prototype for the procedure SQLAllocEnv, that is in the service program QSQCLI, the following definition specification could be coded:
D SQLEnv PR EXTPROC(SQLAllocEnv)
If a procedure pointer is specified, it must be assigned a valid address before it is used in a call. It should point to a procedure whose return value and parameters are consistent with the prototype definition. # # # # # When a prototype is specified for a procedure, the EXTPROC keyword is specified for the prototype. Otherwise, the EXTPROC keyword is specified for the procedure interface. It is only necessary to explicitly specify a prototype when the procedure will be called from another RPG module. When the procedure is only called from within the same module, or when it is only called by non-RPG callers, the prototype can be implicitly derived from the procedure interface. Figure 5-17 on page 5-108 shows an example of the EXTPROC keyword with a procedure pointer as its parameter.
Specifications
5-107
Definition-Specification Keywords
* Assume you are calling a procedure that has a procedure * pointer as the EXTPROC. Here is how the prototype would * be defined: D DspMsg PR 10A EXTPROC(DspMsgPPtr) D Msg 32767A D Length 4B 0 VALUE * Here is how you would define the prototype for a procedure * that DspMsgPPtr could be assigned to. D MyDspMsg PR LIKE(DspMsg) D Msg 32767A D Length 4B 0 VALUE * Before calling DSPMSG, you would assign DSPMSGPPTR * to the actual procedure name of MyDspMsg, that is * MYDSPMSG. C EVAL DspMsgPPtr = %paddr(MYDSPMSG) C EVAL Reply = DspMsg(Msg, %size(Msg)) ... P MyDspMsg B Figure 5-17. Using EXTPROC with a Procedure Pointer
char RPG_PROC (short s, float f); char C_PROC (short s, float f); #pragma argument(RPG_PROC, nowiden) #pragma argument(C_PROC, nowiden) /* "fn" calls the RPG procedure with unwidened parameters, /* and expects the return value to be passed according to C /* conventions. void fn(void) { char c; c = RPG_PROC(5, 15.3); } /* Function C_PROC expects its parameters to be passed unwidened.*/ /* It will return its return value using C conventions. */ char C_PROC (short s, float f); { char c = x; if (s == 5 || f < 0) { return S; } else { return F; } } Figure 5-18. Using EXTPROC with *CNOWIDEN - C Code */ */ */
5-108
Definition-Specification Keywords
D RPG_PROC D short D float D C_RPOC D short D float P RPG_PROC D D short D float D C C C C C C P char
PR
1A EXTPROC(*CNOWIDEN : RPG_PROC) 5I 0 VALUE 4F VALUE 1A EXTPROC(*CNOWIDEN : C_PROC) 5I 0 VALUE 4F VALUE EXPORT 1A 5I 0 VALUE 4F VALUE 1A c = C_PROC(4 : 14.7) on the values of the parameters short < float L G
PR
B PI
* Call the C procedure EVAL * Return the value depending IF RETURN ELSE RETURN ENDIF E
char RPG_PROC (short s, float f); char C_PROC (short s, float f); /* Function "fn" calls the RPG procedure with widened parameters,*/ /* and expects the return value to be passed according to C */ /* conventions. */ void fn(void) { char c; c = RPG_PROC(5, 15.3); } /* Function C_PROC expects its parameters to be passed widened. /* It will return its return value using C conventions. char C_PROC (short s, float f); { char c = x; if (s == 5 || f < 0) { return S; } else { return F; } } Figure 5-20. Using EXTPROC with *CWIDEN - C Code */ */
Specifications
5-109
Definition-Specification Keywords
D RPG_PROC D short D float D C_PROC D short D float P RPG_PROC D D short D float D C C C C C C P char
PR
1A EXTPROC(*CWIDEN : RPG_PROC) 5I 0 VALUE 4F VALUE 1A EXTPROC(*CWIDEN : C_PROC) 5I 0 VALUE 4F VALUE EXPORT 1A 5I 0 VALUE 4F VALUE 1A c = C_PROC(4 : 14.7) on the values of the parameters short < float L G
PR
B PI
* Call the C procedure EVAL * Return the value depending IF RETURN ELSE RETURN ENDIF E
/* CL procedure CL_PROC */ DCL &CHAR1 TYPE(*CHAR) LEN(1) /* Call the RPG procedure */ CALLPRC RPG_PROC RTNVAR(&CHAR1) Figure 5-22. Using EXTPROC with *CL - CL Code
D RPG_PROC P RPG_PROC D C P
PR B PI RETURN E
1A 1A X
P isValidCust B EXPORT D PI N EXTPROC(*CL : isValidCust) D custId 10A CONST D isValid S N INZ(*OFF) /free ... calculations using the "custId" parameter return isValid; /end-free P E Figure 5-24. Using EXTPROC on a procedure interface for a procedure intended to be called only by CL callers
5-110
Definition-Specification Keywords
| | | | | | | | | | | |
DCL-S currentCity LIKE(name_T) EXPORT(*DCLCASE); DCL-DS customerOptions LIKEDS(custOpt_T) IMPORT(*DCLCASE);
Specifying *DCLCASE as the External Name: In a free-form definition, you can specify *DCLCASE as the external name for the EXTPROC, EXPORT, and IMPORT keywords. *DCLCASE with the EXPORT and IMPORT keywords The external name of the item is the same as the name of the item, in the same case as the name is specified. In the following example v the external name of exported field currentCity is 'currentCity' v the external name of imported data structure customerOptions is 'customerOptions'.
The external name of the procedure or method is the same as the name of the prototype or procedure interface containing the EXTPROC keyword, in the same case as the name is specified. If the EXTPROC keyword is specified in a procedure-interface definition, and the procedure interface has no name, the then the external name is the same as the name of the procedure, specified in the same case as the procedure name is specified on the DCL-PROC statement. In the following example 1. The external name for the getCustomerCity prototype is 'getCustomerCity'. 2. The method name for the getBytes prototype is 'getBytes'. 3. The external name for the getNextOrder procedure is 'getNextOrder', from the DCL-PROC statement ( 3a ) beginning the procedure, because the procedure name is not specified for the procedure interface ( 3b ). 4. The external name for the addQuotes procedure is 'addQuotes', from the procedure interface statement ( 4b ), because the procedure name is specified for the procedure interface. The different case specified for the name in the DCL-PROC statement ( 4a ) is ignored.
DCL-PR getBytes EXTPROC(*JAVA : java.lang.String : *DCLCASE); ... DCL-PROC getNextOrder; 3a DCL-PI *N EXTPROC(*DCLCASE); ... 3b
4b
| | |
FLOAT(bytes)
The FLOAT keyword is a numeric data type keyword. It is used in a free-form definition to indicate that the item has float format.
Specifications
5-111
Definition-Specification Keywords
| It must be the first keyword. | The parameter specifies the length in bytes. It must be one of 4 or 8. | The parameter can be a literal or a named constant. If it is a named constant, the constant must be | defined prior to the definition statement. | In the following example | v field variance is defined as an 8-byte float field. | |
DCL-S variance FLOAT(8);
FROMFILE(file_name)
The FROMFILE keyword is used to specify the file with input data for the prerun-time array or table being defined. The FROMFILE keyword must be specified for every prerun-time array or table used in the program. See also TOFILE(file_name) on page 5-146. | GRAPH(length) | The GRAPH keyword is used in a free-form definition to indicate that the item is fixed-length graphic. | It must be the first keyword. | The parameter specifies the length in double-byte characters. It can be between 1 and 8,386,552. | The parameter can be a literal or a named constant. If it is a named constant, the constant must be | defined prior to the definition statement. | In the following example | v field cust_name is defined as a fixed-length graphic field with 100 characters. | v field message is defined as a fixed-length graphic field with 5000 characters. The length is defined using named constant MSG_LEN. | | | | |
DCL-S cust_name GRAPH(100); DCL-C MSG_LEN 5000; DCL-S message GRAPH(MSG_LEN);
| For information on defining a variable-length graphic item, see VARGRAPH(length {:2 | 4}) on page | 5-147.
IMPORT{(external_name)}
The IMPORT keyword specifies that storage for the data item being defined is allocated in another module, but may be accessed in this module. The external_name parameter, if specified, must be a character literal or constant. | In a free-form definition, you can specify *DCLCASE for the external_name parameter, indicating that the | external name of the item is the same as the name of the item, in the same case as the name is specified. | See Specifying *DCLCASE as the External Name on page 5-111.
5-112
Definition-Specification Keywords
If a name is defined as imported but no module in the program contains an exported definition of the name, an error will occur at link time. See EXPORT{(external_name)} on page 5-102. The IMPORT keyword on the definition specification is used to import data items and cannot be used to import procedure names. Procedure names are imported implicitly, to all modules in the program, when the EXPORT keyword is specified on a procedure specification. The following restrictions apply when IMPORT is specified: v The data item may not be initialized (the INZ keyword is not allowed). The exporting module manages all initialization for the data. v An imported field cannot be defined as a compile-time or prerun-time array or table, or as a data area. (Keywords CTDATA, FROMFILE, TOFILE, EXTFMT, PERRCD, and DTAARA are not allowed.) v An imported field may not be specified as an argument to the RESET operation code since the initial value is defined in the exporting module. v v v v v You cannot specify an imported field in the Result-Field entry of a PARM in the *ENTRY PLIST. You cannot define an imported field as based (the keyword BASED is not allowed). This keyword is not allowed for unnamed data structures. The only other keywords allowed are DIM, EXTNAME, LIKE, OCCURS, and PREFIX. The same external field name cannot be specified more than once per module and also cannot be used as an external procedure name.
For a multiple-occurrence data structure or table, each module will contain its own copy of the occurrence number or table index. An OCCUR or LOOKUP operation in any module will have only a local impact since the occurrence number or index is local to each module. | | | | | | | | | | | |
DCL-S num_elems INT(10);
INT(digits)
The INT keyword is a numeric data type keyword. It is used in a free-form definition to indicate that the item has signed integer format. It must be the first keyword. The parameter specifies the length in digits. It must be one of 3, 5, 10 or 20, occupying 1, 2, 4, and 8 bytes respectively. The parameter can be a literal or a named constant. If it is a named constant, the constant must be defined prior to the definition statement. In the following example v field num_elems is defined as an integer field with 10 digits. It occupies 4 bytes in storage.
| | | | | |
IND
The IND keyword is used in a free-form definition to indicate that the item is an indicator. It must be the first keyword. In the following example v field found is defined as an indicator.
Specifications
5-113
Definition-Specification Keywords
INZ{(initial value)}
The INZ keyword initializes the standalone field, data structure, data-structure subfield, or object to the default value for its data type or, optionally, to the constant specified in parentheses. v For a program described data structure, no parameter is allowed for the INZ keyword. v For an externally described data structure, only the *EXTDFT parameter is allowed. v For a data structure that is defined with the LIKEDS keyword, the value *LIKEDS specifies that subfields are initialized in the same way as the parent data structure. This applies only to initialization specified by the INZ keyword on the parent subfield. It does not apply to initialization specified by the CTDATA or FROMFILE keywords. If the parent data structure has some subfields initialized by CTDATA or FROMFILE, the data structure initialized with INZ(*LIKEDS) will not have the CTDATA or FROMFILE data. v For an object, only the *NULL parameter is allowed. Every object is initialized to *NULL, whether or not you specify INZ(*NULL). The initial value specified must be consistent with the type being initialized. The initial value can be a literal, named constant, figurative constant, built-in function, or one of the special values *SYS, *JOB, *EXTDFT, *USER, *LIKEDS, or *NULL. When initializing Date or Time data type fields or named constants with Date or Time values, the format of the literal must be consistent with the default format as derived from the Control specification, regardless of the actual format of the date or time field. A UCS-2 field may be initialized with a character, UCS-2 or graphic constant. If the constant is not UCS-2, the compiler will implicitly convert it to UCS-2 at compile time. A numeric field may be initialized with any type of numeric literal. However, a float literal can only be used with a float field. Any numeric field can be initialized with a hexadecimal literal of 16 digits or fewer. In this case, the hexadecimal literal is considered an unsigned numeric value. Specifying INZ(*EXTDFT) initializes externally described data-structure subfields with the default values from the DFT keyword in the DDS. If no DFT or constant value is specified, the DDS default value for the field type is used. You can override the value specified in the DDS by coding INZ with or without a parameter on the subfield specification. Specifying INZ(*EXTDFT) on the external data structure definition, initializes all externally described subfields to their DDS default values. If the externally described data structure has additional program described subfields, these are initialized to the RPG default values. When using INZ(*EXTDFT), take note of the following: v If the DDS value for a date or time field is not in the RPG internal format, the value will be converted to the internal format in effect for the program. v External descriptions must be in physical files. v If *NULL is specified for a null-capable field in the DDS, the compiler will use the DDS default value for that field as the initial value. v If DFT('') is specified for a varying length field, the field will be initialized with a string of length 0. v INZ(*EXTDFT) is not allowed if the CVTOPT option is in effect. Specifying INZ(*USER) intializes any character field or subfield to the name of the current user profile. Character fields must be at least 10 characters long. If the field is longer than 10 characters, the user name is left-justified in the field with blanks in the remainder.
5-114
Definition-Specification Keywords
Date fields can be initialized to *SYS or *JOB. Time and Timestamp fields can be initialized to *SYS. Please see Initialization of Nested Data Structures on page 4-15 for a complete description of the use of the INZ keyword in the inititlization of nested data structures. A data structure, data-structure subfield, or standalone field defined with the INZ keyword cannot be specified as a parameter on an *ENTRY PLIST. Note: When the INZ parameter is not specified: v Static standalone fields and subfields of initialized data structures are initialized to their RPG default initial values (for example, blanks for character, 0 for numeric). v Subfields of uninitialized data structures (INZ not specified on the definition specification for the data structure) are initialized to blanks (regardless of their data type). This keyword is not valid in combination with BASED or IMPORT.
LEN(length)
The LEN keyword is used to define the length in characters of a Data Structure or character, UCS-2 or graphic definition. It is valid for Data Structure definitions, and for Prototype, Prototyped Parameter, Standalone Field and Subfield definitions where the type entry is A (Alphanumeric), C (UCS-2), or G (Graphic). | | Note: In free-form definitions, the LEN keyword is only used for data-structure definitions. For other definition types, the length of the item is specified as a parameter for the data-type keyword. Rules for the LEN keyword:: v The data type A, C or G must be specified in the Data-Type entry. v The LEN keyword cannot be specified if the Length entry is specified, or if the From and To entries are specified for subfields. The LEN keyword must be used to specify a length greater than 9,999,999. v Length adjustment for LIKE definitions cannot be done using the LEN keyword. v The length is specified in characters; for UCS-2 and Graphic definitions, each character represents two bytes.
* Use the LEN keyword to define a standalone field of one million * characters and a standalone array of 100 characters. D paragraph S A LEN(1000000) VARYING(4) D splitPara S A LEN(100) DIM(10000) * Use the LEN keyword to define a data structure of length 16000000, * and to define three subfields. Since the lengths of the parameters * are less than 9999999, they can be defined using from-and-to, or length * notation, or the LEN keyword. D info DS LEN(16000000) D name G LEN(100) OVERLAY(info : 14000001) D address 5000G OVERLAY(info : 14000301) D country 1 40G * Use the LEN keyword to define a prototype that returns a varying * UCS-2 value that is up to 5000 UCS-2 characters long, and to define * two alphanumeric parameters. Since the lengths of the parameters * are less than 9999999, they can be defined either using length notation * or the LEN keyword. D getDftDir PR C VARYING LEN(5000) D usrprf A LEN(10) CONST D type 5A CONST Figure 5-25. Examples of the LEN keyword
Specifications
5-115
Definition-Specification Keywords
LIKE(name {: length-adjustment})
The LIKE keyword is used to define an item like an existing one. For information about using LIKE with an object, see LIKE(object-name) on page 5-117. When the LIKE keyword is specified, the item being defined takes on the length and the data format of the item specified as the parameter. Standalone fields, prototypes, parameters, and data-structure subfields may be defined using this keyword. The parameter of LIKE can be a standalone field, a data structure, a data structure subfield, a parameter in a procedure interface definition, or a prototype name. The data type entry (position 40) must be blank. This keyword is similar to the *LIKE DEFINE operation code (see *LIKE DEFINE on page 6-174). However, it differs from *LIKE DEFINE in that the defined data takes on the data format and CCSID as well as the length. Note: Attributes such as ALTSEQ(*NONE), NOOPT, ASCEND, CONST and null capability are not inherited from the parameter of LIKE by the item defined. Only the data type, length, decimal positions, and CCSID are inherited. If the parameter of LIKE is a prototype, then the item being defined will have the same data type as the return value of the prototype. If there is no return value, then an error message is issued. | The length of the item being defined can be adjusted. You specify the length adjustment in the second | parameter of the LIKE keyword in free-form definitions, or the Length entry in fixed-form definitions. | The length adjust must be specified with either a positive (+) or negative (-) sign. Here are some considerations for using the LIKE keyword with different data types: v For character fields, the length adjustment is the number of additional (or fewer) characters. v For numeric fields, the length adjustment is the number of additional (or fewer) digits. For integer or unsigned fields, adjustment values must be such that the resulting number of digits for the field are 3, 5, 10, or 20. For float fields, length adjustment is not allowed. v For graphic or UCS-2 fields, the length adjustment is the number of additional (or fewer) graphic or UCS-2 characters (1 graphic or UCS-2 character = 2 bytes). v For date, time, timestamp, basing pointer, or procedure pointer fields, length adjustment is not allowed. When LIKE is used to define an array, the DIM keyword is still required to define the array dimensions. However, DIM(%elem(array)) can be used to define an array exactly like another array. Use LIKEDS to define a data structure like another data structure, with the same subfields.
| | | | | | | |
5-116
Definition-Specification Keywords
| | | | | | | | | | | | | | | | | | | | | | | | | | | | |
1 2
DCL-DS Struct; NameList LIKE(Name) DIM(20) INZ(*ALLX); END-DS; DCL-PR GetBonus LIKE(Salary : -2); Employee_Id INT(10) VALUE; END-PR; 3
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++ D.....................................Keywords+++++++++++++++++++++++++++++ D Name S 20 D Long_name S +5 LIKE(Name) 1 D D D D Struct NameList GetBonus Employee_Id DS LIKE(Name) DIM(20) INZ(*ALLX) PR -2 LIKE(Salary) 10I 0 VALUE 3 2
LIKE(object-name): You can use the LIKE keyword to specify that one object has the same class as a previously defined object. Only the values on the CLASS keyword are inherited.
* Variables MyString and OtherString are both Java String objects. D MyString S O CLASS(*JAVA D :java.lang.String) D OtherString S LIKE(MyString) * Proc is a Java method returning a Java String object D Proc PR EXTPROC(*JAVA:MyClass:meth) D LIKE(MyString) Figure 5-28. Defining objects LIKE other objects
Note: You cannot use the *LIKE DEFINE operation to define an object. You must use the LIKE keyword.
LIKEDS(data_structure_name)
The LIKEDS keyword is used to define a data structure, data structure subfield, prototyped return value, or prototyped parameter like another data structure. The subfields of the new item will be identical to the subfields of the parent data structure specified as the parameter to the LIKEDS keyword. A data structure defined using LIKEDS is automatically qualified even if the parent data structure is not qualified. The subfields must be referred to using the qualified notation DSNAME.SUBFIELDNAME. If the parent data structure has any unnamed subfields, the child data structure will have the same unnamed subfields. LIKEDS can be coded for subfields of a qualified data structure. When LIKEDS is coded on a data structure subfield definition, the subfield data structure is automatically defined as QUALIFIED. Subfields in a LIKEDS subfield data structure are referenced in fully qualified form: "ds.subf.subfa". Subfields defined with LIKEDS are themselves data structures, and can be used wherever a data structure is required.
Specifications
5-117
Definition-Specification Keywords
The values of the ALIGN and ALTSEQ keywords are inherited by the new data structure. The values of the OCCURS, DIM, NOOPT, and INZ keywords are not inherited. To initialize the subfields in the same way as the parent data structure, specify INZ(*LIKEDS).
* Data structure qualDs is a qualified data structure * with two named subfields and one unnamed subfield D qualDs DS QUALIFIED D a1 10A D 2A D a2 5P 0 DIM(3) * Data structure unqualDs is a non-qualified data structure * with one named subfield and one unnamed subfield D unqualDs DS D b1 5A D 5A * Data structure likeQual is defined LIKEDS(qualDs) D likeQual DS LIKEDS(qualDs) * Data structure likeUnqual is defined LIKEDS(unqualDs) D likeUnqual DS LIKEDS(unqualDs) /FREE // Set values in the subfields of the // parent data structures. qualDs.a1 = abc; qualDs.a2(1) = 25; b1 = xyz; // Set values in the subfields of the // child data structures. likeQual.a1 = def; likeQual.a2(2) = -250; likeUnqual.b1 = rst; // Display some of the subfields dsply likeQual.a1; // displays def dsply b1; // displays xyz Figure 5-29. Defining data structures using LIKEDS
D sysName DS qualified D lib 10A inz(*LIBL) D obj 10A D userSpace DS LIKEDS(sysName) INZ(*LIKEDS) // The variable "userSpace" was initialized with *LIKEDS, so the // first lib subfield was initialized to *LIBL. The second // obj subfield must be set using a calculation. C eval userSpace.obj = TEMPSPACE Figure 5-30. Using INZ(*LIKEDS)
5-118
Definition-Specification Keywords
P createSpace B D createSpace PI D name LIKEDS(sysName) /free if name.lib = *blanks; name.lib = *LIBL; endif; QUSCRTUS (name : *blanks : 4096 : : *USE : *blanks); /end-free P createSpace E Figure 5-31. Using a data structure parameter in a subprocedure
LIKEFILE(filename)
The LIKEFILE keyword is used to define a prototyped parameter as a file with the same characteristics as the filename parameter. Note: In the following discussion, the term file parameter is used for the parameter within the procedure that was defined using the LIKEFILE keyword, the term parent file is used for the parameter of the LIKEFILE keyword whose definition is used to derive the definition of the parameter, and the term passed file is used for the file that is passed to the procedure by the caller. Rules for the LIKEFILE keyword for prototyped parameters:: v The filename parameter of the LIKEFILE keyword must be a file that has been previously defined on a File specification. v File specification keywords cannot be specified with the LIKEFILE keyword on a Definition specification. The file parameter uses all the settings specified by the File specification of the file specifed as the parameter of the LIKEFILE keyword. v No other Definition keywords can be specified other than OPTIONS(*NOPASS) or OPTIONS(*OMIT). v File parameters can be passed only between RPG programs and procedures. They are not compatible with file parameters from other programming languages, such as COBOL files, or files returned by the C fopen() or open() functions. v A file is always passed by reference. The called procedure works directly on the same file as the calling procedure. For example, if the caller reads a record, and the called procedure updates the record and returns, the caller cannot update the record again. v If the blocking attribute for the file cannot be determined from the File specification, the BLOCK keyword must be specified for the filename parameter. Rules for passing and using file parameters: v The passed file must be defined with the same parent file as the prototyped parameter. v The file parameter is qualified. If the record formats of the parent file FILE1 are REC1 and REC2, then the record formats of the file parameter PARM must be referred to in the called procedure by PARM.REC1 and PARM.REC2. v Any settings for the passed file that are defined using File specification keywords are in effect for all procedures that access the file, either directly or through parameter passing. For example, if the EXTFILE keyword is specified with a variable holding the external file name, and a called procedure opens the file, then the value of the caller's variable will be used to set the name of the file to be opened. If the called procedure needs to change or access those variables associated with the file through keywords, the calling procedure must pass the variables as separate parameters. # v The file-feedback built-in functions %EOF(filename), %EQUAL(filename), %FOUND(filename), # %OPEN(filename), and %STATUS(filename) can be used in the called procedure to determine the # current state of the file parameter by specifying the name of the file parameter as the operand to the # built-in function.
Specifications
5-119
Definition-Specification Keywords
# # # For more information on passing a file parameter between modules, see Variables Associated with Files on page 3-105 and Example of passing a file and passing a data structure with the associated variables. on page 3-106.
* Define a file template to be used for defining actual files * and the file parameter Finfile_t IF E DISK TEMPLATE BLOCK(*YES) F EXTDESC(MYLIB/MYFILE) F RENAME(R01M2:inRec) * Define two actual files that can be passed to the file parameter Ffile1 LIKEFILE(infile_t) F EXTFILE(MYLIB/FILE1) Ffile2 LIKEFILE(infile_t) F EXTFILE(MYLIB/FILE2) * Define a data structure type for the file data D inData_t DS LIKEREC(infile_t.inRec:*INPUT) D TEMPLATE * Define the prototype for a procedure to handle the files D nextValidRec PR N D infile LIKEFILE(infile_t) D data LIKEDS(inData_t) * Define variables to hold the record data D f1Data DS LIKEDS(inData_t) D f2Data DS LIKEDS(inData_t) /FREE // Process valid records from each file until one // of the files has no more valid records DOW nextValidRec(file1 : f1Data) AND nextValidRec(file2 : f2Data); // ... process the data from the files ENDDO; *INLR = 1; /END-FREE * The procedure that will process the file parameter P nextValidRec B D nextValidRec PI N D infile LIKEFILE(infile_t) D data LIKEDS(inData_t) /FREE // Search for a valid record in the file parameter READ infile data; DOW NOT %EOF(infile); IF data.active = Y; RETURN *ON; // This is a valid record ENDIF; READ infile data; ENDDO; RETURN *OFF; // No valid record was found /END-FREE P nextValidRec E Figure 5-32. Passing a file as a parameter to a procedure
LIKEREC(intrecname{:*ALL|*INPUT|*OUTPUT |*KEY})
Keyword LIKEREC is used to define a data structure, data structure subfield, prototyped return value, or prototyped parameter like a record. The subfields of the data structure will be identical to the fields in the record. LIKEREC can take an optional second parameter which indicates which fields of the record to include in the data structure. These include: v *ALL All fields in the external record are extracted.
5-120
Definition-Specification Keywords
v *INPUT All input-capable fields are extracted. (This is the default.) v *OUTPUT All output-capable fields are extracted. v *KEY The key fields are extracted in the order that the keys are defined on the K specification in the DDS. The following should be taken into account when using the LIKEREC keyword: v The first parameter for keyword LIKEREC is a record name in the program. If the record name has been renamed, it is the internal name for the record. v The second parameter for LIKEREC must match the definition of the associated record of the file on the system. *INPUT is only allowed for input and update capable records; *OUTPUT is only allowed for output capable records; *ALL is allowed for any type of record; and *KEY is only allowed for keyed files. If not specified, the parameter defaults to *INPUT. v For *INPUT and *OUTPUT, subfields included in the data structure occupy the same start positions as in the external record description. v If a prefix was specified for the file, the specified prefix is applied to the names of the subfields.
# # # #
v Even if a field in the record is explicitly renamed on an input specification the external name (possibly prefixed) is used, not the internal name. # v If the file is defined with the ALIAS keyword, the alias names will be used for the subfields of the data # structure. Figure 5-8 on page 5-51 shows an example defining a data structure with the LIKEREC # keyword where the file is defined with the ALIAS keyword. v A data structure defined with LIKEREC is a QUALIFIED data structure. The names of the subfields will be qualified with the new data structure name, DS1.SUBF1. v LIKEREC can be coded for subfields of a qualified data structure. When LIKEREC is coded on a data structure subfield definition, the subfield data structure is automatically defined as QUALIFIED. Subfields in a LIKEREC subfield data structure are referenced in fully qualified form: "ds.subf.subfa". Subfields defined with LIKEREC are themselves data structures, and can be used wherever a data structure is required.
NOOPT
The NOOPT keyword indicates that no optimization is to be performed on the standalone field, parameter or data structure for which this keyword is specified. Specifying NOOPT ensures that the content of the data item is the latest assigned value. This may be necessary for those fields whose values are used in exception handling. Note: The optimizer may keep some values in registers and restore them only to storage at predefined points during normal program execution. Exception handling may break this normal execution sequence, and consequently program variables contained in registers may not be returned to their assigned storage locations. As a result, when those variables are used in exception handling, they may not contain the latest assigned value. The NOOPT keyword will ensure their currency. If a data item which is to be passed by reference is defined with the NOOPT keyword, then any prototype or procedure interface parameter definition must also have the NOOPT keyword specified. This requirement does not apply to parameters passed by value. Tip: Any data item defined in an OPM RPG/400 program is implicitly defined with NOOPT. So if you are creating a prototype for an OPM program, you should specify NOOPT for all parameters defined within the prototype. This will avoid errors for any users of the prototype. All keywords allowed for standalone field definitions, parameters, or data structure definitions are allowed with NOOPT.
Specifications
5-121
Definition-Specification Keywords
| OBJECT{(*JAVA:class-name)} | The OBJECT keyword is used in a free-form definition to indicate that the item has type object. | It must be the first keyword. | | | | | The parameters are optional if the OBJECT keyword is used to define the type of the return value for a Java constructor method. In this case, the class of the return value is the same as the class of the Java method, so it is not necessary to specify the class again. See EXTPROC({*CL|*CWIDEN|*CNOWIDEN| {*JAVA:class-name:}}name) on page 5-106 for information on defining the prototype for a Java constructor.
| Otherwise, both parameters are required. | The first parameter must be *JAVA. | The second parameter specifies the Java class of the object. See Object Data Type on page 4-77 for | information on specifying the Java class. The parameter must be a literal or a named constant. | Note: If you do specify the parameters for the OBJECT keyword when defining the return value for a | Java constructor, the class must be the same as the class specified by the EXTPROC keyword. | In the following example | v Field str is defined as an object field of class java.lang.String. | v The return value of the prototype newBigDecimal for the Java BigDecimal object constructor is defined | as an object. The OBJECT keyword has no parameters, so the class of the return value, | 'java.math.BigDecimal', is derived from the class specified in the EXTPROC keyword. | | | | | | |
DCL-S str OBJECT(*JAVA : java.lang.String); DCL-PR newBigDecimal OBJECT EXTPROC(*JAVA : java.math.BigDecimal : *CONSTRUCTOR); val VARUCS2(100) CONST; END-PR;
OCCURS(numeric_constant)
The OCCURS keyword allows the specification of the number of occurrences of a multiple-occurrence data structure. The numeric_constant parameter must be a value greater than 0 with no decimal positions. It can be a numeric literal, a built-in function returning a numeric value, or a numeric constant. The constant value does not need to be known at the time the keyword is processed, but the value must be known at compile-time. This keyword is not valid for a program status data structure, a file information data structure, or a data area data structure. If a multiple occurrence data structure contains pointer subfields, the distance between occurrences must be an exact multiple of 16 because of system storage restrictions for pointers. This means that the distance between occurrences may be greater than the length of each occurrence. The following is an example showing the storage allocation of a multiple occurrence data structure with pointer subfields.
5-122
Definition-Specification Keywords
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... * DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++ D DS1 DS OCCURS(2) D POINTER 16* D FLD5 5 D DS2 DS OCCURS(2) D CHAR16 16 D CHR5 5 Allocation of fields in storage. The occurrences of DS1 are 32 bytes apart, while the occurrences of DS2 are 21 bytes apart.
Figure 5-33. Storage Allocation of Multiple Occurrence Data Structure with Pointer Subfields
OPDESC
The OPDESC keyword specifies that operational descriptors are to be passed with the parameters that are defined within a prototype. When OPDESC is specified, operational descriptors are passed with all character or graphic parameters that are passed by reference. If you attempt to retrieve an operational descriptor for a parameter passed by value, an error will result. Note: Operational descriptors are not passed for UCS-2 fields. Using CALLP with a prototyped procedure whose prototype contains OPDESC is the same as calling a procedure using CALLB (D). Operational descriptors are also passed for procedures called within expressions. The keyword applies both to a prototype definition and to a procedure-interface definition. It cannot be used with the EXTPGM keyword. # Note: If you use the OPDESC keyword for your own procedures, the RTNPARM keyword can affect the # way you call APIs such as CEEDOD to get information about your parameters. See RTNPARM on page # 5-139 and %PARMNUM (Return Parameter Number) on page 6-111 for more information. For an example of the OPDESC keyword, see the service program example in the Rational Development Studio for i: ILE RPG Programmer's Guide.
5-123
Definition-Specification Keywords
v Whether the parameter should be trimmed of blanks before being passed. v Whether the parameter value should be right-adjusted in the passed parameter. v Whether the null-byte-map should be passed with the parameter. When OPTIONS(*NOPASS) is specified on a definition specification, the parameter does not have to be passed on the call. Any parameters following that specification must also have *NOPASS specified. When the parameter is not passed to a program or procedure, the called program or procedure will simply function as if the parameter list did not include that parameter. If the unpassed parameter is accessed in the called program or procedure, unpredictable results will occur. When OPTIONS(*OMIT) is specified, then the value *OMIT is allowed for that parameter. *OMIT is only allowed for CONST parameters and parameters which are passed by reference. For more information on omitted parameters, see the chapter on calling programs and procedures in Rational Development Studio for i: ILE RPG Programmer's Guide. OPTIONS(*VARSIZE) is valid only for parameters passed by reference that have a character, graphic, or UCS-2 data type, or that represent an array of any type. When OPTIONS(*VARSIZE) is specified, the passed parameter may be shorter or longer in length than is defined in the prototype. It is then up to the called program or subprocedure to ensure that it accesses only as much data as was passed. To communicate the amount of data passed, you can either pass an extra parameter containing the length, or use operational descriptors for the subprocedure. For variable-length fields, you can use the %LEN built-in function to determine the current length of the passed parameter. When OPTIONS(*VARSIZE) is omitted for fixed-length fields, you must pass at least as much data as is required by the prototype; for variable-length fields, the parameter must have the same declared maximum length as indicated on the definition. # # # # # # # Note: For the parameter passing options *NOPASS, *OMIT, and *VARSIZE, it is up to the programmer of the procedure to ensure that these options are handled. For example, if OPTIONS(*NOPASS) is coded and you choose to pass the parameter, the procedure must check that the parameter was passed before it accesses it. The compiler will not do any checking for this. If you call APIs such as CEEDOD or CEETSTA to get information about a parameter that uses these options, the RTNPARM keyword can affect the way you call the APIs. See RTNPARM on page 5-139 and %PARMNUM (Return Parameter Number) on page 6-111 for more information. When OPTIONS(*STRING) is specified for a basing pointer parameter passed by value or by constant-reference, you may either pass a pointer or a character expression. If you pass a character expression, a temporary value will be created containing the value of the character expression followed by a null-terminator (x'00'). The address of this temporary value will be passed to the called program or procedure. When OPTIONS(*RIGHTADJ) is specified for a CONST or VALUE parameter in a prototype, the character, graphic, or UCS-2 parameter value is right adjusted. This keyword is not allowed for a varying length parameter within a procedure prototype. Varying length values may be passed as parameters on a procedure call where the corresponding parameter is defined with OPTIONS(*RIGHTADJ). When OPTIONS(*TRIM) is specified for a CONST or VALUE parameter of type character, UCS-2 or graphic, the passed parameter is copied without leading and trailing blanks to a temporary. If the parameter is not a varying length parameter, the trimmed value is padded with blanks (on the left if OPTIONS(*RIGHTADJ) is specified, otherwise on the right). Then the temporary is passed instead of the original parameter. Specifying OPTIONS(*TRIM) causes the parameter to be passed exactly as though %TRIM were coded on every call to the procedure.
5-124
Definition-Specification Keywords
When OPTIONS(*STRING : *TRIM) is specified for a CONST or VALUE parameter of type pointer, the character parameter or %STR of the pointer parameter is copied without leading or trailing blanks to a temporary, a null-terminator is added to the temporary and the address of the temporary is passed. When OPTIONS(*NULLIND) is specified for a parameter, the null-byte map is passed with the parameter, giving the called procedure direct access to the null-byte map of the caller's parameter. Note the following rules for OPTIONS(*NULLIND). v ALWNULL(*USRCTL) must be in effect. v OPTIONS(*NULLIND) is not valid for parameters passed by value. v The only other options that can be specified with OPTIONS(*NULLIND) are *NOPASS and *OMIT. v Only variables may be passed as the parameter when OPTIONS(*NULLIND) is specified, and the variable must be an exact match even when CONST is specified. v If the parameter is a data structure, the passed parameter must be defined with the same parent LIKEDS or LIKEREC as the prototyped parameter. Furthermore, the null-capability of the prototyped parameter and passed parameter must match exactly. v A prototyped data structure parameter can have OPTIONS(*NULLIND) specified whether or not there are any null-capable subfields. v If a non-data-structure prototyped parameter is defined with OPTIONS(*NULLIND), the parameter in the procedure interface is defined as null-capable. v See Rational Development Studio for i: ILE RPG Programmer's Guide for information about using OPTIONS(*NULLIND) when the calling procedure or called procedure is not written using ILE RPG. You can specify more than one option. For example, to specify that an optional parameter can be shorter than the prototype indicates, you would code OPTIONS(*VARSIZE : *NOPASS). The following example shows how to code a prototype and procedure that use OPTIONS(*NOPASS) to indicate that a parameter is optional.
Specifications
5-125
Definition-Specification Keywords
* The following prototype describes a procedure that expects * either one or two parameters. D FormatAddress PR 45A D City 20A CONST D Province 20A CONST OPTIONS(*NOPASS) * The first call to FormatAddress only passes one parameter. The * second call passes both parameters. C EVAL A = FormatAddress(North York) C EVAL A = FormatAddress(Victoria : B.C.) C RETURN *---------------------------------------------------------------* FormatAddress: * This procedure must check the number of parameters since the * second was defined with OPTIONS(*NOPASS). * It should only use the second parameter if it was passed. *---------------------------------------------------------------P FormatAddress B D FormatAddress PI 45A D City 20A CONST D ProvParm 20A CONST OPTIONS(*NOPASS) D Province S 20A INZ(Ontario) * Set the local variable Province to the value of the second * parameter if it was passed. Otherwise let it default to * Ontario as it was initialized. C IF %PARMS > 1 C EVAL Province = ProvParm C ENDIF * Return the city and province in the form City, Province * for example North York, Ontario C RETURN %TRIMR(City) + , + Province P FormatAddress E Figure 5-34. Using OPTIONS(*NOPASS) to Indicate that a Parameter is Optional
The following example shows how to code a prototype and procedure using OPTIONS(*OMIT) to indicate that the special value *OMIT may be passed as a parameter.
5-126
Definition-Specification Keywords
FQSYSPRT O F 10 PRINTER USROPN * The following prototype describes a procedure that allows * the special value *OMIT to be passed as a parameter. * If the parameter is passed, it is set to 1 if an error * occurred, and 0 otherwise. D OpenFile PR D Error 1A OPTIONS(*OMIT) C SETOFF 10 * The first call to OpenFile assumes that no error will occur, * so it does not bother with the error code and passes *OMIT. C CALLP OpenFile(*OMIT) * The second call to OpenFile passes an indicator so that * it can check whether an error occurred. C CALLP OpenFile(*IN10) C IF *IN10 C ... an error occurred C ENDIF C RETURN *---------------------------------------------------------------* OpenFile * This procedure must check the number of parameters since the * second was defined with OPTIONS(*OMIT). * It should only use the second parameter if it was passed. *---------------------------------------------------------------P OpenFile B D OpenFile PI D Error 1A OPTIONS(*OMIT) D SaveIn01 S 1A * Save the current value of indicator 01 in case it is being * used elsewhere. C EVAL SaveIn01 = *IN01 * Open the file. *IN01 will indicate if an error occurs. C OPEN QSYSPRT 01 * If the Error parameter was passed, update it with the indicator C IF %ADDR(Error) <> *NULL C EVAL Error = *IN01 C ENDIF * Restore *IN01 to its original value. C EVAL *IN01 = SaveIn01 P OpenFile E Figure 5-35. Using OPTIONS(*OMIT)
The following example shows how to code a prototype and procedure allowing variable-length parameters, using OPTIONS(*VARSIZE).
Specifications
5-127
Definition-Specification Keywords
* The following prototype describes a procedure that allows * both a variable-length array and a variable-length character * field to be passed. Other parameters indicate the lengths. D Search PR 5U 0 D SearchIn 50A OPTIONS(*VARSIZE) D DIM(100) CONST D ArrayLen 5U 0 VALUE D ArrayDim 5U 0 VALUE D SearchFor 50A OPTIONS(*VARSIZE) CONST D FieldLen 5U 0 VALUE D Arr1 S 1A DIM(7) CTDATA PERRCD(7) D Arr2 S 10A DIM(3) CTDATA D Elem S 5U 0 * Call Search to search an array of 7 elements of length 1 with * a search argument of length 1. Since the * is in the 5th * element of the array, Elem will have the value 5. C EVAL Elem = Search(Arr1 : C %SIZE(Arr1) : %ELEM(Arr1) : C * : 1) * Call Search to search an array of 3 elements of length 10 with * a search argument of length 4. Since Pink is not in the * array, Elem will have the value 0. C EVAL Elem = Search(Arr2 : C %SIZE(Arr2) : %ELEM(Arr2) : C Pink : 4) C RETURN Figure 5-36. Using OPTIONS(*VARSIZE)
5-128
Definition-Specification Keywords
*-----------------------------------------------------------* Search: * Searches for SearchFor in the array SearchIn. Returns * the element where the value is found, or 0 if not found. * The character parameters can be of any length or * dimension since OPTIONS(*VARSIZE) is specified for both. *-----------------------------------------------------------P Search B D Search PI 5U 0 D SearchIn 50A OPTIONS(*VARSIZE) D DIM(100) CONST D ArrayLen 5U 0 VALUE D ArrayDim 5U 0 VALUE D SearchFor 50A OPTIONS(*VARSIZE) CONST D FieldLen 5U 0 VALUE D I S 5U 0 * Check each element of the array to see if it the same * as the SearchFor. Use the dimension that was passed as * a parameter rather than the declared dimension. Use * %SUBST with the length parameter since the parameters may * not have the declared length. C 1 DO ArrayDim I 5 0 * If this element matches SearchFor, return the index. C IF %SUBST(SearchIn(I) : 1 : ArrayLen) C = %SUBST(SearchFor : 1 : FieldLen) C RETURN I C ENDIF C ENDDO * No matching element was found. C RETURN 0 P Search E Compile-time data section: **CTDATA ARR1 A2$@*jM **CTDATA ARR2 Red Blue Yellow
The following example shows how to use OPTIONS(*STRING) to code a prototype and procedure that use a null-terminated string parameter.
Specifications
5-129
Definition-Specification Keywords
* The following prototype describes a procedure that expects * a null-terminated string parameter. It returns the length * of the string. D StringLen PR 5U 0 D Pointer * VALUE OPTIONS(*STRING) D P S * D Len S 5U 0 * Call StringLen with a character literal. The result will be * 4 since the literal is 4 bytes long. C EVAL Len = StringLen(abcd) * Call StringLen with a pointer to a string. Use ALLOC to get * storage for the pointer, and use %STR to initialize the storage * to My string where represents the null-termination * character x00. * The result will be 9 which is the length of My string. C ALLOC 25 P C EVAL %STR(P:25) = My string C EVAL Len = StringLen(P) * Free the storage. C DEALLOC P C RETURN *-----------------------------------------------------------* StringLen: * Returns the length of the string that the parameter is * pointing to. *-----------------------------------------------------------P StringLen B D StringLen PI 5U 0 D Pointer * VALUE OPTIONS(*STRING) C RETURN %LEN(%STR(Pointer)) P StringLen E Figure 5-37. Using OPTIONS(*STRING)
5-130
Definition-Specification Keywords
* * * * * * * * * * * * * * * * D D D D D D D * * * * * *
The following prototype describes a procedure that expects these parameters: 1. trimLeftAdj - a fixed length parameter with the non-blank data left-adjusted 2. leftAdj - a fixed length parameter with the value left-adjusted (possibly with leading blanks) 3. trimRightAdj - a fixed length parameter with the non-blank data right-adjusted 4. rightAdj - a fixed length parameter with the value right-adjusted (possibly with trailing blanks) 5. trimVar - a varying parameter with no leading or trailing blanks 6. var - a varying parameter, possibly with leading or trailing blanks trimProc PR trimLeftAdj 10a const options(*trim) leftAdj 10a const trimRightAdj 10a value options(*rightadj : *trim) rightAdj 10a value options(*rightadj) trimVar 10a const varying options(*trim) var 10a value varying The following prototype describes a procedure that expects these parameters: 1. trimString - a pointer to a null-terminated string with no leading or trailing blanks 2. string - a pointer to a null-terminated string, possibly with leading or trailing blanks
Specifications
5-131
Definition-Specification Keywords
D trimStringProc PR D trimString * value options(*string : *trim) D string * value options(*string) D ptr s * /free // trimProc is called with the same value passed // for every parameter // // The called procedure receives the following parameters // trimLeftAdj abc // leftAdj abc // trimRightAdj abc // rightAdj abc // trimVar abc // var abc callp trimProc ( abc : abc : abc : abc : abc : abc ); // trimStringProc is called with the same value passed // for both parameters // // The called procedure receives the following parameters, // where represents x00 // trimstring pointer to abc // string pointer to abc callp trimStringProc ( abc : abc ); // // // // // // // trimStringProc is called with the same pointer passed to both parameters The called procedure receives the following parameters, where represents x00 trimstring pointer to xyz string
pointer to xyz ptr = %alloc (6); %str(ptr : 6) = xyz ; callp trimStringProc (ptr : ptr);
5-132
Definition-Specification Keywords
*----------------------------------* DDS for file NULLFILE *----------------------------------A R TESTREC A NULL1 10A ALWNULL A NOTNULL2 10A A NULL3 10A ALWNULL *----------------------------------* Calling procedure *----------------------------------* The externally-described data structure DS, and the * data structure DS2 defined LIKEDS(ds) have * null-capable fields NULL1 and NULL3. D ds E DS EXTNAME(nullFile) D ds2 DS LIKEDS(ds) * Procedure PROC specifies OPTIONS(*NULLIND) for all its * parameters. When the procedure is called, the * null-byte maps of the calling procedures parameters * will be passed to the called procedure allowing the * called procedure to use %NULLIND(parmname) to access the * null-byte map. D proc PR D parm LIKEDS(ds) D OPTIONS(*NULLIND) D parm2 10A OPTIONS(*NULLIND) D parm3 10A OPTIONS(*NULLIND) CONST /free // The calling procedure sets some values // in the parameters and their null indicators %nullind(ds.null1) = *on; ds.notnull2 = abcde; ds.null3 = fghij; %nullind(ds.null3) = *off; ds2.null1 = abcde; %nullind(ds2.null1) = *on; %nullind(ds3.null3) = *off; // The procedure is called (see the code for // the procedure below proc (ds : ds2.null1 : ds2.null3); // After "proc" returns, the calling procedure // displays some results showing that the // called procedure changed the values of // the calling procedures parameters and // their null-indicators dsply (%nullind(ds.null1)); // displays 0 dsply ds2.null2; // displays newval dsply (%nullind(ds2.null2)); // displays 0 /end-free Figure 5-39. Using OPTIONS(*NULLIND)
Specifications
5-133
Definition-Specification Keywords
*----------------------------------* Called procedure PROC *----------------------------------P B D proc PI D parm LIKEDS(ds) D OPTIONS(*NULLIND) D parm2 10A OPTIONS(*NULLIND) D parm3 10A OPTIONS(*NULLIND) CONST /free if %NULLIND(parm.null1); // This code will be executed because the // caller set on the null indicator for // subfield NULL1 of the parameter DS endif; if %NULLIND(parm3); // PARM3 is defined as null-capable since it was // defined with OPTIONS(*NULLIND). // This code will not be executed, because the // caller set off the null-indicator for the parameter endif; // Change some data values and null-indicator values // The calling procedure will see the updated values. parm2 = newvalue; %NULLIND(parm2) = *OFF; %NULLIND(parm.null1) = *OFF; parm.null1 = newval; return; /end-free P E
OVERLAY(name{:start_pos | *NEXT})
| The OVERLAY keyword overlays the storage of one subfield with that of another subfield, or in a | fixed-form definition, with that of the data structure itself. This keyword is allowed only for data | structure subfields. The Name-entry subfield overlays the storage specified by the name parameter at the position specified by the start_pos parameter. If start_pos is not specified, it defaults to 1. Note: The start_pos parameter is in units of bytes, regardless of the types of the subfields. Specifying OVERLAY(name:*NEXT) positions the subfield at the next available position within the overlaid field. (This will be the first byte past all other subfields prior to this subfield that overlay the same subfield.) The following rules apply to keyword OVERLAY: | 1. The name parameter must be the name of a subfield defined previously in the current data structure, | or in a fixed-form definition, the name of the current data structure. In a free-form definition, use the | POS keyword to position a subfield within the data structure. 2. If the data structure is qualified, the first parameter to the OVERLAY keyword must be specified without the qualifying data structure name. In the following example, subfield MsgInfo.MsgPrefix overlays subfield MsgInfo.MsgId.
D MsgInfo D MsgId D MsgPrefix DS 7 3 QUALIFIED OVERLAY(MsgId)
5-134
Definition-Specification Keywords
3. The start_pos parameter (if specified) must be a value greater than 0 with no decimal positions. It can be a numeric literal, a built-in function returning a numeric value, or a numeric constant. If start_pos is a named constant, it must be defined prior to this specification. 4. The OVERLAY keyword is not allowed when the From-Position entry is not blank. 5. If the name parameter is a subfield, the subfield being defined must be contained completely within the subfield specified by the name parameter. 6. Alignment of subfields defined using the OVERLAY keyword must be done manually. If they are not correctly aligned, a warning message is issued. 7. If the subfield specified as the first parameter for the OVERLAY keyword is an array, the OVERLAY keyword applies to each element of the array. That is, the field being defined is defined as an array with the same number of elements. The first element of this array overlays the first element of the overlaid array, the second element of this array overlays the second element of the overlaid array, and so on. No array keywords may be specified for the subfield with the OVERLAY keyword in this situation. (Refer to Figure 5-40) See also SORTA (Sort an Array) on page 6-303. If the subfield name, specified as the first parameter for the OVERLAY keyword, is an array and its element length is longer than the length of the subfield being defined, the array elements of the subfield being defined are not stored contiguously. Such an array is not allowed as the Result Field of a PARM operation or in Factor 2 or the Result Field of a MOVEA operation. 8. If the ALIGN keyword is specified for the data structure, subfields defined with OVERLAY(name:*NEXT) are aligned to their preferred alignment. Pointer subfields are always aligned on a 16-byte boundary. 9. If a subfield with overlaying subfields is not otherwise defined, the subfield is implicitly defined as follows: v The start position is the first available position in the data structure. v The length is the minimum length that can contain all overlaying subfields. If the subfield is defined as an array, the length will be increased to ensure proper alignment of all overlaying subfields. Examples
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... * DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords++++++++++++++++++++++++++++ D DataStruct DS D A 10 DIM(5) D B 5 OVERLAY(A) D C 5 OVERLAY(A:6) Figure 5-40. Storage Allocation of Subfields with Keywords DIM and OVERLAY
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... * DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++ D DataStruct DS D A 5 D B 1 OVERLAY(A) DIM(4) Figure 5-41. Storage Allocation of Subfields with Keywords DIM and OVERLAY
5-135
Definition-Specification Keywords
A B(1) B(2) B(3) B(4)
The following example shows two equivalent ways of defining subfield overlay positions: explicitly with (name:start_pos) and implicitly with (name:*NEXT).
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... * DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++ * Define subfield overlay positions explicitly D DataStruct DS D PartNumber 10A D Family 3A OVERLAY(PartNumber) D Sequence 6A OVERLAY(PartNumber:4) D Language 1A OVERLAY(PartNumber:10) *.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... * DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++ * Define subfield overlay positions with *NEXT D DataStruct DS D PartNumber D Family 3A OVERLAY(PartNumber) D Sequence 6A OVERLAY(PartNumber:*NEXT) D Language 1A OVERLAY(PartNumber:*NEXT) Figure 5-42. Defining Subfield Overlay Positions with *NEXT
| PACKED(digits {: decimal-positions}) | The PACKED keyword is a numeric data type keyword. It is used in a free-form definition to indicate | that the item has packed-decimal format. | It must be the first keyword. | The first parameter is required. It specifies the total number of digits. It can be a value between 1 and 63. | The second parameter is optional. It specifies the number of decimal positions. It can be a value between | zero and the number of digits. It defaults to zero. | Each parameter can be a literal or a named constant. If it is a named constant, the constant must be | defined prior to the definition statement. | In the following example | v field salary is defined as a packed field with 5 digits and 2 decimal places | v field age is defined as a packed field with 3 digits and the default of 0 decimal places | v field price is defined as a packed field with 7 digits and 3 decimal positions. The number of decimal | positions is defined using named constant NUM_DEC_POS. | | | | |
DCL-S DCL-S DCL-C DCL-S salary PACKED(5 : 2); age PACKED(3); NUM_DEC_POS 3; price PACKED(7 : NUM_DEC_POS);
PACKEVEN
The PACKEVEN keyword indicates that the packed field or array has an even number of digits. The keyword is only valid for packed program-described data-structure subfields defined using FROM/TO
5-136
Definition-Specification Keywords
positions. For a field or array element of length N, if the PACKEVEN keyword is not specified, the number of digits is 2N - 1; if the PACKEVEN keyword is specified, the number of digits is 2(N-1).
PERRCD(numeric_constant)
The PERRCD keyword allows you to specify the number of elements per record for a compile-time or a prerun-time array or table. If the PERRCD keyword is not specified, the number of elements per record defaults to one (1). The numeric_constant parameter must be a value greater than 0 with no decimal positions. It can be a numeric literal, a built-in function returning a numeric value, or a numeric constant. If the parameter is a named constant, it does not need to be defined prior to this specification. The PERRCD keyword is valid only when the keyword FROMFILE, TOFILE, or CTDATA is specified. | | | | | | |
POINTER{(*PROC)}
The POINTER keyword is used in a free-form definition to indicate that the item has type basing pointer or type procedure pointer. It must be the first keyword. The parameter is optional. If the parameter is specified, it must be *PROC, indicating that the item is a procedure pointer. If the parameter is not specified, the item is a basing pointer.
| In the following example | v Field userspace is defined as a basing pointer field | v Field callback is defined as a procedure-pointer field. | | | |
DCL-S userspace POINTER; DCL-S callback POINTER(*PROC);
| | | | | | | | | | | | | | | |
POS(starting-position)
The POS keyword is used in a free-form subfield definition to specify the starting position of the subfield in the data structure. The starting-position parameter must be a value between 1 and the length of the data structure. The parameter can be a literal or a named constant. If it is a named constant, the constant must be defined prior to the definition statement. The following example is defining an INDDS data structure. It uses the POS keyword to place the indicators at specific positions in the data structure.
DCL-DS indds LEN(99); exit IND POS(3); refresh IND POS(5); cancel IND pos(12); sflclr IND pos(55); sfldsp IND pos(56); END-DS;
Specifications
5-137
Definition-Specification Keywords
| The following example is defining a data structure to use with an API. It uses the POS keyword to place | the subfields at the positions specified in the API documentation. | | | | | |
DCL-DS Qwc JOBI0100_t QUALIFIED; Job_Type CHAR(1) POS(61); Job_Subtype CHAR(1) POS(62); Default_Wait INT(10) POS(73); END-DS;
PREFIX(prefix{:nbr_of_char_replaced})
The PREFIX keyword allows the specification of a character string or character literal which is to be prefixed to the subfield names of the externally described data structure being defined. In addition, you can optionally specify a numeric value to indicate the number of characters, if any, in the existing name to be replaced. If the parameter 'nbr_of_char_replaced' is not specified, then the string is attached to the beginning of the name. To remove characters from the beginning of every name, specify an empty string as the first parameter: PREFIX('':number_to_remove). If the 'nbr_of_char_replaced' is specified, it must represent a numeric value between 0 and 9 with no decimal places. Specifying a value of zero is the same as not specifying 'nbr_of_char_replaced' at all. For example, the specification PREFIX(YE:3) would change the field name 'YTDTOTAL' to 'YETOTAL'. The 'nbr_of_char_replaced' parameter can be a numeric literal, a built-in function that returns a numeric value, or a numeric constant. If it is a named constant, then the constant must be defined prior to the specification containing the PREFIX keyword. In addition, if it is a built-in function, all parameters to the built-in function must be defined prior to the specification containing the keyword PREFIX. The following rules apply: v Subfields that are explicitly renamed using the EXTFLD keyword are not affected by this keyword. v The total length of a name after applying the prefix must not exceed the maximum length of an RPG field name. v If the number of characters in the name to be prefixed is less than or equal to the value represented by the 'nbr_of_char_replaced' parameter, then the entire name is replaced by the prefix_string. v The prefix cannot end in a period. v If the prefix is a character literal, it must be uppercase. # See the ALIAS keyword for information on how the PREFIX keyword interacts with the ALIAS keyword.
5-138
Definition-Specification Keywords
The following example uses PREFIX('':2) on the externally-described data structures DS1 and DS2. The fields of the file FILE1 all begin with the characters X4, and the fields of the file FILE2 all begin with the characters WR. If the two files have any fields whose names are the same aside from the initial two characters, then by specifying PREFIX('':2) for the externally-described data structures, the subfields will have identical names within the RPG program. This will enable the subfields to be assigned using the EVAL-CORR operation. Ffile1 if e disk Ffile2 o e disk D ds1 e ds extname(file1) prefix(:2) D qualified D ds2 e ds extname(file2) prefix(:2) D qualified /free read file1 ds1; // Read into data structure eval-corr ds2 = ds1; // Assign fields with same name write file2 ds2; // Write from data structure /end-free Figure 5-43. Using PREFIX to remove characters from the names
PROCPTR
The PROCPTR keyword defines an item as a procedure pointer. The internal Data-Type field (position 40) must contain a *. # See EXTPROC({*CL|*CWIDEN|*CNOWIDEN| {*JAVA:class-name:}}name) on page 5-106 for # information on how to use a procedure pointer to call a procedure. | | | | | Note: The PROCPTR keyword is not used in a free-form definition. Instead, keyword POINTER(*PROC) is specified to define the item as a procedure pointer.
PSDS
The PSDS keyword is used in a free-form data structure definition to indicate that the data structure is a Program-Status Data Structure.
QUALIFIED
The QUALIFIED keyword specifies that the subfields of a data structure will be accessed by specifying the data structure name followed by a period and the subfield name. The data structure must have a name. The subfields can have any valid name, even if the name has been used elsewhere in the program. This is illustrated in the following example:
* In this example, FILE1 and FILE2 are the names of files. FILE1 and FILE2 are * also subfields of qualified data structure FILESTATUS. This is valid, * because the subfields FILE1 and FILE2 must be qualified by the data structure * name: FILESTATUS.FILE1 and FILESTATUS.FILE2. Ffile1 if e disk Ffile2 if e disk D fileStatus D file1 D file2 C C ds N N open(e) eval file1 fileStatus.file1 = %error qualified
# RTNPARM # The RTNPARM keyword specifies that the return value of a procedure is to be handled internally as a # parameter of the same type as the defined returned value, passed by reference.
Specifications
5-139
Definition-Specification Keywords
# Using RTNPARM may improve performance when returning large values. # # # # # # # # # # # # # # The impact on performance due to the RTNPARM keyword will vary from having a small negative impact to having a large positive impact. There may be a small negative impact when the prototyped return value is relatively small, such as an integer, or a small data structure. There will be some improvement when the prototyped return value is a larger value such as a 32767 byte data structure. The performance improvement is most apparent when the prototyped return value is a large varying length string, and the actual returned value is relatively small; for example, the prototype defines the return value as a one million byte varying length character string, and the value 'abc' is returned. Using RTNPARM for a procedure prototype may also reduce the amount of automatic storage required for other procedures that contain calls to that procedure. For example, if procedure MYCALLER contains a call to procedure MYPROC that returns a large value, procedure MYCALLER will require additional automatic storage (even if MYCALLER does not actually call procedure MYPROC at run time). In some cases, procedure MYCALLER will not compile due to excessive automatic storage requirements; in other cases, MYCALLER is not able to be called because the total automatic storage on the call stack would exceed the maximum. Using RTNPARM avoids this problem with additional automatic storage.
# Note: # 1. The additional parameter is passed as the first parameter. # # # # # # # # # # # # # # # 2. The %PARMS and %PARMNUM built-in functions include the additional parameter in the parameter count. When the RTNPARM keyword is specified, the value returned by %PARMNUM will be one higher than the apparent parameter number. 3. When calling APIs that require a parameter number, such as CEEDOD or CEETSTA, you must account for the extra first parameter. For example, if your procedure has three parameters, and you want to find the length of the third parameter as it appears in your parameter list, you must ask for information about the fourth parameter. If you use the %PARMNUM built-in function to return the correct parameter number for calling these APIs, you do not need to worry about manually determining the correct parameter number. 4. When the calling procedure is written in a language other than RPG, the caller must code the call as though the procedure has no return value, and as though there is an additional first parameter passed by reference with the same type as the RPG return value. 5. Similarly, when the called procedure is written in a language other than RPG, the procedure must be coded without a return value, and having an additional first parameter passed by reference with the same type as the RPG return value.
# 6. When RTNPARM is specified for the procedure, the maximum number of prototyped parameters is # 398. # 7. The RTNPARM keyword is not allowed for a Java method call. # The RTNPARM keyword applies both to a prototype definition and to a procedure-interface definition. #
5-140
Definition-Specification Keywords
# 1. The prototype for the procedure pr 100000a varying # D center rtnparm # D 50000a const varying # D text 10i 0 value # D len # # # 2. Calling the procedure s 100a varying # D title /free # title = center (Chapter 1 : 20); # // title = Chapter 1 # # # 3.The procedure b export # P center pi 100000a varying # D center rtnparm # D 50000a const varying # D text 10i 0 value # D len s 50000a inz(*blanks) # D blanks s 10i 0 # D numBlanks s 10i 0 # D startBlanks s 10i 0 # D endBlanks /free # if len < %len(text); # ... handle invalid input # endif; # numBlanks = len - %len(text); # startBlanks = numBlanks / 2; # endBlanks = numBlanks - startBlanks; # return %subst(blanks : 1 : startBlanks) # + text # + %subst(blanks : 1 : endBlanks); # /end-free # e # P center # # # Figure 5-44. Example of a procedure with the RTNPARM keyword # #
Specifications
5-141
Definition-Specification Keywords
# D proc pi a len(16773100) varying rtnparm opdesc # D 10a # D p1 10a options(*varsize) # D p2 10a options(*omit : *nopass) # D p3 # s 10i 0 # D num_parms s 10i 0 # D parm_len s 10i 0 # D desc_type s 10i 0 # D data_type s 10i 0 # D desc_info1 s 10i 0 # D desc_info2 pr # D CEEDOD 10i 0 const # D parm_num 10i 0 # D desc_type 10i 0 # D data_type 10i 0 # D desc_info1 10i 0 # D desc_info2 10i 0 # D parm_len 12a options(*omit) # D feedback /free # // Get information about parameter p2 # callp CEEDOD(%parmnum(p2) : desc_type : data_type # : desc_info1 : desc_info2 # : parm_len : *omit); # if parm_len < 10; # // The parameter passed for p2 is shorter than 10 # endif; # # // Find out the number of parameters passed # num_parms = %parms(); # // If all three parameters were passed, num_parms = 4 # # // test if p3 was passed # if num_parms >= %parmnum(p3); # // Parameter p3 was passed # if %addr(p3) <> *null; # // Parameter p3 was not omitted # endif; # endif; # # # # Figure 5-45. Using %PARMS and calling CEEDOD with the RTNPARM keyword # # # 1. The RPG prototype pr 200a rtnparm # D myproc 10a const # D name # # 2. A CL module calling this RPG procedure # dcl &retval type(*char) len(200) # # callprc myproc parm(&retval Jack Smith) # # # Figure 5-46. Calling a procedure with the RTNPARM keyword from another language #
5-142
Definition-Specification Keywords
# 1. CL procedure GETLIBTEXT # PGM PARM(&retText &lib) # # DCL &retText type(*char) len(50) type(*char) len(10) # DCL &lib # # /* Set &retText to the library text */ # rtvobjd obj(&lib) objtype(*lib) text(&retText) # return # # 2. RPG procedure calling this CL procedure using the RTNPARM keyword pr 50a rtnparm # D getLibText 10a const # D name /free # if getLibText(MYLIB) = *blanks; # ... # # # # Figure 5-47. Calling a procedure with the RTNPARM keyword written in another language #
STATIC{(*ALLTHREAD)}
The STATIC keyword is used: v To specify that a local variable is stored in static storage v To specify that the same copy of a static variable will be available to all threads in a multithreaded environment v To specify that a Java method is defined as a static method. For a local variable of a subprocedure, the STATIC keyword specifies that the data item is to be stored in static storage, and thereby hold its value across calls to the procedure in which it is defined. The keyword can only be used within a subprocedure. All global fields are static. The data item is initialized when the program or service program it is contained in is first activated. It is not reinitialized again, even if reinitialization occurs for global definitions as part of normal cycle processing. If STATIC is not specified, then any locally defined data item is stored in automatic storage. Data stored in automatic storage is initialized at the beginning of every call. When a procedure is called recursively, each invocation gets its own copy of the storage. For any variable in a module where THREAD(*CONCURRENT) is specified on the Control specification, STATIC(*ALLTHREAD) specifies that the same instance of a static variable will be used by all threads. If *ALLTHREAD is not specified for a static variable in a thread-concurrent module, then the variable will be in thread-local storage, meaning that each thread will have its own instance of the variable. The following rules apply to the use of the STATIC(*ALLTHREAD) keyword: v STATIC(*ALLTHREAD) is not allowed unless THREAD(*CONCURRENT) is specified on the Control specification. v The STATIC keyword is implied for global variables. The STATIC keyword cannot be specified for a global variable unless *ALLTHREAD is specified as a parameter. v A variable defined with STATIC(*ALLTHREAD) cannot be initialized to the address of variables which are not also defined with STATIC(*ALLTHREAD).
Specifications
5-143
Definition-Specification Keywords
CAUTION: It is up to you to ensure that a static variable used in all threads is handled in a thread-safe manner. See the "Multithreading Considerations" section in the Rational Development Studio for i: ILE RPG Programmer's Guide, and . Tip: It is a good idea to have a naming convention for your all-thread static variables to alert maintenance programmers and code reviewers that the variables need special handling. For example, you could add the prefix ATS_ to all your variable names that are defined with STATIC(*ALLTHREAD). For a Java method, the STATIC keyword specifies that the method is defined as static. If STATIC is not specified, the method is assumed to be an instance method. You must code the STATIC keyword for your prototype if and only if the Java method has the "static" attribute. The *ALLTHREAD parameter is not allowed when the STATIC keyword is specified for a prototype. Additional Considerations for STATIC(*ALLTHREAD): Null-capable fields: The internal variable used to hold the null indicator for a STATIC(*ALLTHREAD) null-capable field will also be defined as STATIC(*ALLTHREAD). A change to the value of the null indicator for a variable by one thread will be visible to all threads. Access to the null indicator value will not be synchronized. Tables and Multiple-Occurrence Data Structures: The |internal variable used to hold the current occurrence for a table or multiple-occurrence data structure defined with STATIC(*ALLTHREAD) will be defined in thread-local storage. Each thread will have its own instance of the current-occurrence variable.
TEMPLATE
The TEMPLATE keyword indicates that the definition is to be used only for further LIKE or LIKEDS definitions. The TEMPLATE keyword is valid for Data Structure definitions and Standalone field definitions. Rules for the TEMPLATE keyword for Definition specifications:: 1. When the TEMPLATE keyword is specified for a definition, the template name and the subfields of the template name can be used only in the following ways v As a parameter for the LIKE keyword v As a parameter for the LIKEDS keyword, if the template is a data structure v As a parameter for the %SIZE builtin function v As a parameter for the %ELEM builtin function v As a parameter for the %LEN builtin function in Definition specifications (for example, as a named constant or initialization value) v As a parameter for the %DECPOS builtin function in Definition specifications (for example, as a named constant or initialization value) 2. The INZ keyword is allowed for template data structures. This allows you to set an initialization value to be used with LIKEDS definitions of the template, through the INZ(*LIKEDS) keyword.
5-144
Definition-Specification Keywords
* Define a template for the type of a NAME D standardName S 100A VARYING TEMPLATE * Define a template for the type of an EMPLOYEE D employee_type DS QUALIFIED TEMPLATE INZ D name LIKE(standardName) D INZ(** UNKNOWN **) D idNum 10I 0 INZ(0) D type 1A INZ(R) D years 5I 0 INZ(-1) * Define a variable like the employee type, initialized * with the default value of the employee type D employee DS LIKEDS(employee_type) D INZ(*LIKEDS) * Define prototypes using the template definitions * * The "id" parameter is defined like a subfield of a * template data structure. D getName PR LIKE(standardName) D idNum D findEmp PR N D emp LIKEDS(employee_type) D id LIKE(employee_type.idNum) D CONST Figure 5-48. : Examples of TEMPLATE definitions
| | | | | | | | | |
TIME{(format{separator})}
The TIME keyword is used in a free-form definition to indicate that the item has type time. It must be the first keyword. The parameter is optional. It specifies the time format and separator. See Time Data Type on page 4-75 for information on the default format for time items. In the following example, field time_dft is defined as a time field with the default format for the module, and field time_mdy is defined with *HMS as the format and period as the separator.
DCL-S time_dft TIME; DCL-S time_hms TIME(*HMS.);
| | | | | |
TIMESTAMP
The TIMESTAMP keyword is used in a free-form definition to indicate that the item has type timestamp. It must be the first keyword. In the following example, field startTs is defined as a timestamp field.
DCL-S startTs TIMESTAMP;
TIMFMT(format{separator})
The TIMFMT keyword allows the specification of an internal time format, and optionally the time separator, for any of these items of type Time: standalone field; data-structure subfield; prototyped parameter; or return value on a prototype or procedure-interface definition. This keyword will be automatically generated for an externally described data-structure subfield of type Time.
Specifications
5-145
Definition-Specification Keywords
If TIMFMT is not specified, the Time field will have the time format and separator as specified by the TIMFMT keyword on the control specification, if present. If none is specified on the control specification, then it will have *ISO format. | Note: The TIMFMT keyword is not used in a free-form definition. Instead, the time format is specified as | the parameter of the TIME keyword. See Table 4-6 on page 4-76 for valid formats and separators. For more information on internal formats, see Internal and External Formats on page 4-49.
TOFILE(file_name)
The TOFILE keyword allows the specification of a target file to which a prerun-time or compile-time array or table is to be written. If an array or table is to be written, specify the file name of the output or combined file as the keyword parameter. This file must also be defined in the file description specifications. An array or table can be written to only one output device. If an array or table is assigned to an output file, it is automatically written if the LR indicator is on at program termination. The array or table is written after all other records are written to the file. If an array or table is to be written to the same file from which it was read, the same file name that was specified as the FROMFILE parameter must be specified as the TOFILE parameter. This file must be defined as a combined file (C in position 17 on the file description specification). | UCS2(length) | The UCS2 keyword is used in a free-form definition to indicate that the item is fixed-length UCS-2. | It must be the first keyword. | The parameter specifies the length in double-byte characters. It can be between 1 and 8,386,552. | The parameter can be a literal or a named constant. If it is a named constant, the constant must be | defined prior to the definition statement. | In the following example | v field cust_name is defined as a fixed-length UCS-2 field with 100 characters. | v field message is defined as a fixed-length UCS-2 field with 5000 characters. The length is defined using | named constant MSG_LEN. | | | |
DCL-S cust_name UCS2(100); DCL-C MSG_LEN 5000; DCL-S message UCS2(MSG_LEN);
| For information on defining a variable-length UCS-2 item, see VARUCS2(length {:2 | 4}) on page 5-148. | UNS(digits) | The UNS keyword is a numeric data type keyword. It is used in a free-form definition to indicate that the | item has unsigned integer format. | It must be the first keyword. | The parameter specifies the length in digits. It must be one of 3, 5, 10 or 20, occupying 1, 2, 4, and 8 bytes | respectively.
5-146
Definition-Specification Keywords
| | | | | |
DCL-S num_elems UNS(10);
The parameter can be a literal or a named constant. If it is a named constant, the constant must be defined prior to the definition statement. In the following example v field num_elems is defined as an unsigned integer field with 10 digits. It occupies 4 bytes in storage.
VALUE
The VALUE keyword indicates that the parameter is passed by value rather than by reference. Parameters can be passed by value when the procedure they are associated with are called using a procedure call. The VALUE keyword cannot be specified for a parameter if its prototype was defined using the EXTPGM keyword. Calls to programs require that parameters be passed by reference. The rules for what can be passed as a value parameter to a called procedure are the same as the rules for what can be assigned using the EVAL operation. The parameter received by the procedure corresponds to the left-hand side of the expression; the passed parameter corresponds to the right-hand side. See EVAL (Evaluate expression) on page 6-191 for more information. | | | | | | | | | | |
| In the following example | v field cust_name is defined as a variable-length character field with a maximum length of 50 characters | v field message is defined as a variable-length character field with a maximum length of 500 characters and a prefix size of 4 bytes. | | | |
DCL-S cust_name VARCHAR(50); DCL-S message VARCHAR(500 : 4);
| For information on defining a fixed-length character item, see CHAR(length) on page 5-96. | | |
Specifications
5-147
Definition-Specification Keywords
| It must be the first keyword. | The parameter specifies the length in bytes. It can be between 1 and 8,386,550. | The parameter can be a literal or a named constant. If it is a named constant, the constant must be | defined prior to the definition statement. | The second parameter is optional. It specifies the number of bytes used to store the current length of the | variable-length item. See Size of the Length-Prefix for a Varying Length Item on page 4-55. | Each parameter can be a literal or a named constant. If it is a named constant, the constant must be | defined prior to the definition statement. | In the following example | v field cust_name is defined as a variable-length graphic field with a maximum length of 50 characters | v field message is defined as a variable-length graphic field with a maximum length of 500 characters and | a prefix size of 4 bytes. | | |
DCL-S cust_name VARGRAPH(50); DCL-S message VARGRAPH(500 : 4);
| For information on defining a fixed-length graphic item, see GRAPH(length) on page 5-112. | VARUCS2(length {:2 | 4}) | The VARUCS2 keyword is used in a free-form definition to indicate that the item is variable-length | UCS-2. | It must be the first keyword. | The first parameter is required. It specifies the length in bytes. It can be between 1 and 8,386,550. | The second parameter is optional. It specifies the number of bytes used to store the current length of the | variable-length item. See Size of the Length-Prefix for a Varying Length Item on page 4-55. | Each parameter can be a literal or a named constant. If it is a named constant, the constant must be | defined prior to the definition statement. | In the following example | v field cust_name is defined as a variable-length UCS-2 field with a maximum length of 50 characters | v field message is defined as a variable-length UCS-2 field with a maximum length of 500 characters and a prefix size of 4 bytes. | | | |
DCL-S cust_name VARUCS2(50); DCL-S message VARUCS2(500 : 4);
| For information on defining a fixed-length UCS-2 item, see UCS2(length) on page 5-146.
VARYING{(2 | 4)}
The VARYING keyword indicates that a character, graphic, or UCS-2 field, defined on the definition specifications, should have a variable-length format. If this keyword is not specified for character, graphic, or UCS-2 fields, they are defined as fixed length.
5-148
Definition-Specification Keywords
# The parameter of the VARYING keyword indicates the number of bytes used to store the current length # of the variable-length item. See Size of the Length-Prefix for a Varying Length Item on page 4-55. | | Note: The VARYING keyword is not used in a free-form definition. Instead, the VARCHAR, VARGRAPH, or VARUCS2 keyword is used to specify the data type of the item. keyword. For more information, see Variable-Length Character, Graphic and UCS-2 Formats on page 4-54. | | | | | | | | |
ZONED(digits {: decimal-positions})
The ZONED keyword is a numeric data type keyword. It is used in a free-form definition to indicate that the item has zoned-decimal format. It must be the first keyword. The first parameter is required. It specifies the total number of digits. It can be a value between 1 and 63. The second parameter is optional. It specifies the number of decimal positions. It can be a value between zero and the number of digits. It defaults to zero. Each parameter can be a literal or a named constant. If it is a named constant, the constant must be defined prior to the definition statement.
| In the following example | v field salary is defined as a zoned field with 5 digits and 2 decimal places | v field age is defined as a zoned field with 3 digits and the default of 0 decimal places | v field price is defined as a zoned field with 7 digits and 3 decimal positions. The number of decimal | positions is defined using named constant NUM_DEC_POS. | | | | |
DCL-S DCL-S DCL-C DCL-S salary ZONED(5 : 2); age ZONED(3); NUM_DEC_POS 3; price ZONED(7 : NUM_DEC_POS);
A Data Structure
Specifications
5-149
A Data Structure Subfield External Subfield Standalone Field Named Constant Prototype Prototype Parameter A Procedure Interface R Procedure Interface Parameter R R A R A R R R R R
A A A A A R
A A
A A
A A
A A
Table 5-21. Data Structure, Standalone Fields, and Named Constants Keywords Keyword ALIGN ALT ALTSEQ ASCEND BASED A
7
Data Structure A
External Subfield
Standalone Field
Named Constant
A A A A
A A A
A A A A
| |
BINDEC CHAR
7
A A A
A A A A
CCSID CLASS
6 1 2
CONST
R A A A A A A A A A A A A A A A A A
CTDATA
DATE
5-150
External Subfield
Standalone Field A
Named Constant
EXT
| | | |
FLOAT
A A A A A
FROMFILE GRAPH
7 7 2
A A A A A A A A A A
A A A A A A
A A A
A A A A A
LIKEREC NOOPT
OBJECT
OCCURS OVERLAY
A A A
6
PACKED
PACKEVEN PERRCD
A A A A A
| |
POINTER POS
5 4
A A A
PREFIX
PROCPTR
A A A A A A
7
A A A A A A A A A A A
TEMPLATE
| |
TIME
A A A A A
| | | |
UCS2 UNS
7
VARCHAR
7 7
A A
VARGRAPH
Specifications
5-151
| |
1. When defining a named constant, the keyword is optional, but the parameter to the keyword is required. For example, to assign a named constant the value '10', you could specify either CONST('10') or '10'. 2. This keyword applies only to global definitions. 3. This keyword applies only to local definitions. 4. This keyword applies only to externally described data structures. 5. This keyword applies only to program-described data structures.
| |
6. This keyword applies only to free-form definitions. 7. This keyword applies only to fixed-form definitions. Table 5-22. Prototype, Procedure Interface, and Parameter Keywords Keyword ALTSEQ ASCEND Prototype (PR) A
1
PR or PI Parameter A A
| |
A A A A
A A A A
A A A A A
CLASS
CONST
DATE
1 2
A A
A A
A A A
DATFMT
DESCEND DIM A A A A
1
A A A A A A A A A
# EXTPGM # EXTPROC | | | |
FLOAT
1 1
A A A A A A A
A A A A A
A A
A A
A A A
OBJECT
A A
A A
OPDESC
5-152
Prototype (PR)
PR or PI Parameter A
| |
PACKED
A A A A A A
1
A A A A A A A A A A
A A A
POINTER
PROCPTR
# RTNPARM
STATIC
| | | | | | | | | | | |
TIME
A A A A A A
A A A A
A A A A A A A
A A A A A A A
A A A A A A A
VARCHAR
1 2
VARGRAPH VARUCS2
1
1. This keyword applies only to free-form definitions. 2. This keyword applies only to fixed-form definitions.
Input Specifications
For a program-described input file, input specifications describe the types of records within the file, the sequence of the types of records, the fields within a record, the data within the field, indicators based on the contents of the fields, control fields, fields used for matching records, and fields used for sequence checking. For an externally described file, input specifications are optional and can be used to add RPG IV functions to the external description. Input specifications are not used for all of the files in your program. For some files, you must code data structures in the result field of your input operatons. The following files in your program do not use Input specifications: v Files defined in subprocedures v Files defined with the QUALIFIED keyword v Files defined with the TEMPLATE keyword v Files defined with the LIKEFILE keyword Detailed information for the input specifications is given in: v Entries for program described files v Entries for externally described files
Specifications
5-153
Program Described
For program described files, entries on input specifications are divided into the following categories: v Record identification entries (positions 7 through 46), which describe the input record and its relationship to other records in the file.
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 ...+... 9 ...+... 10 IFilename++SqNORiPos1+NCCPos2+NCCPos3+NCC..................................Comments++++++++++++ I.........And..RiPos1+NCCPos2+NCCPos3+NCC..................................Comments++++++++++++ Figure 5-49. Program Described Record Layout
v Field description entries (positions 31 through 74), which describe the fields in the records. Each field is described on a separate line, below its corresponding record identification entry.
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 ...+... 9 ...+... 10 I........................Fmt+SPFrom+To+++DcField+++++++++L1M1FrPlMnZr......Comments++++++++++++ Figure 5-50. Program Described Field Layout
Externally Described
For externally described files, entries on input specifications are divided into the following categories: v Record identification entries (positions 7 through 16, and 21 through 22), which identify the record (the externally described record format) to which RPG IV functions are to be added.
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 ...+... 9 ...+... 10 IRcdname+++....Ri..........................................................Comments++++++++++++ Figure 5-51. Externally Described Record Layout
v Field description entries (positions 21 through 30, 49 through 66, and 69 through 74), which describe the RPG IV functions to be added to the fields in the record. Field description entries are written on the lines following the corresponding record identification entries.
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 ...+... 9 ...+... 10 I..............Ext-field+..................Field+++++++++L1M1..PlMnZr......Comments++++++++++++ Figure 5-52. Externally Described Field Layout
5-154
An unlimited number of AND/OR lines can be used. For more information see AND Relationship on page 5-159 and OR Relationship on page 5-159.
5-155
Position 19 (Number)
Entry Explanation Blank The program does not check record types for a special sequence (positions 17 and 18 have alphabetic entries). 1 N Only one record of this type can be present in the sequenced group. One or more records of this type can be present in the sequenced group.
This entry must be used when a numeric entry is made in positions 17 and 18. If an alphabetic entry is made in positions 17 and 18, this entry must be blank.
Position 20 (Option)
Entry Explanation Blank The record type must be present if sequence checking is specified. O The record type is optional (that is, it may or may not be present) if sequence checking is specified.
This entry must be blank if positions 17 and 18 contain an alphabetic entry. Sequence checking of record types has no meaning when all record types within a file are specified as optional (alphabetic entry in positions 17 and 18 or O entry in position 20).
L1-L9 or LR Control level indicator used for a record identifying indicator. H1-H9 Halt indicator. U1-U8 External indicator. RT ** Return indicator. Lookahead record (not an indicator). Lookahead can be used only with a primary or secondary file.
The indicators specified in these positions are used in conjunction with the record identification codes (positions 23 through 46). Indicators: Positions 21 and 22 associate an indicator with the record type defined on this line. The normal entry is one of the indicators 01 to 99; however, the control level indicators L1 through L9 and LR can be used to cause certain total steps to be processed. If a control level indicator is specified, lower control level indicators are not set on. The halt indicators H1 through H9 can be used to stop processing. The return indicator (RT) is used to return to the calling program. When a record is selected for processing and satisfies the conditions indicated by the record identification codes, the appropriate record identifying indicator is set on. This indicator can be used to condition calculation and output operations. Record identifying indicators can be set on or set off by the programmer. However, at the end of the cycle, all record identifying indicators are set off before another record is selected.
5-156
Specifications
5-157
Blank No record identification code is present. 1-32766 The position that contains the record identification code in the record. In these positions enter the position that contains the record identification code in each record. The position containing the code must be within the record length specified for the file. This entry must be right-adjusted, but leading zeros can be omitted. Positions 28, 36, and 44 (Not): Entry Explanation
Blank Record identification code must be present. N Record identification code must not be present.
Enter an N in this position if the code described must not be present in the specified record position. Positions 29, 37, and 45 (Code Part): Entry C Z D Explanation Entire character Zone portion of character Digit portion of character.
This entry specifies what part of the character in the record identification code is to be tested. Character (C): The C entry indicates that the complete structure (zone and digit) of the character is to be tested. Zone (Z): The Z entry indicates that the zone portion of the character is to be tested. The zone entry causes the four high-order bits of the character entry to be compared with the zone portion of the character in the record position specified in the position entry. The following three special cases are exceptions: v The hexadecimal representation of an & (ampersand) is 50. However, when an ampersand is coded in the character entry, it is treated as if its hexadecimal representation were C0, that is, as if it had the same zone as A through I. An ampersand in the input data satisfies two zone checks: one for a hexadecimal 5 zone, the other for a hexadecimal C zone. v The hexadecimal representation of a - (minus sign) is 60. However, when a minus sign is coded in the character entry, it is treated as if its hexadecimal representation were D0, that is, as if it had the same zone as J through R. A minus sign in the input data satisfies two zone checks: one for a hexadecimal 6 zone, the other for a hexadecimal D zone. v The hexadecimal representation of a blank is 40. However, when a blank is coded in the character entry, it is treated as if its hexadecimal representation were F0, that is, as if it had the same zone as 0 through 9. A blank in the input data satisfies two zone checks: one for a hexadecimal 4 zone, the other for a hexadecimal F zone.
5-158
Specifications
5-159
The entry in position 36 specifies the data type, and if numeric, the external data format of the data in the program-described file.
5-160
The maximum size of a character or data structure field specified as a program described input field is 32766 since that is the maximum record length for a file. When specifying a variable-length character, graphic, or UCS-2 input field, the length includes the 2 byte length prefix. For arrays, enter the beginning position of the array in positions 37 through 41 and the ending position in positions 42 through 46. The array length must be an integral multiple of the length of an element. The From-To position does not have to account for all the elements in the array. The placement of data into the array starts with the first element.
This entry, used with the data format entry in position 36, describes the format of the field. An entry in this field identifies the input field as numeric (except float numeric); if the field is numeric, an entry must be made. The number of decimal positions specified for a numeric field cannot exceed the length of the field.
Specifications
5-161
Positions 63 and 64 indicate the fields that are used as control fields. A change in the contents of a control field causes all operations conditioned by that control level indicator and by all lower level indicators to be processed. A split control field is a control field that is made up of more than one field, each having the same control level indicator. The first field specified with that control level indicator is placed in the high-order position of the split control field, and the last field specified with the same control level indicator is placed in the low-order position of the split control field. Binary, float, integer, character varying, graphic varying, UCS-2 and unsigned fields cannot be used as control fields.
5-162
Field record relation indicators are used to associate fields within a particular record type when that record type is one of several in an OR relationship. This entry reduces the number of lines that must be written. The field described on a line is extracted from the record by the RPG IV program only when the indicator coded in positions 67 and 68 is on or when positions 67 and 68 are blank. When positions 67 and 68 are blank, the field is common to all record types defined by the OR relationship. Field record relation indicators can be used with control level fields (positions 63 and 64) and matching fields (positions 65 and 66).
Entries in positions 69 through 74 test the status of a field or of an array element as it is read into the program. Field indicators are specified on the same line as the field to be tested. Depending on the status of the field (plus, minus, zero, or blank), the appropriate indicator is set on and can be used to condition later specifications. The same indicator can be specified in two positions, but it should not be used for all three positions. Field indicators cannot be used with arrays that are not indexed or look-ahead fields. Positions 69 and 70 (plus) and positions 71 and 72 (minus) are valid for numeric fields only. Positions 73 and 74 can be used to test a numeric field for zeros or a character, graphic, or UCS-2 field for blanks. The field indicators are set on if the field or array element meets the condition specified when the record is read. Each field indicator is related to only one record type; therefore, the indicators are not reset (on or off) until the related record is read again or until the indicator is defined in some other specification.
Specifications
5-163
5-164
Blank This field is not a control field. L1-L9 This field is a control field.
Null-capable and UCS-2 fields cannot be used as control fields. Note: For externally described files, split control fields are combined in the order in which the fields are specified on the data description specifications (DDS), not in the order in which the fields are specified on the input specifications.
Blank This field is not a match field. M1-M9 This field is a match field. Null-capable and UCS-2 fields cannot be used as matching fields. See Positions 65-66 (Matching Fields) on page 5-162 for more information on match fields.
Specifications
5-165
Field indicators are allowed for null-capable fields only if the ALWNULL(*USRCTL) keyword is specified on a control specification or as a command parameter. If a field is a null-capable field and the value is null, the indicator is set off. See Positions 69-74 (Field Indicators) on page 5-163 for more information.
Calculation Specifications
Calculation specifications indicate the operations done on the data in a program. Calculation specifications within the main source section must be grouped in the following order: v Detail calculations v Total calculations v Subroutines Calculation specifications for subprocedures include two groups: v Body of the subprocedure v Subroutines Calculations within the groups must be specified in the order in which they are to be done. Note: If the keyword MAIN or NOMAIN is specified on the control specification, then only declarative calculation specifications are allowed in the main source section. You can specify calculation specifications in three different formats: v Traditional Syntax on page 5-167 v Extended Factor 2 Syntax on page 5-172 v Free-Form Calculation Statement on page 5-173. See Operation Codes on page 6-140 for details on how the calculation specification entries must be specified for individual operation codes. The calculation specification can also be used to enter SQL statements into an ILE RPG program. See Rational Development Studio for i: ILE RPG Programmer's Guide and the IBM i Information Center database and file systems category for more information.
5-166
Traditional Syntax
The general layout for the calculation specification is as follows: v The calculation specification type (C) is entered in position 6 v The non-commentary part of the specification extends from position 7 to position 80. These positions are divided into three parts that specify the following: When calculations are done: The control level indicator and the conditioning indicators specified in positions 7 through 11 determine when and under what conditions the calculations are to be done. What kind of calculations are done: The entries specified in positions 12 through 70 (12 through 80 for operations that use extended factor 2, see Extended Factor 2 Syntax on page 5-172 and Expressions on page 6-49) specify the kind of calculations done, the data (such as fields or files) upon which the operation is done, and the field that contains the results of the calculation. What tests are done on the results of the operation: Indicators specified in positions 71 through 76 are used to test the results of the calculations and can condition subsequent calculations or output operations. The resulting indicator positions have various uses, depending on the operation code. For the uses of these positions, see the individual operation codes in Operation Codes on page 6-140. v The comments section of the specification extends from position 81 to position 100
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 ...+... 9 ...+... 10 CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....Comments++++++++++++ CL0N01Factor1+++++++Opcode(E)+Extended-factor2+++++++++++++++++++++++++++++Comments++++++++++++ Figure 5-53. Calculation Specification Layout
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 ...+... 9 ...+... 10 C.............................Extended-factor2-continuation++++++++++++++++Comments++++++++++++ Figure 5-54. Calculation Specification Extended Factor-2 Continuation Line
5-167
AN, OR Indicators on more than one line condition the calculation. Control Level Indicators: The L0 entry is used in positions 7 and 8 to indicate that the calculation is always done during total calculation time. If indicators L1 through L9 are specified in positions 7 and 8, the calculation is processed at total calculation time only when the specified indicator is on. Remember that, if L1 through L9 are set on by a control break, all lower level indicators are also set on. If positions 7 and 8 are blank, the calculation is done at detail time calculation, is a statement within a subroutine, is a declarative statement, or is a continuation line. The following operations can be specified within total calculations with positions 7 and 8 blank: PLIST, PARM, KLIST, KFLD, TAG, DEFINE, and ELSE. (Conditioning indicators in positions 9 through 11 are not allowed with these operations.) In addition, all the preceding operations except TAG and ELSE can be specified anywhere within the calculations, even between an ENDSR operation of one subroutine and the BEGSR operation of the next subroutine or after the ENDSR operation for the last subroutine. Note: Control indicators cannot be specified in subprocedures. Last Record Indicator: The LR Indicator, if specified in positions 7 and 8, causes the calculation to be done during the last total calculation time. Note that the LR indicator cannot be specified in subprocedures. If there is a primary file but no secondary files in the program, the LR indicator is set on after the last input record has been read, the calculations specified for the record have been done, and the detail output for the last record read has been completed. If there is more than one input file (primary and secondary), the programmer determines which files are to be checked for end-of-file by entering an E in position 19 of the file description specifications. LR is set on when all files with an end-of-file specification have been completely read, when detail output for the last record in these files has been completed, and after all matching secondary records have been processed. When the LR indicator is set on after the last input record has been read, all control indicators L1 through L9 defined to the program are also set on. Subroutine Identifier: An SR entry in positions 7 and 8 may optionally be used for operations within subroutines as a documentation aid. Subroutine lines must appear after the total calculation specifications. The operation codes BEGSR and ENDSR serve as delimiters for a subroutine. AND/OR Lines Identifier: Positions 7 and 8 can contain AN or OR to define additional indicators (positions 9 through 11) for a calculation. The entry in positions 7 and 8 of the line immediately preceding an AND/OR line or a group of AND/OR lines determines when the calculation is to be processed. The entry in positions 7 and 8 on the first line of a group applies to all AND/OR lines in the group. A control level indicator (L1 through L9, L0, or LR) is entered for total calculations, an SR or blanks for subroutines, and a blank for detail calculations.
5-168
KA-KN, KP-KY Function key indicators. L1-L9 LR MR Control level indicators. Last record indicator. Matching record indicator.
U1-U8 External indicators. OA-OG, OV Overflow indicator. Positions 10 and 11 contain an indicator that is tested to determine if a particular calculation is to be processed. A blank in position 9 designates that the indicator must be on for a calculation to be done. An N in positions 9 designates that the associated indicator must be off for a calculation to be done.
Blank No operation extension supplied A H N Used on the DUMP operation to indicate that the operation is always performed regardless of the DEBUG option set on the H specification. Half adjust (round) result of numeric operation Record is read but not locked Set pointer to *NULL after successful DEALLOC P D Pad the result field with blanks Pass operational descriptors on bound call Date field T Time field
Specifications
5-169
The operation extenders provide additional attributes to the operations that they accompany. Operation extenders are specified in positions 26-35 of calculation specifications. They must begin to the right of the operation code and be contained within parentheses; blanks can be used for readability. For example, the following are all valid entries: MULT(H), MULT (H), MULT ( H ). More than one operation extender can be specified. For example, the CALLP operation can specify both error handling and the default precision rules with CALLP(EM). An H indicates whether the contents of the result field are to be half adjusted (rounded). Resulting indicators are set according to the value of the result field after half-adjusting has been done. An N in a READ, READE, READP, READPE, or CHAIN operation on an update disk file indicates that a record is to be read, but not locked. If no value is specified, the default action of locking occurs. An N in a DEALLOC operation indicates that the result field pointer is to be set to *NULL after a successful deallocation. A P indicates that, the result field is padded after executing the instruction if the result field is longer than the result of the operation. A D when specified on the CALLB operation code indicates that operational descriptors are included. The D, T, and Z extenders can be used with the TEST operation code to indicate a date, time, or timestamp field. M and R are specified for the precision of single free-form expressions. For more information, see Precision Rules for Numeric Operations on page 6-58. An M indicates that the default precision rules are used. An R indicates that the precision of a decimal intermediate will be computed such that the number of decimal places will never be reduced smaller than the number of decimal positions of the result of the assignment. An E indicates that operation-related errors will be checked with built-in function %ERROR.
5-170
Positions 69-70 indicate the number of positions to the right of the decimal in a numeric result field. If the numeric result field contains no decimal positions, enter a '0' (zero). This position must be blank if the result field is character data or if no field length is specified. The number of decimal positions specified cannot exceed the length of the field.
KA-KN, KP-KY Function key indicators H1-H9 Halt indicators L1-L9 LR Control level indicators Last record indicator
5-171
Resulting indicators cannot be used when the result field uses a non-indexed array. If the same indicator is used as a resulting indicator on more than one calculation specification, the most recent specification processed determines the status of that indicator. Remember the following points when specifying resulting indicators: v When the calculation operation is done, the specified resulting indicators are set off, and, if a condition specified by a resulting indicator is satisfied, that indicator is set on. v When a control level indicator (L1 through L9) is set on, the lower level indicators are not set on. v When a halt indicator (H1 through H9) is set on, the program ends abnormally at the next *GETIN point in the cycle, or when a RETURN operation is processed, unless the halt indicator is set off before the indicator is tested.
Blank No operation extension supplied. H M R E Half adjust (round) result of numeric operation Default precision rules "Result Decimal Position" precision rules Error handling
Half adjust may be specified, using the H extender, on arithmetic EVAL and RETURN operations. The type of precision may be specified, using the M or R extender, on CALLP, DOU, DOW, EVAL, IF, RETURN, and WHEN operations. Error handling may be specified, using the 'E' extender, on CALLP operations.
5-172
See the specific operation codes for more information. See Continuation Rules on page 5-7 for more information on coding continuation lines.
For each record within a free-form calculation block, positions 6 and 7 must be blank. You can specify compiler directives within a free-format calculation block, with the following restrictions: v The compiler directive must be the first item on the line. Code the directive starting anywhere from column 7 onward. It cannot continue to the next line. v Compiler directives are not allowed within a statement. The directive must appear on a new line after one statement ends and before the next statement begins. Free-form operands can be longer than 14 characters. The following are not supported: v Continuation of numeric literals v Defining field names v Resulting indicators. (In most cases where you need to use operation codes with resulting indicators, you can use an equivalent built-in function instead.)
Specifications
5-173
CL0
items += 1; Total TAG IF *INL1; EXCEPT orderTotal; orders += 1; totalItems += items; items = 0; ENDIF;
1 2 3
*..1....+....2....+....3....+....4....+....5....+....6....+....7...+.... read file; dow not %eof(file); // Get next record // Keep looping while we have // a record
if %error; dsply The read failed; leave; else; chain(n) name database data; time = hours * num_employees + overtime_saved; pos = %scan (,: name); name = %xlate(upper:lower:name); exsr handle_record; read file; endif; enddo; begsr handle_record; eval(h) time = time + total_hours_array (empno); temp_hours = total_hours - excess_hours; record_transaction(); endsr; Figure 5-55. Example of Free-Form Calculation Specification
You can combine free-form and traditional calculation specifications in the same program, as shown below:
C testb if *in10; openAllFiles(); endif; OPEN_ALL flags 10
Figure 5-56. Example that Combines Traditional and Free-Form Calculation Specifications
5-174
Output Specifications
Output specifications describe the record and the format of fields in a program-described output file and when the record is to be written. Output specifications are optional for an externally described file. If MAIN or NOMAIN is coded on a control specification, only exception output can be done. Output specifications are not used for all of the files in your program. For some files, you must code data structures in the result field of your output and update operatons. The following files in your program do not use Output specifications: v Files defined in subprocedures v Files defined with the QUALIFIED keyword v Files defined with the TEMPLATE keyword v Files defined with the LIKEFILE keyword Output specifications can be divided into two categories: record identification and control (positions 7 through 51), and field description and control (positions 21 through 80). Detailed information for each category of output specifications is given in: v Entries for program-described files v Entries for externally described files
Program Described
For program described files, entries on the output specifications can be divided into two categories: v Record identification and control (positions 7 through 51)
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 ...+... 9 ...+... 10 OFilename++DF..N01N02N03Excnam++++B++A++Sb+Sa+.............................Comment+++++++++++++ OFilename++DAddN01N02N03Excnam++++.........................................Comment+++++++++++++ O.........And..N01N02N03Excnam++++.........................................Comment+++++++++++++ Figure 5-57. Program Described Record Layout
v Field description and control (positions 21 through 80). Each field is described on a separate line, below its corresponding record identification entry.
Specifications
5-175
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 ...+... 9 ...+... 10 O..............N01N02N03Field+++++++++YB.End++PConstant/editword/DTformat++Comment+++++++++++++ O..............................................Constant/editword-ContinutioComment+++++++++++++ Figure 5-58. Program Described Field Layout
Externally Described
For externally described files, entries on output specifications are divided into the following categories: v Record identification and control (positions 7 through 39)
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 ...+... 9 ...+... 10 ORcdname+++D...N01N02N03Excnam++++.........................................Comment+++++++++++++ ORcdname+++DAddN01N02N03Excnam++++.........................................Comment+++++++++++++ O.........And..N01N02N03Excnam++++.........................................Comment+++++++++++++ Figure 5-59. Externally Described Record Layout
5-176
Position 17 (Type)
Entry H or D Detail records usually contain data that comes directly from the input record or that is the result of calculations processed at detail time. Heading records usually contain constant identifying information such as titles, column headings, page number, and date. No distinction is made between heading and detail records. The H/D specifications are available to help the programmer document the program. T E Total records usually contain data that is the end result of specific calculations on several detail records. Exception records are written during calculation time. Exception records can be specified only when the operation code EXCEPT is used. See EXCEPT (Calculation Time Output) on page 6-200 for further information on the EXCEPT operation code. Explanation
Position 17 indicates the type of record to be written. Position 17 must have an entry for every output record. Heading (H) and detail (D) lines are both processed as detail records. No special sequence is required for coding the output records; however, lines are handled at separate times within the program cycle based on their record type. See Figure 3-8 on page 3-26 and Figure 3-9 on page 3-28 for more information on when in the cycle output is performed. Note: If MAIN or NOMAIN is coded on a control specification, only exception output can be done.
An entry of ADD is valid for input, output, or update files. DEL is valid for update DISK files only. When ADD is specified, there must be an A in position 20 of the corresponding file-description specification. If positions 18-20 are blank, then for an output file, the record will be added; for an update file, the record is updated. The Record-Addition/Deletion entry must appear on the same line that contains the record type (H, D, T, E) specification (position 17). If an AND/OR line is used following an ADD or DEL entry, this entry applies to the AND/OR line also.
Specifications
5-177
Function
Note: Within RPG, the term create a new file means to add records to a newly created file. Thus, the first two entries in this table perform the identical function. Both are listed to show that there are two ways to specify that function.
Blank Must be blank for all files except printer files (PRINTER specified in positions 36 through 42 of the file description specifications). If position 18 is blank for printer files, overflow is not fetched. F R Fetch overflow. Release a device (workstation) after output.
Fetch Overflow: An F in position 18 specifies fetch overflow for the printer file defined on this line. This file must be a printer file that has overflow lines. Fetch overflow is processed only when an overflow occurs and when all conditions specified by the indicators in positions 21 through 29 are satisfied. An overflow indicator cannot be specified on the same line as fetch overflow. If an overflow indicator has not been specified with the OFLIND keyword on the file description specifications for a printer file, the compiler assigns one to the file. An overflow line is generated by the compiler for the file, except when no other output records exist for the file or when the printer uses externally described data. This compiler-generated overflow can be fetched. Overflow lines can be written during detail, total, or exception output time. When the fetch overflow is specified, only overflow output associated with the file containing the processed fetch is output. The fetch overflow entry (F) is required on each OR line for record types that require the overflow routine. The fetch overflow routine does not automatically advance forms. For detailed information on the overflow routine see Overflow Routine on page 3-34 and Figure 3-11 on page 3-33 The form length and overflow line can be specified using the FORMLEN and OFLIND keywords on the file description specifications, in the printer device file, or through an IBM i override command.
5-178
H1-H9 Halt indicators. U1-U8 External indicator set before running the program or set as a result of a calculation operation. OA-OG, OV Overflow indicator previously assigned to this file. MR LR RT 1P Matching record indicator. Last record indicator. Return indicator. First-page indicator. Valid only on heading or detail lines.
Conditioning indicators are not required on output lines. If conditioning indicators are not specified, the line is output every time that record is checked for output. Up to three indicators can be entered on one specification line to control when a record or a particular field within a record is written. The indicators that condition the output are coded in positions 22 and 23, 25 and 26, and 28 and 29. When an N is entered in positions 21, 24, or 27, the indicator in the associated position must be off for the line or field to be written. Otherwise, the indicator must be on for the line or field to be written. See PAGE, PAGE1-PAGE7 on page 5-182 for information on how output indicators affect the PAGE fields. If more than one indicator is specified on one line, all indicators are considered to be in an AND relationship. If the output record must be conditioned by more than three indicators in an AND relationship, enter the letters AND in positions 16 through 18 of the following line and specify the additional indicators in positions 21 through 29 on that line. For an AND relationship, fetch overflow (position 18) can only be specified on the first line. Positions 40 through 51 (spacing and skipping) must be blank for all AND lines. An overflow indicator must be defined on the file description specifications with the OFLIND keyword before it can be used as a conditioning indicator. If a line is to be conditioned as an overflow line, the overflow indicator must appear on the main specification line or on the OR line. If an overflow indicator is used on an AND line, the line is not treated as an overflow line, but the overflow indicator is checked before the line is written. In this case, the overflow indicator is treated like any other output indicator. If the output record is to be written when any one of two or more sets of conditions exist (an OR relationship), enter the letters OR in positions 16-18 of the following specification line, and specify the additional OR indicators on that line.
Specifications
5-179
5-180
5-181
5-182
Position 45 is used to reset a numeric field to zeros or a character, graphic, or UCS-2 field to blanks. Date, time, and timestamp fields are reset to their default values. If the field is conditioned by indicators in positions 21 through 29, the blank after is also conditioned. This position must be blank for look-ahead, user date reserved words, *PLACE, named constants, and literals. Resetting fields to zeros may be useful in total output when totals are accumulated and written for each control group in a program. After the total is accumulated and written for one control group, the total field can be reset to zeros before accumulation begins on the total for the next control group. If blank after (position 45) is specified for a field to be written more than once, the B should be entered on the last line specifying output for that field, or else the field named will be printed as the blank-after value for all lines after the one doing the blank after.
Specifications
5-183
EP is the calculated end position. PEP is the previous end position. For the first field specification in the record, PEP is equal to zero. FL is the length of the field after editing, or the length of the constant specified in this specification. The use of +nnnn is equivalent to placing nnnn positions between the fields. A -nnnn causes an overlap of the fields by nnnn positions. For example, if the previous end position (PEP) is 6, the number of positions to be placed between the fields (nnnn) is 5, and the field length (FL) is 10, the end position (EP) equals 21. When *PLACE is used, an actual end position must be specified; it cannot be blank or a displacement. An entry of blank is treated as an entry of +0000. No positions separate the fields.
Explanation
5-184
This position must be blank if editing is specified. The entry in position 52 specifies the external format of the data in the records in the file. This entry has no effect on the format used for internal processing of the output field in the program. For numeric fields, the number of bytes required in the output record depends on this format. For example, a numeric field with 5 digits requires: v 5 bytes when written in zoned format v 3 bytes when written in packed format v 6 bytes when written in either L or R format v 4 bytes when written in binary format | | | | | v 2 bytes when written in either I or U format. This may cause an error at run time if the value is larger than the maximum value for a 2-byte integer or unsigned field. For the case of 5-digit fields, binary-decimal format may be better. Float numeric fields written out with blank Data Format entry occupy either 14 or 23 positions (for 4-byte and 8-byte float fields respectively) in the output record. A 'G' or blank must be specified for a graphic field in a program-described file. If 'G' is specified, then, the data will be output without SO/SI. If this column is blank for program-described output, then SO/SI brackets will be placed around the field in the output record by the compiler if the field is of type graphic. You must ensure that there is sufficient room in the output record for both the data and the SO/SI characters.
Specifications
5-185
5-186
Position 17 (Type)
Entry H or D Detail records T E Total records Exception records. Explanation
Position 17 indicates the type of record to be written. See Position 17 (Type) on page 5-177 for more information.
Position 18 (Release)
Entry R Explanation Release a device after output.
For more information on record addition, see Positions 18-20 (Record Addition/Deletion) on page 5-177.
Specifications
5-187
Position 45 is used to reset a numeric field to zeros or a character, graphic, or UCS-2 field to blanks. Date, time, and timestamp fields are reset to their default values. If the field is conditioned by indicators in positions 21 through 29, the blank after is also conditioned. This position must be blank for look-ahead, user date reserved words, *PLACE, named constants, and literals. Resetting fields to zeros may be useful in total output when totals are accumulated and written for each control group in a program. After the total is accumulated and written for one control group, the total field can be reset to zeros before accumulation begins on the total for the next control group. If blank after (position 45) is specified for a field to be written more than once, the B should be entered on the last line specifying output for that field, or else the field named will be printed as the blank-after value for all lines after the one doing the blank after.
Procedure Specifications
Procedure specifications are used to define prototyped procedures that are specified after the main source section, otherwise known as subprocedures. # # # # The prototype for the subprocedure may be defined in the main source section of the module containing the subprocedure definition. If the prototype is not specified, the prototype is implicitly defined using the information in the procedure interface. If the procedure interface is also not defined, a default prototype with no return value and no parameters is implicitly defined. A subprocedure includes the following: 1. A Begin-Procedure statement. (Use the DCL-PROC operation code in free-form, or specify B in position 24 of a fixed-form procedure specification) 2. A Procedure-Interface definition, which specifies the return value and parameters, if any. The procedure-interface definition is optional if the subprocedure does not return a value and does not have any parameters that are passed to it. The procedure interface must match the corresponding prototype, if the prototype is specified. 3. Other definitions including files, variables, constants and prototypes needed by the subprocedure. These definitions are local definitions. 4. Any calculation specifications needed to perform the task of the procedure. Any subroutines included within the subprocedure are local. They cannot be used outside of the subprocedure. If the
| | # # # # | |
5-188
| | | |
v In the following example, procedure getNextOrder is defined without a prototype. The procedure interface specifies EXTPROC(*DCLCASE) 2 , so the external name of the procedure is "getNextOrder", exactly as specified for the DCL-PROC statement 1 . Note: At run-time, you can see the external name in the joblog if the procedure has an error, or in the program stack when you display the job.
Specifications
5-189
| | | | | | | | | | | |
DCL-PROC getNextOrder; DCL-PI *N IND EXTPROC(*DCLCASE); order LIKEDS(order_t); END-PI; DCL-F orders STATIC; READ orders order; RETURN %EOF(orders); END-PROC getNextOrder;
1 2
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 ...+... 9 ...+... 10 PName+++++++++++..B...................Keywords+++++++++++++++++++++++++++++Comments++++++++++++ Figure 5-62. Procedure Specification Layout
If additional space is required for keywords, the keywords field can be continued on subsequent lines as follows: v Position 6 of the continuation line must contain a P v Positions 7 to 43 of the continuation line must be blank v The specification continues on or past position 44
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 ...+... 9 ...+... 10 P.....................................Keywords+++++++++++++++++++++++++++++Comments++++++++++++ Figure 5-63. Procedure Specification Keyword Continuation Line Layout
A name that is up to 15 characters long can be specified in the Name entry of the procedure specification without requiring continuation. Any name (even one with 15 characters or fewer) can be continued on multiple lines by coding an ellipsis (...) at the end of the partial name. A name definition consists of the following parts:
5-190
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 ...+... 9 ...+... 10 PContinuedName+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++Comments++++++++++++ Figure 5-64. Procedure Specification Continued Name Line Layout
Entry
Explanation
Name The name of the subprocedure to be defined. Use positions 7-21 to specify the name of the subprocedure being defined. If the name is longer than 15 characters, a name is specified in positions 7 - 80 of the continued name lines. The normal rules for RPG IV apply; reserved words cannot be used (see Symbolic Names on page 3-1). The name can begin in any position in the space provided. # The name specified must be the same as the name of the prototype describing the procedure, if a # prototype is specified. If a prototype is not specified, the prototype will be implicitly defined using the # name specified on the Procedure Specification and the information specified by the procedure interface. If position 24 contains an E, then the name is optional.
A subprocedure coding consists minimally of a beginning procedure specification and an ending procedure specification. Any parameters and return value, as well as other definitions and calculations for the subprocedure are specified between the procedure specifications.
Specifications
5-191
Positions 44 to 80 are provided for procedure specification keywords. Only a Begin-Procedure specification (B in position 24) can have a keyword entry.
Procedure-Specification Keywords
EXPORT
The specification of the EXPORT keyword allows the procedure to be called by another module in the program. The name in positions 7-21 is exported in uppercase form. Note: Procedure names are not imported using the IMPORT keyword. They are imported implicitly by any module in the program that makes a bound call to the procedure or that uses the procedure name to initialize a procedure pointer. If the EXPORT keyword is not specified, the procedure can only be called from within the module.
SERIALIZE
When the SERIALIZE keyword is specified in a concurrent-thread module, only one thread can run in the procedure at any time. If one thread is running in the procedure and another thread calls the procedure, the second thread will wait to run the procedure until the first thread is no longer running in the procedure. If a thread is running in the procedure and it makes a recursive call to the procedure, then it must return from all the recursive calls to the procedure before another thread can begin running in the procedure. The SERIALIZE keyword is allowed only when THREAD(*CONCURRENT) is specified on the Control specification. Specifying SERIALIZE for one procedure is similar to specifying THREAD(*SERIALIZE) on the control specification. The difference is that specifying THREAD(*SERIALIZE) on the Control specification limits access by multiple threads to all the procedures in the module, while specifying the SERIALIZE keyword for a procedure only limits access to that procedure. If you have more than one procedure in a module with the SERIALIZE keyword, the procedures are independent. One thread can be running in one serialized procedure, while another thread is running in another serialized procedure in the same module. For example, if procedures PROCA and PROCB in the same module both have the SERIALIZE keyword, one thread could be running PROCA while another thread was running PROCB. For more information on using serialized procedures, see THREAD(*CONCURRENT | *SERIALIZE) on page 5-34.
5-192
Operations
The RPG IV programming language allows you to do many different types of operations on your data. To perform an operation, you use either an operation code or a built-in function. This chapter summarizes the operation codes and built-in functions that are available. It also organizes the operation codes and built-in functions into categories. For detailed information about a specific operation code or built-in function, see Operation Codes on page 6-140 or Built-in Functions on page 6-64.
Operation Codes
The following table shows the free-form syntax for each operation code. v Extenders (A) # (A) (D) (D) # (D) (E) (H) (M) (N) (N) (N) (P) (R) (T) (Z) Always perform a dump, even if DEBUG(*NO) is specified Sort ascending Pass operational descriptors on bound call Date field Sort descending Error handling Half adjust (round the numeric result) Default precision rules Do not lock record Set pointer to *NULL after successful DEALLOC Do not force data to non-volatile storage Pad the result with blanks or zeros "Result Decimal Position" precision rules Time field Timestamp field
6-1
Free-Form Syntax ACQ{(E)} device-name workstn-file BEGSR subroutine-name {CALLP{(EMR)}} name( {parm1{:parm2...}} ) CHAIN{(ENHMR)} search-arg file-or-record-name {data-structure} CLEAR {*NOKEY} {*ALL} name CLOSE{(E)} file-name COMMIT{(E)} {boundary}
1
BEGSR CALLP CHAIN CLEAR CLOSE COMMIT DEALLOC DELETE DOU DOW DSPLY DUMP ELSE ELSEIF ENDDO ENDFOR ENDIF ENDMON ENDSL ENDSR EVAL EVALR EVAL-CORR EXCEPT EXFMT EXSR FEOD FOR FORCE IF IN
1 1
DEALLOC{(EN)} pointer-name DELETE{(EHMR)} {search-arg} file-or-record-name DOU{(MR)} indicator-expression DOW{(MR)} indicator-expression DSPLY{(E)} {message {message-queue {response}}} DUMP{(A)} {identifier} ELSE ELSEIF{(MR)} indicator-expression ENDDO ENDFOR ENDIF ENDMON ENDSL ENDSR {return-point} {EVAL{(HMR)}} result = expression EVALR{(MR)} result = expression EVAL-CORR{(EH)} target-ds = source-ds EXCEPT {except-name} EXFMT{(E)} format-name {data-structure} EXSR subroutine-name FEOD{(EN)} file-name FOR{(MR)} index {= start} {BY increment} {TO|DOWNTO limit} FORCE file-name IF{(MR)} indicator-expression IN{(E)} {*LOCK} data-area-name ITER LEAVE LEAVESR MONITOR NEXT{(E)} program-device file-name ON-ERROR {exception-id1 {:exception-id2...}} OPEN{(E)} file-name OTHER
6-2
Free-Form Syntax OUT{(E)} {*LOCK} data-area-name POST{(E)} {program-device} file-name READ{(EN)} file-or-record-name {data-structure} READC{(E)} record-name {data-structure} READE{(ENHMR)} search-arg|*KEY file-or-record-name {data-structure} READP{(EN)} name {data-structure} READPE{(ENHMR)} search-arg|*KEY file-or-record-name {data-structure} REL{(E)} program-device file-name
1
POST READ
RESET
RESET{(E)} {*NOKEY} {*ALL} name RETURN{(HMR)} expression ROLBK{(E)} SELECT SETGT{(EHMR)} search-arg file-or-record-name SETLL{(EHMR)} search-arg file-or-record-name SORTA{(AD)} array-name or keyed-ds-array TEST{(EDTZ)} {dtz-format} field-name
1
# SORTA
TEST
1
UNLOCK{(E)} name UPDATE{(E)} file-or-record-name {data-structure|%FIELDS(name{:name...})} WHEN{(MR)} indicator-expression WRITE{(E)} file-or-record-name {data-structure} XML-INTO{(EH)} target-or-handler xml-document XML-SAX{(E)} handler xml-document
XML-INTO XML-SAX
Note: 1. Complex-qualified names are not allowed for this operation code. The next table is a summary of the specifications for each operation code in traditional syntax. v An empty column indicates that the field must be blank. v All underlined fields are required. v An underscored space denotes that there is no resulting indicator in that position. v Symbols + Plus
Minus v Extenders (A) # (A) (D) (D) # (D) (E) Always perform a dump, even if DEBUG(*NO) is specified Sort ascending Pass operational descriptors on bound call Date field Sort descending Error handling
Operations, Expressions, and Functions
6-3
Half adjust (round the numeric result) Default precision rules Do not lock record Set pointer to *NULL after successful DEALLOC Pad the result with blanks or zeros "Result Decimal Position" precision rules Time field
(Z) Timestamp field v Resulting indicator symbols BL BN BOF EOF EQ ER FD HI IN LO LR NR NU OF ON Z ZB Blank(s) Blank(s) then numeric Beginning of the file End of the file Equal Error Found Greater than Indicator Less than Last record No record was found Numeric Off On Zero Zero or Blank
Resulting Indicators Codes ACQ (E ) ADD (H) ADDDUR (E) ALLOC (E) ANDxx BEGSR BITOFF BITON CABxx CALL (E) Comparand Comparand subroutine-name Bit numbers Bit numbers Comparand Program name Character field Character field Label Plist name HI LO ER EQ LR
7
Result Field
71-72
73-74 ER
75-76
ER ER
6-4
Table 6-2. Operation Codes in Traditional Syntax (continued) Resulting Indicators Codes CALLB (D E) CALLP (E M/R) CASxx CAT (P) CHAIN (E N) CHECK (E) CHECKR (E) CLEAR Comparand Source string 1 search-arg Comparator String Comparator String *NOKEY Factor 1 Factor 2 Procedure name or Procedure pointer name{ (parm1 {:parm2...}) } Comparand Source string 2:number of blanks name (file or record format) Base String:start Base String:start *ALL Subroutine name Target string data-structure Left-most Position(s) Right-most Position(s) name (variable or record format) ER ER Comparand pointer-name *LIKE *DTAARA search-arg Dividend Starting value Referenced field External data area name (file or record format) Divisor Limit value indicator-expression Comparand Comparand indicator-expression Comparand
4
71-72
73-74 ER
75-76 LR
HI
LO
EQ
NR2
ER ER ER FD2 FD2
LO ER
EQ
DEALLOC (E/N) DEFINE DEFINE DELETE (E) DIV (H) DO DOU (M/R) DOUxx DOW (M/R) DOWxx DSPLY (E)
message identifier
DUMP (A) ELSE ELSEIF (M/R) END ENDCS ENDDO ENDFOR ENDIF ENDMON ENDSL ENDSR
Increment value
label
return-point
Operations, Expressions, and Functions
6-5
Table 6-2. Operation Codes in Traditional Syntax (continued) Resulting Indicators Codes EVAL (H M/R) EVALR (M/R) EVAL-CORR EXCEPT EXFMT (E) EXSR EXTRCT (E) FEOD (EN) FOR FORCE GOTO IF (M/R) IFxx IN (E) ITER KFLD KLIST LEAVE LEAVESR LOOKUP1 (array) LOOKUP1 (table) MHHZO MHLZO MLHZO MLLZO MONITOR MOVE (P) MOVEA (P) MOVEL (P) MULT (H) MVR NEXT (E) OCCUR (E) ON-ERROR OPEN (E) ORxx OTHER OUT (E) *LOCK data-area-name ER Comparand program-device Occurrence value file-name Data structure Status codes file-name Comparand ER Occurrence value Data Attributes Multiplicand Data Attributes Source field Source Source field Multiplier Target field Target Target field Product Remainder + + + + + ER ER ZB ZB ZB Z Z Search argument Search argument Array name Table name Source field Source field Source field Source field Table name Target field Target field Target field Target field HI HI LO LO EQ6 EQ6 KLIST name Key field Comparand *LOCK Factor 1 Factor 2 Result = Expression Result = Expression EVAL-CORR target-ds = source-ds except-name Record format-name subroutine-name Date/Time:Duration Code file-name Target Field ER ER data-structure ER Result Field 71-72 73-74 75-76
Index-name = start-value BY increment TO|DOWNTO limit file-name Label indicator-expression Comparand data-area-name ER
6-6
Table 6-2. Operation Codes in Traditional Syntax (continued) Resulting Indicators Codes PARM PLIST POST (E)
3
71-72
73-74
75-76
READ (E N) READC (E) READE (E N) READP (E N) READPE (E N) REALLOC (E) REL (E) RESET (E) program-device *NOKEY search-arg search-arg
name (file or record format) name (file or record format) name (file or record format) Length file-name *ALL
ER
RETURN (H M/R) ROLBK (E) SCAN (E) SELECT SETGT (E) SETLL (E) SETOFF1 SETON
1
Expression ER Comparator string:length Base string:start Left-most position(s) NR2 NR2 OF ON ON array-name or keyed-ds-array Value Minuend Date/Time/ Timestamp Subtrahend Date/Time/Timestamp Duration:Duration Code Base string:start Root Difference Duration: Duration Code Date/Time/ Timestamp Target string + ER ER ER Z ER FD2
search-arg search-arg
ER ER OF ON EQ6 OF ON
SHTDN
# SORTA (A/D) #
SQRT (H) SUB (H) SUBDUR (E) (duration)
SUBDUR (E) (new Date/Time/ date) Timestamp SUBST (E P) TAG TEST (E)
8
ER
6-7
Table 6-2. Operation Codes in Traditional Syntax (continued) Resulting Indicators Codes TEST (D E)
8
Factor 2
Result Field Character or Numeric field Character or Numeric field Character or Numeric field
71-72
73-74 ER ER ER
75-76
TEST (E T)8 TEST (E Z)8 TESTB1 TESTN TESTZ TIME UNLOCK (E) UPDATE (E) WHEN (M/R) WHENxx WRITE (E) XFOOT (H) XLATE (E P) XML-INTO XML-SAX Z-ADD (H) Z-SUB (H) Note:
1 1
Bit numbers
OF NU AI
ON BN JR
EQ BL XX
name (file or data area) name (file or record format) indicator-expression Comparand Comparand name (file or record format) Array name From:To String:start datastructure Sum Target String + datastructure
ER ER
ER ER
EOF5 Z
XML-INTO target-or-handler xml-document XML-SAX{(E)} handler xml-document Addend Subtrahend Sum Difference + + Z Z
1. At least one resulting indicator is required. 2. The %FOUND built-in function can be used as an alternative to specifying an NR or FD resulting indicator. 3. You must specify factor 2 or the result field. You may specify both. 4. You must specify factor 1 or the result field. You may specify both. 5. The %EOF built-in function can be used as an alternative to specifying an EOF or BOF resulting indicator. 6. The %EQUAL built-in function can be used to test the SETLL and LOOKUP operations. 7. For all operation codes with extender 'E', either the extender 'E' or an ER error indicator can be specified, but not both. 8. You must specify the extender 'E' or an error indicator for the TEST operation.
Built-in Functions
Built-in functions are similar to operation codes in that they perform operations on data you specify. Built-in functions can be used in expressions. Additionally, constant-valued built-in functions can be used in named constants. These named constants can be used in any specification. All built-in functions have the percent symbol (%) as their first character. The syntax of built-in functions is:
function-name{(argument{:argument...})}
6-8
Arguments for the function may be variables, constants, expressions, a prototyped procedure, or other built-in functions. An expression argument can include a built-in function. The following example illustrates this.
CL0N01Factor1+++++++Opcode(E)+Extended-factor2++++++++++++++++++++++++++ * * This example shows a complex expression with multiple * nested built-in functions. * * %TRIM takes as its argument a string. In this example, the * argument is the concatenation of string A and the string * returned by the %SUBST built-in function. %SUBST will return * a substring of string B starting at position 11 and continuing * for the length returned by %SIZE minus 20. %SIZE will return * the length of string B. * * If A is the string Toronto, and B is the string * Ontario, Canada then the argument for %TRIM will * be Toronto, Canada and RES will have the value * Toronto, Canada. * C EVAL RES = %TRIM(A + %SUBST(B:11:%SIZE(B) - 20)) Figure 6-1. Built-in Function Arguments Example
See the individual built-in function descriptions for details on what arguments are allowed. Unlike operation codes, built-in functions return a value rather than placing a value in a result field. The following example illustrates this difference.
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq.... * * In the following example, CITY contains the string * Toronto, Ontario. The SCAN operation is used to locate the * separating blank, position 9 in this illustration. SUBST * places the string Ontario in field TCNTRE. * * Next, TCNTRE is compared to the literal Ontario and * 1 is added to CITYCNT. * C SCAN CITY C C ADD 1 C C SUBST CITY:C TCNTRE C Ontario IFEQ TCNTRE C ADD 1 CITYCNT C ENDIF * * In this example, CITY contains the same value, but the * variable TCNTRE is not necessary since the %SUBST built-in * function returns the appropriate value. In addition, the * intermediary step of adding 1 to C is simplified since * %SUBST accepts expressions as arguments. * C SCAN CITY C C IF %SUBST(CITY:C+1) = Ontario C EVAL CITYCNT = CITYCNT+1 C ENDIF Figure 6-2. Built-in Function Example
6-9
Note that the arguments used in this example (the variable CITY and the expression C+1) are analogous to the factor values for the SUBST operation. The return value of the function itself is analogous to the result. In general, the arguments of the built-in function are similar to the factor 1 and factor 2 fields of an operation code. Another useful feature of built-in functions is that they can simplify maintenance of your code when used on the definition specification. The following example demonstrates this feature.
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords++++++++++++++++++++++++++ * * In this example, CUSTNAME is a field in the * externally described data structure CUSTOMER. * If the length of CUSTNAME is changed, the attributes of * both TEMPNAME and NAMEARRAY would be changed merely by * recompiling. The use of the %SIZE built-in function means * no changes to your code would be necessary. * D CUSTOMER E DS D DS D TEMPNAME LIKE(CUSTNAME) D NAMEARRAY 1 OVERLAY(TEMPNAME) D DIM(%SIZE(TEMPNAME)) Figure 6-3. Simplified Maintenance with Built-in Functions
Built-in functions can be used in expressions on the extended factor 2 calculation specification and with keywords on the definition specification. When used with definition specification keywords, the value of the built-in function must be known at compile time and the argument cannot be an expression. The following table lists the built-in functions, their arguments, and the value they return.
Table 6-3. Built-In Functions Name %ABS %ADDR %ALLOC %BITAND %BITNOT %BITOR %BITXOR %CHAR %CHECK %CHECKR %DATE Arguments numeric expression variable name {: *DATA} number of bytes to allocate character, numeric character, numeric character, numeric character, numeric graphic, UCS-2, numeric, date, time, or timestamp expression {: date, time, or timestamp format} comparator string:string to be checked{:start position} comparator string:string to be checked{:start position} {value {: date format}} Value Returned absolute value of expression address of variable, or address of the data portion of a variable-length variable pointer to allocated storage bit wise ANDing of the bits of all the arguments bit-wise reverse of the bits of the argument bit-wise ORing of the bits of all the arguments bit-wise exclusive ORing of the bits of the two arguments value in character format first position of a character that is not in the comparator string, or zero if not found last position of a character that is not in the comparator string, or zero if not found the date that corresponds to the specified value, or the current system date if none is specified number of days as a duration
%DAYS
number of days
6-10
Table 6-3. Built-In Functions (continued) Name %DEC Arguments numeric expression {:digits:decpos} character expression: digits:decpos date, time or timestamp expression {:format} numeric or character expression: digits:decpos numeric expression date or time expression: date or time expression: unit dividend: divisor non-float numeric expression:edit code {:*CURSYM | *ASTFILL | currency symbol} numeric expression non-float numeric expression:edit word array, table, or multiple occurrence data structure name {file name} Value Returned value in packed numeric format
half-adjusted value in packed numeric format number of decimal digits difference between the two dates, times, or timestamps in the specified unit the quotient from the division of the two arguments string representing edited value character external display representation of float string representing edited value number of elements or occurrences '1' if the most recent cycle input, read operation, or write to a subfile (for a particular file, if specified) ended in an end-of-file or beginning-of-file condition; and, when a file is specified, if a more recent OPEN, CHAIN, SETGT or SETLL to the file was not successful '0' otherwise
%EQUAL
{file name}
'1' if the most recent SETLL (for a particular file, if specified) or LOOKUP operation found an exact match '0' otherwise
%ERROR
'1' if the most recent operation code with extender 'E' specified resulted in an error '0' otherwise
not applicable value in float format '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
character, graphic, or UCS-2 expression handling procedure : communication area number of hours numeric or character expression numeric or character expression data structure containing keys {: number of keys}
value in graphic format not applicable number of hours as a duration value in integer format half-adjusted value in integer format not applicable
6-11
Table 6-3. Built-In Functions (continued) Name %LEN %LOOKUPxx %MINUTES %MONTHS %MSECONDS %NULLIND Arguments any expression argument: array{:start index {:number of elements}} number of minutes number of months number of microseconds null-capable field name Value Returned length in digits or characters array index of the matching element number of minutes as a duration number of months as a duration number of microseconds as a duration value in indicator format representing the null indicator setting for the null-capable field current occurrence of the multiple-occurrence data structure '1' if the specified file is open '0' if the specified file is closed %PADDR %PARMS procedure or prototype name none procedure-interface parameter name pointer: numeric expression dividend: divisor replacement string: source string {:start position {:source length to replace}} address of procedure or prototype number of parameters passed to procedure number of a procedure-interface parameter pointer to allocated storage the remainder from the division of the two arguments string produced by inserting replacement string into source string, starting at start position and replacing the specified number of characters first position of search argument in string or zero if not found string produced by replacing scan string by replacement string in source string, with the scan starting at start position for the specified length number of seconds as a duration '1' if the system operator has requested shutdown '0' otherwise %SIZE %SQRT %STATUS variable, array, or literal {:* ALL} numeric value {file name} size of variable or literal square root of the numeric value 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 %STR %SUBARR pointer{:maximum length} array name:start index{:number of elements} characters addressed by pointer argument up to but not including the first x'00' array subset
%OCCUR %OPEN
# %PARMNUM
%REALLOC %REM %REPLACE
%SCAN
search argument:string to be searched{:start position} scan string: replacement string: source string {:scan start position {:scan length}}
# %SCANRPL # # #
%SECONDS %SHTDN
number of seconds
6-12
Table 6-3. Built-In Functions (continued) Name %SUBDT Arguments date or time expression: unit Value Returned an unsigned numeric value that contains the specified portion of the date or time value substring the class instance for the native method {value {: time format}} the time that corresponds to the specified value, or the current system time if none is specified the timestamp that corresponds to the specified value, or the current system timestamp if none is specified '*ON' if there is a match '*OFF' otherwise %TRIM %TRIML %TRIMR %UCS2 %UNS %UNSH %XFOOT %XLATE %XML %YEARS string {: characters to trim} string {: characters to trim} string {: characters to trim} character, graphic, or UCS-2 expression numeric or character expression numeric or character expression array expression from-characters: to-characters: string {: start position} xml document { : options } number of years string with left and right blanks or specified characters trimmed string with left blanks or specified characters trimmed string with right blanks or specified characters trimmed value in UCS-2 format value in unsigned format half-adjusted value in unsigned format sum of the elements the string with from-characters replaced by to-characters not applicable number of years as a duration
string:start{:length}
%TIMESTAMP
%TLOOKUPxx
Arithmetic Operations
The arithmetic operations are shown in the following table.
Table 6-4. Arithmetic Operations Operation Absolute Value Add Divide Division Remainder Multiply Square Root Subtract Zero and Add Traditional Syntax Free-Form Syntax %ABS (Absolute Value of Expression) on page 6-64 ADD (Add) on page 6-141 DIV (Divide) on page 6-177 MVR (Move Remainder) on page 6-255 MULT (Multiply) on page 6-254 SQRT (Square Root) on page 6-307 SUB (Subtract) on page 6-308 Z-ADD (Zero and Add) on page 6-377 + operator / operator or %DIV (Return Integer Portion of Quotient) on page 6-82 %REM (Return Integer Remainder) on page 6-113 * operator %SQRT (Square Root of Expression) on page 6-120 - operator (not allowed)
6-13
Arithmetic Operations
Table 6-4. Arithmetic Operations (continued) Operation Zero and Subtract Traditional Syntax Z-SUB (Zero and Subtract) on page 6-378 Free-Form Syntax (not allowed)
For examples of arithmetic operations, see Figure 6-4 on page 6-16. Remember the following when specifying arithmetic operations: v Arithmetic operations can be done only on numerics (including numeric subfields, numeric arrays, numeric array elements, numeric table elements, numeric named constants, numeric figurative constants, and numeric literals). v In general, arithmetic operations are performed using the packed-decimal format. This means that the fields are first converted to packed-decimal format prior to performing the arithmetic operation, and then converted back to their specified format (if necessary) prior to placing the result in the result field. However, note the following exceptions: If all operands are unsigned, the operation will use unsigned arithmetic. If all are integer, or integer and unsigned, then the operation will use integer arithmetic. If any operands are float, then the remaining operands are converted to float. However, the DIV operation uses either the packed-decimal or float format for its operations. For more information on integer and unsigned arithmetic, see Integer and Unsigned Arithmetic on page 6-15. v Decimal alignment is done for all arithmetic operations. Even though truncation can occur, the position of the decimal point in the result field is not affected. v The result of an arithmetic operation replaces the data that was in the result field. v An arithmetic operation does not change factor 1 and factor 2 unless they are the same as the result field. v If you use conditioning indicators with DIV and MVR, it is your responsibility to ensure that the DIV operation occurs immediately before the MVR operation. If conditioning indicators on DIV cause the MVR operation to be executed when the immediately preceding DIV was not executed, then undesirable results may occur. v For information on using arrays with arithmetic operations, see Specifying an Array in Calculations on page 4-43.
Ensuring Accuracy
v The length of any field specified in an arithmetic operation cannot exceed 63 digits. If the result exceeds 63 digits, digits are dropped from either or both ends, depending on the location of the decimal point. v The TRUNCNBR option (as a command parameter or as a keyword on a control specification) determines whether truncation on the left occurs with numeric overflow or a runtime error is generated. Note that TRUNCNBR does not apply to calculations performed within expressions. If any overflow occurs within expressions calculations, a run-time message is issued. In addition, TRUNCNBR does not apply to arithmetic operations performed in integer or unsigned format. v Half-adjusting is done by adding 5 (-5 if the field is negative) one position to the right of the last specified decimal position in the result field. The half adjust entry is allowed only with arithmetic operations, but not with an MVR operation or with a DIV operation followed by the MVR operation. Half adjust only affects the result if the number of decimal positions in the calculated result is greater than the number of decimal positions in the result field. Half adjusting occurs after the operation but before the result is placed in the result field. Resulting indicators are set according to the value of the result field after half-adjusting has been done. Half adjust is not allowed if the result field is float.
6-14
Arithmetic Operations
Performance Considerations
The fastest performance time for arithmetic operations occurs when all operands are in integer or unsigned format. The next fastest performance time occurs when all operands are in packed format, since this eliminates conversions to a common format.
6-15
Arithmetic Operations
6-16
Array Operations
*...1....+....2....+....3....+....4....+....5....+....6....+....7... CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....Comments C* C* In the following example, the initial field values are: C* C* A = 1 C* B = 10.0 C* C = 32 C* D = -20 C* E = 6 C* F = 10.0 C* G = 2.77 C* H = 70 C* J = .6 C* K = 25 C* L = 1.0, 1.7, -1.1 Result: C* C ADD 1 A 3 0 A = 002 C B ADD C V 5 2 V = 042.00 C B ADD D V V = -10.00 C Z-ADD C V V = 032.00 C SUB 1 E 3 0 E = 005 C C SUB B W 5 1 W = 0022.0 C C SUB D W W = 0052.0 C Z-SUB C W W = -0032.0 C MULT E F 3 0 F = 060 C B MULT G X 8 4 X = 0027.7000 C B MULT D X X = -0200.0000 C DIV B H 3 0 H = 007 C C DIV J Y 6 2 Y = 0053.33 C MVR Z 5 3 Z = 00.002 C SQRT K Z Z = 05.000 C XFOOT L Z Z = 01.600 Figure 6-5. Arithmetic Operations in Fixed-form Calculations
Array Operations
The array operations are shown in the following table.
Table 6-5. Array Operations Operation Look Up Elements Traditional Syntax LOOKUP (Look Up a Table or Array Element) on page 6-220 Free-Form Syntax %LOOKUPxx (Look Up an Array Element) on page 6-101 or %TLOOKUPxx (Look Up a Table Element) on page 6-132
Number of Elements Move an Array Sort an Array Subset an Array Sum the Elements of an Array
%ELEM (Get Number of Elements) on page 6-85 MOVEA (Move Array) on page 6-239 (not allowed)
SORTA (Sort an Array) on page 6-303 %SUBARR (Set/Get Portion of an Array) on page 6-125 XFOOT (Summing the Elements of an Array) on page 6-328 %XFOOT (Sum Array Expression Elements) on page 6-138
While many operations work with arrays, these operations perform specific array functions. See each operation for an explanation of its function.
Bit Operations
The bit operations are: v %BITAND (Bitwise AND Operation) on page 6-67
Operations, Expressions, and Functions
6-17
Bit Operations
v v v v v %BITNOT (Invert Bits) on page 6-68 %BITOR (Bitwise OR Operation) on page 6-68 %BITXOR (Bitwise Exclusive-OR Operation) on page 6-69 BITOFF (Set Bits Off) on page 6-145 BITON (Set Bits On) on page 6-146
The BITOFF and BITON operations allow you to turn off and on specific bits in a field specified in the result field. The result field must be a one-position character field. The TESTB operation compares the bits identified in factor 2 with the corresponding bits in the field named as the result field. The bits in a byte are numbered from left to right. The left most bit is bit number 0. In these operations, factor 2 specifies the bit pattern (bit numbers) and the result field specifies a one-byte character field on which the operation is performed. To specify the bit numbers in factor 2, a 1-byte hexadecimal literal or a 1-byte character field is allowed. The bit numbers are indicated by the bits that are turned on in the literal or the field. Alternatively, a character literal which contains the bit numbers can also be specified in factor 2. With the BITAND operation the result bit is ON when all of the corresponding bits in the arguments are ON, and OFF otherwise. With the BITNOT operation the result bit is ON when the corresponding bit in the argument is OFF, and OFF otherwise. With the BITOR operation the result bit is ON when any of the corresponding bits in the arguments are ON, and OFF otherwise. With the BITXOR operation the result bit is ON when just one of the corresponding bits in the arguments are ON, and OFF otherwise.
Branching Operations
The branching operations are shown in the following table.
Table 6-7. Branching Operations Operation Compare and Branch Go To Iterate Leave Leave a subroutine Traditional Syntax CABxx (Compare and Branch) on page 6-149 GOTO (Go To) on page 6-209 Free-Form Syntax (not allowed) (not allowed)
ITER (Iterate) on page 6-214 LEAVE (Leave a Do/For Group) on page 6-218 LEAVESR (Leave a Subroutine) on page 6-219
6-18
Branching Operations
Table 6-7. Branching Operations (continued) Operation Tag Traditional Syntax TAG (Tag) on page 6-313 Free-Form Syntax (not allowed)
The GOTO operation (when used with a TAG operation) allows branching. When a GOTO operation occurs, the program branches to the specified label. The label can be specified before or after the GOTO operation. The label is specified by the TAG or ENDSR operation. The TAG operation names the label that identifies the destination of a GOTO or CABxx operation. The ITER operation transfers control from within a DO-group to the ENDDO statement of the DO-group. The LEAVE operation is similar to the ITER operation; however, LEAVE transfers control to the statement following the ENDDO operation. The LEAVESR operation causes control to pass to the ENDSR operation of a subroutine. See each operation for an explanation of its function.
Call Operations
The call operations are shown in the following table.
Table 6-8. Call Operations Operation Call Program or Procedure Traditional Syntax v CALL (Call a Program) on page 6-150 v CALLB (Call a Bound Procedure) on page 6-151 v CALLP (Call a Prototyped Procedure or Program) on page 6-152 Identify Parameters v PARM (Identify Parameters) on page 6-265 v PLIST (Identify a Parameter List) on page 6-267 Number of Parameters %PARMS (Return Number of Parameters) on page 6-109 %PARMNUM (Return Parameter Number) on page 6-111 RETURN (Return to Caller) on page 6-288 PI or PR definition specification Free-Form Syntax CALLP (Call a Prototyped Procedure or Program) on page 6-152
# Number of a # Parameter
Return
# # # #
CALLP is one type of prototyped call. The second type is a call from within an expression. A prototyped call is a call for which there is a prototype defined for the call interface. The prototype may be explicitly defined using a Prototype definition, or it may be implicitly defined by the compiler from the Procedure Interface, if the procedure is defined in the same module as the call. Call operations allow an RPG IV procedure to transfer control to other programs or procedures. However, prototyped calls differ from the CALL and CALLB operations in that they allow free-form syntax. The RETURN operation transfers control back to the calling program or procedure and returns a value, if any. The PLIST and PARM operations can be used with the CALL and CALLB operations to indicate which parameters should be passed on the call. With a prototyped call, you pass the parameters on the call.
6-19
Call Operations
The recommended way to call a program or procedure (written in any language) is to code a prototyped call.
Prototyped Calls
With a prototyped call, you can call (with the same syntax): v Programs that are on the system at run time v Exported procedures in other modules or service programs that are bound in the same program or service program v Subprocedures in the same module # If the program or procedure is not defined in the same module as the call, a prototype must be included # in the definition specifications of the program or procedure making the call. It is used by the compiler to # call the program or procedure correctly, and to ensure that the caller passes the correct parameters. # If the procedure is defined in the same module as the call, it is not necessary to explicitly define a # prototype. The prototype can be implicitly defined by the compiler using the information specified by the # Procedure Interface for the procedure. When a program or procedure is prototyped, you do not need to know the names of the data items used in the program or procedure; only the number and type of parameters. Prototypes improve the communication between programs or procedures. Some advantages of using prototyped calls are: v The syntax is simplified because no PARM or PLIST operations are required. v For some parameters, you can pass literals and expressions. v When calling procedures, you do not have to remember whether operational descriptors are required. v The compiler helps you pass enough parameters, of the the correct type, format and length, by giving an error at compile time if the call is not correct. v The compiler helps you pass parameters with the correct format and length for some types of parameters, by doing a conversion at run time. Figure 6-6 shows an example using the prototype ProcName, passing three parameters. The prototype ProcName could refer to either a program or a procedure. It is not important to know this when making the call; this is only important when defining the prototype.
/FREE // The following calls ProcName with the 3 // parameters CharField, 7, and Field2: ProcName (CharField: 7: Field2); // If you need to specify operation extenders, you must also // specify the CALLP operation code: CALLP(e) ProcName (CharField: 7: Field2); /END-FREE Figure 6-6. Sample of CALLP operation
When calling a procedure in an expression, you should use the procedure name in a manner consistent with the data type of the specified return value. For example, if a procedure is defined to return a numeric, then the call to the procedure within an expression must be where a numeric would be expected. For more information on calling programs and procedures, and passing parameters, see the appropriate chapter in the Rational Development Studio for i: ILE RPG Programmer's Guide. For more information on defining prototypes and parameters, see Prototypes and Parameters on page 4-27.
6-20
Call Operations
Operational Descriptors
Sometimes it is necessary to pass a parameter to a procedure even though the data type is not precisely known to the called procedure, (for example, different types of strings). In these instances you can use operational descriptors to provide descriptive information to the called procedure regarding the form of the parameter. The additional information allows the procedure to properly interpret the string. You should only use operational descriptors when they are expected by the called procedure. You can request operational descriptors for both prototyped and non-prototyped parameters. For prototyped calls, you specify the keyword OPDESC on the prototype definition. For non-prototyped parameters, you specify (D) as the operation code extender of the CALLB operation. In either case, operational descriptors are then built by the calling procedure and passed as hidden parameters to the called procedure. # # # # # # # # When you have specified the OPDESC keyword for your own procedure, you can call APIs to find out information about the length and type of some of the parameters. These APIs require you to pass a parameter number to identify which parameter you are interested in. Usually, the number of a parameter can be obtained by simply counting the parameters in the prototype or procedure interface. However, when the RTNPARM keyword is specified, the number of each parameter is one higher than its apparent number. Use the %PARMNUM built-in function to get the number of a particular parameter instead of using a numeric literal. For more information, see OPDESC on page 5-123, RTNPARM on page 5-139 and %PARMNUM (Return Parameter Number) on page 6-111.
Program references are grouped to avoid the overhead of resolving to the target program. All references to a specific program using a named constant or literal are grouped so that the program is resolved to only once, and all subsequent references to that program (by way of named constant or literal only) do not cause a resolve to recur. The program references are grouped if both the program and the library name are identical. All program references by variable name are grouped by the variable name. When a program reference is made with a variable, its current value is compared to the value used on the previous program reference operation that used that variable. If the value did not change, no resolve is done. If it did change, a resolve is done to the new program specified. Note that this rule applies only to references using a variable name.
6-21
Call Operations
References using a named constant or literal are never re-resolved, and they do not affect whether or not a program reference by variable is re-resolved. Figure 6-7 illustrates the grouping of program references. Program CALL Example:
*...1....+....2....+....3....+....4....+....5....+....6....+....7...+.... DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++ D Pgm_Ex_A C LIB1/PGM1 D Pgm_Ex_B C PGM1 D PGM_Ex_C C LIB/PGM2 * *...1....+....2....+....3....+....4....+....5....+....6....+....7...+.... CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq.... * C CALL Pgm_Ex_A * * The following two calls will be grouped together because both * have the same program name (PGM1) and the same library name * (none). Note that these will not be grouped with the call using * Pgm_Ex_A above because Pgm_Ex_A has a different library * name specified (LIB1). * C CALL PGM1 C CALL Pgm_Ex_B * * The following two program references will be grouped together * because both have the same program name (PGM2) and the same * library name (LIB). * C CALL LIB/PGM2 C CALL Pgm_Ex_C * *...1....+....2....+....3....+....4....+....5....+....6....+....7...+.... CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq.... * * The first call in the program using CALLV below will result in * a resolve being done for the variable CALLV to the program PGM1. * This is independent of any calls by a literal or named constant * to PGM1 that may have already been done in the program. The * second call using CALLV will not result in a resolve to PGM1 * because the value of CALLV has not changed. * C MOVE PGM1 CALLV 21 C CALL CALLV C CALL CALLV Figure 6-7. Example of Grouping of Program References
6-22
Call Operations
Value of *ROUTINE
When a call fails, the contents of the *ROUTINE subfield of the program status data structure (PSDS) is updated with the following: v On an external call, the name of the called program (that is, for CALL or CALLP to a program). v On a bound static call, the name of the called procedure. v On a bound procedure pointer call, *N. Note that since the size of this subfield is only 8 bytes long, the name may be truncated.
Compare Operations
The compare operations are shown in the following table.
Table 6-9. Compare Operations Operation And Compare Compare and Branch Conditional Subroutine Do Until Do While If Or When Traditional Syntax ANDxx (And) on page 6-144 COMP (Compare) on page 6-171 CABxx (Compare and Branch) on page 6-149 CASxx (Conditionally Invoke Subroutine) on page 6-156 Free-Form Syntax AND operator =, <, >, <=, >=, or <> operator (not allowed) IF (If) on page 6-210 and EXSR (Invoke Subroutine) on page 6-203
DOU (Do Until) on page 6-180 or DOUxx DOU (Do Until) on page 6-180 (Do Until) on page 6-180 DOW (Do While) on page 6-182 or DOWxx (Do While) on page 6-183 DOW (Do While) on page 6-182
IF (If) on page 6-210 or IFxx (If) on page IF (If) on page 6-210 6-211 ORxx (Or) on page 6-262 WHEN (When True Then Select) on page 6-324 or WHENxx (When True Then Select) on page 6-325 OR operator WHEN (When True Then Select) on page 6-324
In the ANDxx, CABxx, CASxx, DOUxx, DOWxx, IFxx, ORxx, and WHENxx operations, xx can be: xx GT LT EQ NE GE LE Blanks Unconditional processing (CASxx or CABxx). The compare operations test fields for the conditions specified in the operations. These operations do not change the values of the fields. For COMP, CABXX, and CASXX, the resulting indicators assigned in postions 71 and 76 are set according to the results of the operation. All data types may be compared to fields of the same data type. Meaning Factor 1 is greater than factor 2. Factor 1 is less than factor 2. Factor 1 is equal to factor 2. Factor 1 is not equal to factor 2. Factor 1 is greater than or equal to factor 2. Factor 1 is less than or equal to factor 2.
6-23
Compare Operations
Remember the following when using the compare operations: v If numeric fields are compared, fields of unequal length are aligned at the implied decimal point. The fields are filled with zeros to the left and/or right of the decimal point making the field lengths and number of decimal positions equal for comparison. v All numeric comparisons are algebraic. A plus (+) value is always greater than a minus (-) value. v Blanks within zoned numeric fields are assumed to be zeros, if the FIXNBR(*ZONED) control specification keyword or command parameter is used in the compilation of the program. v If character, graphic, or UCS-2 fields are compared, fields of unequal length are aligned to their leftmost character. The shorter field is filled with blanks to equal the length of the longer field so that the field lengths are equal for comparison. v Date fields are converted to a common format when being compared. v Time fields are converted to a common format when being compared. v An array name cannot be specified in a compare operation, but an array element may be specified. v The ANDxx and ORxx operations can be used following DOUxx, DOWxx, IFxx, and WHENxx. v When comparing a character, graphic, or UCS-2 literal with zero length to a field (fixed or varying) containing blanks, the fields will compare equal. If you want to test that a value is of length 0, use the %LEN built-in function. See Figure 4-4 on page 4-8 for examples.
Attention!
Note the following points, especially if you want to avoid unpredictable results. v The order of the characters is not necessarily the same for UCS-2 data as it is for character or graphic data; for example '2' is less than 'A' in UCS-2, but it is greater than 'A' for a character comparison. If a comparison operation involves implicit conversion to UCS-2, or if you change some of your fields to have UCS-2 type instead of character or graphic type, then you may notice that some less-than or greater-than comparisons have different results than you expect. v All graphic and UCS-2 comparisons are done using the hexadecimal representation of the data. The alternate sequence is not used. v If an alternate collating sequence (using the ALTSEQ{(*NONE | *SRC | *EXT)} on page 5-17 keyword on the Control specification) has been specified for the comparison of character fields, the comparands are converted to the alternate sequence and then compared. If *HIVAL or *LOVAL is used in the comparison, the alternate collating sequence may alter the value before the compare operation. Note that if either comparand is defined with the ALTSEQ(*NONE) keyword on the definition specification, the alternate collating sequence is not used. v When comparing a basing pointer to *NULL (or to a basing pointer with value *NULL), the only comparisons that produce predictable results are for equality and inequality. v Comparing pointers for less-than or greater-than produces predictable results only when the pointers point to addresses in contiguous storage. For example, all pointers are set to addresses in one *USRSPC, or all pointers are set to the addresses of array elements in one array. v When procedure pointer fields are compared for anything except equality or inequality, the results will be unpredictable. v Because of the way float values are stored, they should not be compared for equality or inequality. Instead, the absolute value of the difference between the two values should be compared with a very small value.
Conversion Operations
The following built-in functions perform conversion operations: v %CHAR (Convert to Character Data) on page 6-72 v %DEC (Convert to Packed Decimal Format) on page 6-77 v %DECH (Convert to Packed Decimal Format with Half Adjust) on page 6-78
6-24
Conversion Operations
v v v v v v v v v v %EDITC (Edit Value Using an Editcode) on page 6-82 %EDITFLT (Convert to Float External Representation) on page 6-84 %EDITW (Edit Value Using an Editword) on page 6-85 %FLOAT (Convert to Floating Format) on page 6-90 %GRAPH (Convert to Graphic Value) on page 6-92 %INT (Convert to Integer Format) on page 6-97 %INTH (Convert to Integer Format with Half Adjust) on page 6-97 %UCS2 (Convert to UCS-2 Value) on page 6-136 %UNS (Convert to Unsigned Format) on page 6-137 %UNSH (Convert to Unsigned Format with Half Adjust) on page 6-137
These built-in functions are available in both the traditional syntax and free-form syntax. The traditional MOVE and MOVEL operation codes perform conversions when factor 2 and the result field have different types. See: v MOVE (Move) on page 6-226 v MOVEL (Move Left) on page 6-245
Data-Area Operations
The data-area operations are: v IN (Retrieve a Data Area) on page 6-212 v OUT (Write a Data Area) on page 6-264 v UNLOCK (Unlock a Data Area or Release a Record) on page 6-321. These operations are available in both the traditional syntax and free-form syntax. The IN and OUT operations allow you to retrieve and write one or all data areas in a program, depending on the factor 2 entry. The IN and OUT operations also allow you to control the locking or unlocking of a data area. When a data area is locked, it can be read but not updated by other programs or procedures. The following lock states are used: v For an IN operation with *LOCK specified, an exclusive allow read lock state is placed on the data area. v For an OUT operation with *LOCK the data area remains locked after the write operation v For an OUT operation with blank the data area is unlocked after it is updated v UNLOCK is used to unlock data areas and release record locks, the data areas and/or records are not updated. During the actual transfer of data into or out of a data area, there is a system-internal lock on the data area. If several users are contending for the same data area, a user may get an error message indicating that the data area is not available. Remember the following when using the IN, OUT, and UNLOCK operations: v A data-area operation cannot be done on a data area that is not defined to the operating system. v Before the IN, OUT, and UNLOCK operations can be done on a data area, you must specify the DTAARA keyword on the definition specification for the data area, or specify the data area in the result field of an *DTAARA DEFINE statement. (For further information on the DEFINE statement, see DEFINE (Field Definition) on page 6-173.)
Operations, Expressions, and Functions
6-25
Data-Area Operations
v A locked data area cannot be updated or locked by another RPG program; however, the data area can be retrieved by an IN operation with factor 1 blank. v A data-area name cannot be the name of a multiple-occurrence data structure, an input record field, an array, an array element, or a table. v A data area cannot be the subfield of a multiple occurrence data structure, a data-area data structure, a program-status data structure, a file-information data structure (INFDS), or a data structure that appears on an *DTAARA DEFINE statement. v If the name of the data area is determined at runtime, due to the DTAARA(*VAR) keyword being used, the variable containing the name must be set before an IN operation. If a data area is locked because of a prior *LOCK IN operation, any other operations (IN, OUT, UNLOCK) for the data area will use the previously locked data area, and the variable containing the name will not be consulted. v If the library name is not specified by the DTAARA keyword, the library list will be used to locate the data area. | | | | A data area data structure is automatically read and locked at program initialization time, and the contents of the data structure are written to the data area when the program ends with LR on. If the data area for a data area data structure is not found, it will be created with an initial value of blanks. If the library list was searched for the data area, the new data area will be created in QTEMP.
| In free-form, the DTAARA(*AUTO) keyword specifies that the data structure is a data area data structure. | In fixed-form, a data structure defined with a U in position 23 of the definition specifications indicates | that the data structure is a data area. | In some cases, you can use the IN, OUT and UNLOCK operation codes to specify further operations for | the data area. For a free-form definition, you also specify *USRCTL as a parameter. For a fixed-form | definition, you specify the DTAARA keyword. If the data area for a data area data structure is not found, it will be created with an initial value of blanks. If the library list was searched for the data area, the new data area will be created in QTEMP. To define the local data area (*LDA) you can do one of the following: v Specify the DTAARA(*LDA) keyword on the definition specification for the data area. | v Specify UDS on a fixed-form definition specification for the data area and leave the name blank. | v Specify *N as the name on a free-form definition and specify the DTAARA keyword without a name. v Specify *LDA in factor 2 of a *DTAARA DEFINE statement. To define the *PDA you may specify the DTAARA(*PDA) keyword on the definition specification for the data area, or specify *PDA in factor 2 of a *DTAARA DEFINE statement.
Date Operations
The date operations are shown in the following table.
Table 6-10. Date Operations Operation Add Duration Extract Subtract Duration Traditional Syntax ADDDUR (Add Duration) on page 6-141 EXTRCT (Extract Date/Time/Timestamp) on page 6-203 SUBDUR (Subtract Duration) on page 6-308 Free-Form Syntax + operator %SUBDT (Extract a Portion of a Date, Time, or Timestamp) on page 6-128 - operator or %DIFF (Difference Between Two Date, Time, or Timestamp Values) on page 6-80
6-26
Date Operations
Table 6-10. Date Operations (continued) Operation Convert date/time/timestamp to character Convert date/time/timestamp to numeric Traditional Syntax MOVE (Move) on page 6-226 or MOVEL (Move Left) on page 6-245 MOVE (Move) on page 6-226 or MOVEL (Move Left) on page 6-245 Free-Form Syntax %CHAR (Convert to Character Data) on page 6-72 %DEC (Convert to Packed Decimal Format) on page 6-77 %DATE (Convert to Date) on page 6-76 %TIME (Convert to Time) on page 6-131 %TIMESTAMP (Convert to Timestamp) on page 6-132 date + time
Convert character/numeric MOVE (Move) on page 6-226 or to date MOVEL (Move Left) on page 6-245 Convert character/numeric MOVE (Move) on page 6-226 or to time MOVEL (Move Left) on page 6-245 Convert character/numeric/date to timestamp Move date/time to timestamp Test Number of Years Number of Months Number of Days Number of Hours Number of Minutes Number of Seconds Number of Microseconds MOVE (Move) on page 6-226 or MOVEL (Move Left) on page 6-245 MOVE (Move) on page 6-226 or MOVEL (Move Left) on page 6-245
TEST (Test Date/Time/Timestamp) on page 6-314 %YEARS (Number of Years) on page 6-140 %MONTHS (Number of Months) on page 6-104 %DAYS (Number of Days) on page 6-77 %HOURS (Number of Hours) on page 6-96 %MINUTES (Number of Minutes) on page 6-104 %SECONDS (Number of Seconds) on page 6-118 %MSECONDS (Number of Microseconds) on page 6-105
Date operations allow you to work with dates, times, and timestamp fields and character or numeric fields that represent dates, times, and timestamps. You can: v v v v Add or subtract a duration in years, months, days, hours, minutes, seconds, or microseconds Determine the duration between two dates, times, or timestamps Extract a portion of a date, time, or timestamp (for example, the day) Test that a value is valid as a date, time, or timestamp.
To add or subtract a duration, you can use the + or - operator in free-form syntax or the ADDDUR or SUBDUR operation code in traditional syntax. The following table shows the built-in functions that you use in free-form syntax and the duration codes that you use in traditional syntax.
Table 6-11. Built-In Functions and Duration Codes Unit Year Month Day Hour Minute Second Microsecond Built-In Function %YEARS %MONTHS %DAYS %HOURS %MINUTES %SECONDS %MSECONDS Duration Code *YEARS or *Y *MONTHS or *M *DAYS or *D *HOURS or *H *MINUTES or *MN *SECONDS or *S *MSECONDS or *MS
6-27
Date Operations
For example, you can add 23 days to an existing date in either of the following ways:
C ADDDUR 23:*D DUEDATE
To calculate the duration between two dates, times, or timestamps, you can use the %DIFF built-in function in free-form syntax or the SUBDUR operation code in traditional syntax. In either case, you must specify one of the duration codes shown in Table 6-11 on page 6-27. The duration is given in complete units, with any remainder discarded. A duration of 59 minutes, expressed in hours, is 0. A duration of 61 minutes, expressed in hours, is 1. The following table shows additional examples, using the SUBDUR operation code. The %DIFF built-in function would give the same results.
Table 6-12. Resulting Durations Using SUBDUR Duration Unit Months Factor 1 1999-03-28 1999-03-14 1999-03-15 Years 1999-03-14 1999-03-15 1999-03-14-12.34.45.123456 Hours 1990-03-14-23.00.00.000000 Factor 2 1999-02-28 1998-03-15 1998-03-15 1998-03-15 1998-03-15 1998-03-14-12.34.45.123457 1990-03-14-22.00.00.000001 Result 1 month 11 months 12 months 0 years 1 year 0 years 0 hours
Unexpected Results
A month can contain 28, 29, 30, or 31 days. A year can contain 365 or 366 days. Because of this inconsistency, the following operations can give unexpected results: v Adding or subtracting a number of months (or calculating a duration in months) with a date that is on the 29th, 30th, or 31st of a month v Adding or subtracting a number of years (or calculating a duration in years) with a February 29 date. The following rules are used: v When months or years are added or subtracted, the day portion remains unchanged if possible. For example, 2000-03-15 + %MONTHS(1) is 2000-04-15. v If the addition or subtraction would produce a nonexistent date (for example, April 31), the last day of the month is used instead. v Any month or year operation that changes the day portion is not reversible. For example, 2000-03-31 + %MONTHS(1) is 2000-04-30 changes the day from 31 to 30. You cannot get back the original 2000-03-31 by subtracting one month. The operation 2000-03-31 + %MONTHS(1) - %MONTHS(1) becomes 2000-03-30. v The duration between two dates is one month if the later date minus one month gives the first date. For example, the duration in months (rounded down) between 2000-03-31 and 2000-04-30 is 0 because 2000-04-30 - %MONTHS(1) is 2000-03-30 (not 2000-03-31).
6-28
Declarative Operations
Declarative Operations
The declarative operations are shown in the following table.
Table 6-13. Declarative Operations Operation Define Field Define Key Traditional Syntax DEFINE (Field Definition) on page 6-173 v KFLD (Define Parts of a Key) on page 6-215 v KLIST (Define a Composite Key) on page 6-216 Identify Parameters v PARM (Identify Parameters) on page 6-265 v PLIST (Identify a Parameter List) on page 6-267 Tag TAG (Tag) on page 6-313 (not allowed) PR definition specification Free-Form Syntax LIKE or DTAARA keyword on definition specification (not allowed)
The declarative operations do not cause an action to occur (except PARM with optional factor 1 or 2); they can be specified anywhere within calculations. They are used to declare the properties of fields or to mark parts of a program. The control level entry (positions 7 and 8) can be blank or can contain an entry to group the statements within the appropriate section of the program. The DEFINE operation either defines a field based on the attributes (length and decimal positions) of another field or defines a field as a data area. The KLIST and KFLD operations are used to indicate the name by which a composite key field may be referred and the fields that compose the composite key. A composite key is a key that contains a list of key fields. It is built from left to right, with the first KFLD specified being the leftmost (high-order) field of the composite key. The PLIST and PARM operations are used with the CALL and CALLB operations to allow a called program or procedure access to parameters from a calling program or procedure. The TAG operation names the destination of a branching operation such as GOTO or CABxx.
Error-Handling Operations
The exception-handling operation codes are: v MONITOR (Begin a Monitor Group) on page 6-224 v ON-ERROR (On Error) on page 6-260 v ENDMON, as described in ENDyy (End a Structured Group) on page 6-189 These operation codes are available in both the traditional syntax and free-form syntax. MONITOR, ON-ERROR and ENDMON are used to code a monitor group. The monitor group consists of a monitor block, followed by one or more on-error blocks, followed by ENDMON. The monitor block contains the code that you think might generate an error. The on-error blocks contain the code to handle errors that occur in the monitor block. A monitor block consists of a MONITOR operation followed by the operations that will be monitored. An on-error block consists of an ON-ERROR operation, with a list of status codes, followed by the operations that will be performed if an error in the monitor block generates any of the listed status codes.
Operations, Expressions, and Functions
6-29
Error-Handling Operations
When an error occurs in the monitor block and the operation has an (E) extender or an error indicator, the error will be handled by the (E) extender or the error indicator. If no indicator or extender can handle the error, control passes to the on-error block containing the status code for the error. When the on-error block is finished, control passes to the ENDMON. If there is no on-error block to handle the error, control passes to the next level of exception handling (the *PSSR or INFSR subroutines, or the default error handler).
/free MONITOR; OPEN FILE; DOW getNextRecord (); X = X + 1; nameList(X) = name; ENDDO; CLOSE FILE; ON-ERROR 1216; DSPMSG (Error opening file FILE : %status); RETURN; ON-ERROR 121; DSPMSG (Array NAME is too small : %status); RETURN; ON-ERROR *ALL; DSPMSG (Unexpected error : %status); RETURN; ENDMON; /end-free
_ | | +-- This is the monitor block | | _| _ | | +-- First on-error block _| _ | +-- Second on-error block | _| _ | +-- Final catch-all on-error block | _| --- End of MONITOR group
File Operations
The file operation codes are: v ACQ (Acquire) on page 6-140 v CHAIN (Random Retrieval from a File) on page 6-159 v CLOSE (Close Files) on page 6-170 v COMMIT (Commit) on page 6-170 v DELETE (Delete Record) on page 6-176 v v v v v EXCEPT (Calculation Time Output) on page 6-200 EXFMT (Write/Then Read Format) on page 6-201 FEOD (Force End of Data) on page 6-205 FORCE (Force a Certain File to Be Read Next Cycle) on page 6-208 NEXT (Next) on page 6-255
v OPEN (Open File for Processing) on page 6-261 v POST (Post) on page 6-268 v v v v v READ (Read a Record) on page 6-270 READC (Read Next Changed Record) on page 6-272 READE (Read Equal Key) on page 6-273 READP (Read Prior Record) on page 6-276 READPE (Read Prior Equal) on page 6-277
IBM i: ILE RPG Reference
6-30
File Operations
v v v v v REL (Release) on page 6-281 ROLBK (Roll Back) on page 6-291 SETGT (Set Greater Than) on page 6-295 SETLL (Set Lower Limit) on page 6-298 UNLOCK (Unlock a Data Area or Release a Record) on page 6-321
v UPDATE (Modify Existing Record) on page 6-323 v WRITE (Create New Records) on page 6-327. The file built-in functions are: v %EOF (Return End or Beginning of File Condition) on page 6-86 v %EQUAL (Return Exact Match Condition) on page 6-87 v %FOUND (Return Found Condition) on page 6-90 v %OPEN (Return File Open Condition) on page 6-106 v %STATUS (Return File or Program Status) on page 6-121 These operations are available in both the traditional syntax and free-form syntax. Most file operations can be used with both program described and externally described files. When an externally described file is used with certain file operations, a record format name, rather than a file name, can be specified in factor 2. Thus, the processing operation code retrieves and/or positions the file at a record format of the specified type according to the rules of the calculation operation code used. When the OVRDBF (override with data base file) command is used with the MBR (*ALL) parameter specified, the SETLL, SETGT and CHAIN operations only process the current open file member. For more information, refer to the see the IBM i Information Center database and file systems category. The CHAIN, READ, READC, READE, READP, and READPE operations may have a result data structure. For these operations, data is transferred directly between the file and the data structure, without processing the input specifications for the file. Thus, no record identifying or field indicators are set on as a result of an input operation to a data structure. If all input operations to the file have a result data structure, input specifications are not required. The WRITE and UPDATE operations that specify a program described file name in factor 2 must have a data structure name specified in the result field. WRITE and UPDATE operations to an externally described file or record may have a result data structure. For these operations, data is transferred directly between data structure and the file, without processing the output specifications for the file. If all output operations to the file have a result data structure, output specifications are not required. A data structure name is allowed as the result of an I/O operation to an externally described file name or record name as follows: 1. When a record name is specified on an I/O operation, the origin of the data structure must match the record. That is, the data structure must be defined using LIKEREC(rec) or EXTNAME(file:rec) where rec is the format name specified on the operation. For input operations, the result data structure (or base structure for the LIKEDS data structure) must be defined using *INPUT. For output operations, the result data structure must be defined using *OUTPUT. For UPDATE to a DISK file, the result data structure may be defined using either *INPUT or *OUTPUT. 2. A result data structure may be specified for an I/O operation to an externally described file name, in addition to a record name, for opcodes CHAIN, READ, READE, READP, and READPE. When the name of an externally described file is specified, the data structure must contain one subfield data structure for each record with input-capable fields, where the allowed subfield data structures are defined as in rule 1. Each subfield data structure must start in position 1. (Normally the overlaying
Operations, Expressions, and Functions
6-31
File Operations
subfields will be defined using keyword OVERLAY(ds:1).) In the special case where the file contains only one record, the result data structure may be defined as in rule 1. 3. The result data structure can also be defined using LIKEDS(ds), where ds is an data structure following these rules. If an input operation (CHAIN, EXFMT, READ, READC, READE, READP, READPE) does not retrieve a record because no record was found, because an error occurred in the operation, or because the last record was already retrieved (end of file), then no data is extracted and all fields in the program remain unchanged. If you specify N as the operation extender of a CHAIN, READ, READE, READP, or READPE operation for an update disk file, a record is read without locking. If no operation extender is specified, the record is locked if the file is an update disk file. Exception/errors that occur during file operations can be handled by the programmer (by coding an error indicator or specifying a file-error subroutine), or by the RPG IV error handler. Note: Input and output operations in subprocedures involving input and output specifications always use the global name, even if there is a local variable of the same name. For example, if the field name TOTALS is defined in the main source section, as well as in a subprocedure, any input or output operation in the subprocedure will use the field as defined in the main source section. See Database Null Value Support on page 4-86 for information on handling files with null-capable fields. You can pass a file as a parameter to a prototyped program or procedure. When you pass a file as a parameter, then any settings for the file that are defined using File specification keywords are in effect for all procedures that access the file. For example, if the EXTFILE keyword is specified with a variable parameter, and a called procedure opens the file, then the value of the caller's variable will be used to set the name of the file to be opened. If the called procedure needs to change or access those variables associated with the file through keywords, the calling procedure must pass the variables as a parameter. The file-feedback built-in functions %EOF(filename), %EQUAL(filename), %FOUND(filename), %OPEN(filename), and %STATUS(filename) can be used in the called procedure program or to determine the current state of the file by specifying the name of the file parameter as the operand to the built-in function. For more information on file parameters, see LIKEFILE(filename) on page 5-119 and General File Considerations on page 3-93.
6-32
File Operations
For non-free-form calculations, only field names and klist names are allowed as search argument. Operation extenders H, M, and R are allowed for CHAIN, DELETE, READE, READPE, SETGT, and SETLL when a list of search arguments or %KDS is specified. These extenders apply to the moving of the individual search argument to the search argument build area.
Indicator-Setting Operations
The indicator setting operation codes are: v SETOFF (Set Indicator Off) on page 6-301 v SETON (Set Indicator On) on page 6-302 These operation codes are available only in the traditional syntax. In free-form syntax, you can set the value of *INxx to *ON or *OFF using the EVAL operation. The following indicator-setting built-in function is available in both the traditional syntax and free-form syntax: v %NULLIND (Query or Set Null Indicator) on page 6-105 The SETON and SETOFF operations set (on or off) indicators specified in positions 71 through 76. At least one resulting indicator must be specified in these positions. Remember the following when setting indicators: v The 1P, MR, KA through KN, and KP through KY indicators cannot be set on by the SETON operation. v The 1P and MR indicators cannot be set off by the SETOFF operation. v Setting L1 through L9 on or off with a SETON or SETOFF operation does not set any lower control level indicators.
Information Operations
The information operations are shown in the following table.
Table 6-14. Information Operations Operation Dump Get Shutdown Status Get Time and Date Traditional Syntax Free-Form Syntax DUMP (Program Dump) on page 6-187 SHTDN (Shut Down) on page 6-302 TIME (Retrieve Time and Date) on page 6-320 %SHTDN (Shut Down) on page 6-118 v %DATE (Convert to Date) on page 6-76 v %TIME (Convert to Time) on page 6-131 v %TIMESTAMP (Convert to Timestamp) on page 6-132
The DUMP operation provides a dump of all indicators, fields, data structures, arrays, and tables used in a program. The SHTDN operation allows the program to determine whether the system operator has requested shutdown. If so, the resulting indicator that must be specified in positions 71 and 72 is set on. The TIME operation allows the program to access the system time of day and system date at any time during program running.
Initialization Operations
The initialization operations provide run-time clearing and resetting of all elements in a structure (record format, data structure, array, or table) or a variable (field, subfield, or indicator).
Operations, Expressions, and Functions
6-33
Initialization Operations
The initialization operations are: v CLEAR (Clear) on page 6-166 v RESET (Reset) on page 6-282. These operations are available in both the traditional syntax and free-form syntax. The CLEAR operation sets all elements in a structure or variable to their default value depending on the field type (numeric, character, graphic, UCS-2, indicator, pointer, or date/time/timestamp). The RESET operation sets all elements in a structure or variable to their initial values (the values they had at the end of the initialization step in the program cycle). The RESET operation is used with data structure initialization and the initialization subroutine (*INZSR). You can use both data structure initialization and the *INZSR to set the initial value of a variable. The initial value will be used to set the variable if it appears in the result field of a RESET operation. When these operation codes are applied to record formats, only fields which are output are affected (if factor 2 is blank) or all fields (if factor 2 is *ALL). The factor 1 entry of *NOKEY prevents key fields from being cleared or reset. *ALL may be specified in factor 2 if the result field contains a table name, or multiple occurrence data structure or record format. If *ALL is specified all elements or occurrences will be cleared or reset. See CLEAR (Clear) on page 6-166 and RESET (Reset) on page 6-282 for more detail. For more information see Data Types and Data Formats on page 4-48.
DEALLOC (Free Storage) on page 6-172 REALLOC (Reallocate Storage with New Length) on page 6-280 %REALLOC (Reallocate Storage) on page 6-112
%ADDR (Get Address of Variable) on page 6-65 %PADDR (Get Procedure Address) on page 6-107
The ALLOC operation allocates heap storage and sets the result-field pointer to point to the storage. The storage is uninitialized. The REALLOC operation changes the length of the heap storage pointed to by the result-field pointer. New storage is allocated and initialized to the value of the old storage. The data is truncated if the new size is smaller than the old size. If the new size is greater than the old size, the storage following the copied data is uninitialized. The old storage is released. The result-field pointer is set to point to the new storage. The DEALLOC operation releases the heap storage that the result-field pointer is set to. If operational extender (N) is specified, the pointer is set to *NULL after a successful deallocation.
6-34
ALLOC 25 Ptr1 DEALLOC Ptr1 * After this point, Fld1 should not be accessed since the * basing pointer Ptr1 no longer points to allocated storage. C CALL SOMEPGM * * * * * C During the previous call to SOMEPGM, several storage allocations may have been done. In any case, it is extremely dangerous to make the following assignment, since 25 bytes of storage will be filled with a. It is impossible to know what that storage is currently being used for. EVAL Fld1 = *ALLa
6-35
Message Operation
The message operation v DSPLY (Display Message) on page 6-185 allows interactive communication between the program and the operator or between the program and the display workstation that requested the program. This operation is available in both the traditional syntax and free-form syntax.
Move Operations
The move operations are shown in the following table.
Table 6-16. Move Operations Operation Move Traditional Syntax MOVE (Move) on page 6-226 Free-Form Syntax EVALR (Evaluate expression, right adjust) on page 6-193 or conversion built-in functions (not allowed) EVAL (Evaluate expression) on page 6-191 or conversionbuilt-in functions
MOVEA (Move Array) on page 6-239 MOVEL (Move Left) on page 6-245
Move operations transfer all or part of factor 2 to the result field. Factor 2 remains unchanged. The source and target of the move operation can be of the same or different types, but some restrictions apply: v For pointer moves, source and target must be the same type, either both basing pointers or both procedure pointers. v When using MOVEA, both the source and target must be of the same type. v MOVEA is not allowed for Date, Time or Timestamp fields. v MOVE and MOVEL are not allowed for float fields or literals. Resulting indicators can be specified only for character, graphic, UCS-2, and numeric result fields. For the MOVE and MOVEL operations, resulting indicators are not allowed if the result field is an unindexed array. For MOVEA, resulting indicators are not allowed if the result field is an array, regardless of whether or not it is indexed. The P operation extender can only be specified if the result field is character, graphic, UCS-2, or numeric.
6-36
Move Operations
6-37
Move Operations
more elements than the factor 2 array, the same padding takes place but the extra elements are not affected. A MOVEA operation with an array name in the result field will pad the last element affected by the operation plus all subsequent elements. When resulting indicators are specified for move operations, the result field determines which indicator is set on. If the result field is a character, graphic, or UCS-2 field, only the resulting indicator in positions 75 and 76 can be specified. This indicator is set on if the result field is all blanks. When the result field is numeric, all three resulting indicator positions may be used. These indicators are set on as follows: High (71-72) Set on if the result field is greater than 0. Low (73-74) Set on if the result field is less than 0. Equal (75-76) Set on if the result field is equal to 0.
v Timestamp to Date v Timestamp to Time v v v v v Date to Character or Numeric Time to Character or Numeric Timestamp to Character or Numeric Character or Numeric to Date Character or Numeric to Time
v Character or Numeric to Timestamp Factor 1 must be blank if both the source and the target of the move are Date, Time or Timestamp fields. If factor 1 is blank, the format of the Date, Time, or Timestamp field is used. Otherwise, factor 1 contains the date or time format compatible with the character or numeric field that is the source or target of the operation. Any valid format may be specified. See Date Data Type on page 4-73, Time Data Type on page 4-75, and Timestamp Data Type on page 4-77. Keep in mind the following when specifying factor 1: v Time format *USA is not allowed for movement between Time and numeric fields. v The formats *LONGJUL, *CYMD, *CMDY, and *CDMY, and a special value *JOBRUN are allowed in factor 1. (For more information, see Table 4-5 on page 4-74.) v A zero (0) specified at the end of a format (for example *MDY0) indicates that the character field does not contain separators.
6-38
Move Operations
v A 2-digit year format (*MDY, *DMY, *YMD, *JUL and *JOBRUN) can only represent dates in the range 1940 through 2039. A 3-digit year format (*CYMD, *CMDY, *CDMY) can only represent dates in the range 1900 through 2899. An error will be issued if conversion to a 2- or 3-digit year format is requested for dates outside these ranges. v When MOVE and MOVEL are used to move character or numeric values to or from a timestamp, the character or numeric value is assumed to contain a timestamp. Factor 2 is required and must be a character, numeric, Date, Time, or Timestamp value. It contains the field, array, array element, table name, literal, or named constant to be converted. The following rules apply to factor 2: v Separator characters must be valid for the specified format. v If factor 2 is not a valid representation of a date or time or its format does not match the format specified in factor 1, an error is generated. v If factor 2 contains UDATE or *DATE, factor 1 is optional and corresponds to the header specifications DATEDIT keyword. v If factor 2 contains UDATE and factor 1 entry is coded, it must be a date format with a 2-digit year. If factor 2 contains *DATE and factor 1 is coded, it must be a date format with a 4-digit year. The result field must be a Date, Time, Timestamp, numeric, or character variable. It can be a field, array, array element, or table name. The date or time is placed in the result field according to its defined format or the format code specified in factor 1. If the result field is numeric, separator characters will be removed, prior to the operation. The length used is the length after removing the separator characters. When moving from a Date to a Timestamp field, the time and microsecond portion of the timestamp are unaffected, however the entire timestamp is checked and an error will be generated if it is not valid. When moving from a Time to a Timestamp field, the microseconds part of the timestamp is set to 000000. The date portion remains unaffected, but the entire timestamp will be checked and an error will be generated when it is not valid. If character or numeric data is longer than required, only the leftmost data (rightmost for the MOVE operation) is used. Keep in mind that factor 1 determines the length of data to be moved. For example, if the format of factor 1 is *MDY for a MOVE operation from a numeric date, only the rightmost 6 digits of factor 2 would be used. Examples of Converting a Character Field to a Date Field: Figure 6-9 on page 6-40 shows some examples of how to define and move 2- and 4-digit year dates between date fields, or between character and date fields.
6-39
Move Operations
*..1....+....2....+....3....+....4....+....5....+....6....+....7...+.... * Define two 8-byte character fields. D CHR_8a s 8a inz(95/05/21) D CHR_8b s 8a inz(abcdefgh) * * Define two 8-byte date fields. To get a 2-digit year instead of * the default 4-digit year (for *ISO format), they are defined * with a 2-digit year date format, *YMD. For D_8a, a separator (.) * is also specified. Note that the format of the date literal * specified with the INZ keyword must be the same as the format * specified on the * control specification. In this case, none * is specified, so it is the default, *ISO. * D D_8a s d datfmt(*ymd.) D D_8b s d inz(d1995-07-31) datfmt(*ymd) * * Define a 10-byte date field. By default, it has *ISO format. D D_10 s d inz(d1994-06-10) * * D_10 now has the value 1995-05-21 * * Move the 8-character field to a 10-character date field D_10. * It will contain the date that CHR_8a was initialized to, but * with a 4-digit year and the format of D_10, namely, * 1995-05-21 (*ISO format). * * Note that a format must be specified with built-in function * %DATE to indicate the format of the character field. * /FREE D_10 = %DATE (CHR_8a: *YMD); // // Move the 10-character date to an 8-character field CHR_8b. // It will contain the date that was just moved to D_10, but with // a 2-digit year and the default separator indicated by the *YMD // format. // CHR_8b = %CHAR (D_10: *YMD); // // Move the 10-character date to an 8-character date D_8a. // It will contain the date that * was just moved to D_10, but // with a 2-digit year and a . separator since D_8a was defined // with the (*YMD.) format. // D_8a = D_10; // // Move the 8-character date to a 10-character date D_10 // It will contain the date that * D_8b was initialized to, // but with a 4-digit year, 1995-07-31. // D_10 = D_8b; // // After the last move, the fields will contain // CHR_8b: 95/05/21 // D_8a: 95.05.21 // D_10: 1995-07-31 // *INLR = *ON; /END-FREE Figure 6-9. Moving character and date data
The following example shows how to convert from a character field in the form CYYMMDD to a date field in *ISO format. This is particularly useful when using command parameters of type *DATE.
6-40
Move Operations
# The RPG program is only intended to be called using the command interface, so it is not necessary to # specify a prototype for the program. The prototype will be implicitly defined by the compiler using the # information in the procedure interface.
CMD PARM PROMPT(Use DATE parameter) KWD(DATE) TYPE(*DATE)
Figure 6-10. Source for a command using a date parameter. *..1....+....2....+....3....+....4....+....5....+....6....+....7...+.... # * Procedure interface for this program (no prototype is necessary) # PI EXTPGM(FIG210) # D FIG210 7A # D DateParm # * Declare a date type with date format *ISO. # S D DATFMT(*ISO) # D ISO_DATE # * The format of the DateParm parameter is CYYMMDD, so code # * *CYMD0 as the 2nd parameter of built-in function %DATE. # /FREE # ISO_DATE = %DATE (DateParm: *CYMD0); # /END-FREE # # # # Figure 6-11. Part of RPG IV command processing program for this command. #
Note: While you may see this usage in old programs, your code will be clearer if you use hexadecimal literals for this purpose. Use X'F0' to obtain a positive zone and X'D0' to obtain a negative zone. Note: The character (-) is represented by a hexadecimal 60, and cannot be used to obtain a negative result, since it has a zone of 6, and a negative result requires a zone of "D".
6-41
Result Operations
Character Factor Two
MLHZO
Character
Factor Two
MHHZO
MLLZO MHLZO
MLLZO
MHLZO
Character
Result Field
Numeric
Result Field
Numeric
Factor Two
MLHZO
Numeric
Factor Two
MLLZO
MLLZO
Character
Figure 6-12. Function of MOVE Zone Operations
Result Field
Numeric
Result Field
Result Operations
The following built-in functions work with the result of the previous operation: v %EQUAL (Return Exact Match Condition) on page 6-87 v %FOUND (Return Found Condition) on page 6-90 v %ERROR (Return Error Condition) on page 6-89 v %STATUS (Return File or Program Status) on page 6-121 These built-in functions are available in both the traditional syntax and free-form syntax.
Size Operations
The following built-in functions return information about the size of a varible, field, constant, array, table, or data structure: v %DECPOS (Get Number of Decimal Positions) on page 6-79 v %LEN (Get or Set Length) on page 6-98 v %SIZE (Get Size in Bytes) on page 6-119 These built-in functions are available in both the traditional syntax and free-form syntax.
String Operations
The string operations are shown in the following table.
Table 6-17. String Operations Operation Concatenate Check Check Reverse Traditional Syntax CAT (Concatenate Two Strings) on page 6-157 CHECK (Check Characters) on page 6-162 CHECKR (Check Reverse) on page 6-164 Free-Form Syntax + operator %CHECK (Check Characters) on page 6-73 %CHECKR (Check Reverse) on page 6-75
6-42
String Operations
Table 6-17. String Operations (continued) Operation Create Replace Scan Scan and Replace Substring Translate Trim Blanks Traditional Syntax Free-Form Syntax
%STR (Get or Store Null-Terminated String) on page 6-123 %REPLACE (Replace Character String) on page 6-114 SCAN (Scan String) on page 6-292 %SCAN (Scan for Characters) on page 6-115
%SCANRPL (Scan and Replace Characters) on page 6-116 SUBST (Substring) on page 6-311 XLATE (Translate) on page 6-329 %SUBST (Get Substring) on page 6-129 %XLATE (Translate) on page 6-138
%TRIM (Trim Characters at Edges) on page 6-133, %TRIML (Trim Leading Characters) on page 6-134, or %TRIMR (Trim Trailing Characters) on page 6-135
The string operations include concatenation, scanning, substringing, translation, and verification. String operations can only be used on character, graphic, or UCS-2 fields. The CAT operation concatenates two strings to form one. The CHECK and CHECKR operations verify that each character in factor 2 is among the valid characters in factor 1. CHECK verifies from left to right and CHECKR from right to left. The SCAN operation scans the base string in factor 2 for occurrences of another string specified in factor 1. The SUBST operation extracts a specified string from a base string in factor 2. The extracted string is placed in the result field. The XLATE operation translates characters in factor 2 according to the from and to strings in factor 1. Note: Figurative constants cannot be used in the factor 1, factor 2, or result fields. No overlapping in a data structure is allowed for factor 1 and the result field, or factor 2 and the result field. In the string operations, factor 1 and factor 2 may have two parts. If both parts are specified, they must be separated by a colon. This option applies to all but the CAT, CHECK, CHECKR, and SUBST operations (where it applies only to factor 2). If you specify P as the operation extender for the CAT, SUBST, or XLATE operations, the result field is padded from the right with blanks after the operation. See each operation for a more detailed explanation. When using string operations on graphic fields, all data in factor 1, factor 2, and the result field must be graphic. When numeric values are specified for length, start position, and number of blanks for graphic characters, the values represent double byte characters. When using string operations on UCS-2 fields, all data in factor 1, factor 2, and the result field must be UCS-2. When numeric values are specified for length, start position, and number of blanks for UCS-2 characters, the values represent double byte characters. When using string operations on the graphic part of mixed-mode character data, the start position, length and number of blanks represent single byte characters. Preserving data integrity is the user's responsibility.
6-43
DOU (Do Until) on page 6-180 or DOUxx DOU (Do Until) on page 6-180 (Do Until) on page 6-180 DOW (Do While) on page 6-182 or DOWxx (Do While) on page 6-183 DOW (Do While) on page 6-182
ELSE (Else) on page 6-188 ELSEIF (Else If) on page 6-189 ENDyy (End a Structured Group) on page 6-189 FOR (For) on page 6-206 IF (If) on page 6-210 or IFxx (If) on page IF (If) on page 6-210 6-211 ITER (Iterate) on page 6-214 LEAVE (Leave a Do/For Group) on page 6-218 ORxx (Or) on page 6-262 OR operator
OTHER (Otherwise Select) on page 6-263 SELECT (Begin a Select Group) on page 6-294 WHEN (When True Then Select) on page 6-324 or WHENxx (When True Then Select) on page 6-325 WHEN (When True Then Select) on page 6-324
The DO operation allows the processing of a group of calculations zero or more times starting with the value in factor 1, incrementing each time by a value on the associated ENDDO operation until the limit specified in factor 2 is reached. The DOU and DOUxx (Do Until) operations allow the processing of a group of calculations one or more times. The end of a Do-Until operation is indicated by an ENDDO operation. The DOW and DOWxx (Do While) operations allow the processing of a group of calculations zero or more times. The end of a Do-While operation is indicated by an ENDDO operation. The FOR operation allows the repetitive processing of a group of calculations. A starting value is assigned to the index name. Increment and limit values can be specified, as well. Starting, increment, and limit values can be free-form expressions. An ENDFOR operation indicates the end of the FOR group. The LEAVE operation interrupts control flow prematurely and transfers control to the statement following the ENDDO or ENDFOR operation of an iterative structured group. The ITER operation causes the next loop iteration to occur immediately. The IF and IFxx operations allow the processing of a group of calculations if a specified condition is satisfied. The ELSE operation allows you to specify a group of calculations to be processed if the condition is not satisfied. The ELSEIF operation is a combination of an ELSE operation and an IF operation. The end of an IF or IFxx group is indicated by ENDIF.
6-44
A DO, DOUxx, DOWxx, FOR, IFxx, MONITOR, or SELECT operation (with or without ANDxx or ORxx operations), and an ENDyy operation, delimit a structured group. The ENDDO operation ends each DO, DOUxx, and DOWxx group or causes the structured group to be reprocessed until the specified ending conditions are met. The ENDFOR operation ends each FOR group. The SELECT must end with an ENDSL. An IFxx operation and an IFxx operation with an ELSE operation must end with an ENDIF operation. The rules for making the comparison on the ANDxx, DOUxx, DOWxx, IFxx, ORxx and WHENxx operation codes are the same as those given under Compare Operations on page 6-23. In the ANDxx, DOUxx, DOWxx, IFxx, ORxx, and WHENxx operations, xx can be: xx GT LT EQ NE GE LE Meaning Factor 1 is greater than factor 2. Factor 1 is less than factor 2. Factor 1 is equal to factor 2. Factor 1 is not equal to factor 2. Factor 1 is greater than or equal to factor 2. Factor 1 is less than or equal to factor 2.
In the ENDyy operation, yy can be: yy CS Meaning End for CASxx operation.
Operations, Expressions, and Functions
6-45
End for DO, DOUxx, and DOWxx operation. End for FOR operation. End for IFxx operation. End for SELECT operation.
Remember the following when specifying structured groups: v Each nested structured group must be completely contained within the outer level structured group. v Each structured group must contain one of a DO, DOUxx, DOWxx, FOR, IFxx, or SELECT operation and its associated ENDyy operation. v A structured group can be contained in detail, total, or subroutine calculations, but it cannot be split among them. v Branching into a structured group from outside the structured group may cause undesirable results.
Subroutine Operations
The subroutine operations are: v BEGSR (Beginning of Subroutine) on page 6-145 v ENDSR (End of Subroutine) on page 6-190 v EXSR (Invoke Subroutine) on page 6-203 v LEAVESR (Leave a Subroutine) on page 6-219 v CASxx (Conditionally Invoke Subroutine) on page 6-156 (traditional syntax only) All of these operations except CASxx are available in both the traditional syntax and free-form syntax. A subroutine is a group of calculation specifications in a program that can be processed several times in that program. Subroutine specifications must follow all other calculation operations that can be processed for a procedure; however, the PLIST, PARM, KLIST, KFLD, and DEFINE operations may be specified between an ENDSR operation (the end of one subroutine) and a BEGSR operation (the beginning of another subroutine) or after all subroutines. A subroutine can be called using an EXSR or CASxx operation anywhere in the calculation specifications. Subroutine lines can be identified by SR in positions 7 and 8. The only valid entries in positions 7 and 8 of a subroutine line are SR, AN, OR, or blanks.
6-46
Subroutine Operations
Coding Subroutines
An RPG IV subroutine can be processed from any point in the calculation operations. All RPG IV operations can be processed within a subroutine, and these operations can be conditioned by any valid indicators in positions 9 through 11. SR or blanks can appear in positions 7 and 8. Control level indicators (L1 through L9) cannot be used in these positions. However, AND/OR lines within the subroutine can be indicated in positions 7 and 8. Fields used in a subroutine can be defined either in the subroutine or in the rest of the procedure. In either instance, the fields can be used by both the body of the procedure and the subroutine. A subroutine cannot contain another subroutine. One subroutine can call another subroutine; that is, a subroutine can contain an EXSR or CASxx. However, an EXSR or CASxx specification within a subroutine cannot directly call itself. Indirect calls to itself through another subroutine should not be performed, because unpredictable results will occur. Use the GOTO and TAG operation codes if you want to branch to another point within the same subroutine. Subroutines do not have to be specified in the order they are used. Each subroutine must have a unique symbolic name and must contain a BEGSR and an ENDSR statement. The use of the GOTO (branching) operation is allowed within a subroutine. GOTO can specify the label on the ENDSR operation associated with that subroutine; it cannot specify the name of a BEGSR operation. A GOTO cannot be issued to a TAG or ENDSR within a subroutine unless the GOTO is in the same subroutine as the TAG or ENDSR. You can use the LEAVESR operation to exit a subroutine from any point within the subroutine. Control passes to the ENDSR operation for the subroutine. Use LEAVESR only from within a subroutine. A GOTO within a subroutine in the cycle-main procedure can be issued to a TAG within the same subroutine, detail calculations or total calculations. A GOTO within a subroutine in a subprocedure can be issued to a TAG within the same subroutine, or within the body of the subprocedure.
6-47
Subroutine Operations
Subroutine Coding Examples:
*...1....+....2....+....3....+....4....+....5....+....6....+....7...+.... CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq.... * * For a subroutine, positions 7 and 8 can be blank or contain SR. * C : C : C EXSR SUBRTB C : C : C : CL2 EXSR SUBRTA C : C : C : C SUBRTA BEGSR C : C : C : * * One subroutine can call another subroutine. * C EXSR SUBRTC C : C : C : C ENDSR C SUBRTB BEGSR C : C : C : * *...1....+....2....+....3....+....4....+....5....+....6....+....7...+.... CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq.... * * GOTO and TAG operations can be used within a subroutine. * C START TAG C : C : C : C 23 GOTO END C : C : C : C 24 GOTO START C END ENDSR C SUBRTC BEGSR C : C : C : C ENDSR * Figure 6-15. Examples of Coding Subroutines
Test Operations
The test operations are: v TEST (Test Date/Time/Timestamp) on page 6-314 v TESTB (Test Bit) on page 6-316 v TESTN (Test Numeric) on page 6-318
6-48
Test Operations
v TESTZ (Test Zone) on page 6-319. TEST is available in both the traditional syntax and free-form syntax. The other operations are available only in the traditional syntax. See Figure 6-27 on page 6-70 for an example of how %BITAND can be used to duplicate the function of TESTB. The TESTx operations allow you to test fields specified in the result field. TEST tests for valid date, time, or timestamp data. TESTB tests the bit pattern of a result field. TESTN tests if the character field specified in the result field contain all numbers, or numbers with leading blanks, or all blanks. TESTZ tests the zone portion of the leftmost character of a character field specified in the result field. The result of these operations is indicated by the resulting indicators.
XML Operations
The XML operations include SAX parsing and reading an XML document directly into a variable. The XML operations are: v XML-SAX (Parse an XML Document) on page 6-363 v XML-INTO (Parse an XML Document into a Variable) on page 6-330 v %XML (xmlDocument {:options}) on page 6-139 v %HANDLER (handlingProcedure : communicationArea ) on page 6-93 The %HANDLER and %XML built-in functions are special built-in functions that do not return a value. They can be used only with the XML operation codes XML-SAX and XML-INTO. XML-SAX initiates a SAX parse that repeatedly calls your SAX-handling procedure to handle events. XML-INTO copies the information in an XML document into a program variable. For XML documents with many repeated XML elements, it can be used to handle a limited number of XML elements at a time, having the elements passed to your XML-INTO handling procedure. For more information about processing XML documents in your RPG programs, see Rational Development Studio for i: ILE RPG Programmer's Guide.
Expressions
Expressions are a way to express program logic using free-form syntax. They can be used to write program statements in a more readable or concise manner than fixed-form statements. An expression is simply a group of operands and operations. For example, the following are valid expressions:
A+B*21 STRINGA + STRINGB D = %ELEM(ARRAYNAME) *IN01 OR (BALANCE > LIMIT) SUM + TOTAL(ARRAY:%ELEM(ARRAY)) The tax rate is + %editc(tax : A) + %.
Expressions may be coded in the following statements: v v v v v CALLP (Call a Prototyped Procedure or Program) on page 6-152 CHAIN (Random Retrieval from a File) on page 6-159 (fr