RPG Basics Module 1 2007 IBM Corporation Agenda

RPG Basics Module 1 © 2007 IBM Corporation

Agenda This module consists of: § § § § Introduction Coding RPG Structured Operation Codes Indicators and Built-in-Functions (BIFs) Basic File Handling in RPG More Features and Screen Handling More File Handling Legacy RPG © 2007 IBM Corporation

Course Prerequisites Before starting the course, the student should have at least a basic knowledge of: § § Relational Database System i Fundamentals (Objects, Libraries, Library Lists, etc. ) Programming Environment (WDSC) An understanding of basic program structure (loops, subroutines etc. ) © 2007 IBM Corporation

The RPG Manuals and other Books Two RPG Manuals in the Information Center: § ILE RPG Reference § ILE RPG Programmers Guide ILE RPG Reference available as online help in WDSC The RPG Redbook § "Who Knew You Could Do That With RPG IV? A Sorcerer's Guide to System Access and More" (SG 24 -5402) § Go to http: //www. redbooks. ibm. com/ Who Knew You Could Do That with RPG IV? A Sorcerer's Guide to System Access and More SG 24 -5402 International Technical Support Organization Rochester, Minnesota © 2007 IBM Corporation

Introduction © 2007 IBM Corporation

Report Program Generator (RPG) RPG IV is § a high level, structured language § evolved over a number of years Many parts of RPG are no longer commonly used § e. g. the RPG Cycle § has evolved to a "structured" language There are many flavors of RPG § in "real life" you will find programs whose original structure (and coding) date back to the inception of RPG! © 2007 IBM Corporation

A Brief History RPG – 1960 s (System/360 mainframes) § High Level Language, Fixed-Logic Cycle, Indicators, Batch Oriented, Card based machines § Still in use today! RPG II (System/3, System/32, System/34, System/36) § Interactive applications - Disk processing support, Workstation support RPG III (System 38) § Structured program design for efficiency § DBMS grew in sophistication RPG/400 (AS/400) § RPG/400 is RPG III on the System i family (i. e. AS/400. i. Series, i 5) § Enhancements - New operation codes, Named constants, Initialization subroutines § Embedded SQL statements © 2007 IBM Corporation

RPG IV § § First available with OS/400 V 3 R 1 in 1994 Component of ILE RPG/400 Program Product Expanded or eliminated many RPG III language limits Fulfilled many long-standing requirements - Longer field names - Free form expressions - Date/time calculations § Positioned for future growth § Participates in Integrated Language Environment (ILE) ILE § First available with V 2 R 3 § Greater modularity § Better performance © 2007 IBM Corporation

Standard Representation of an RPG Program Data Storage I/O Buffers Instruction Set © 2007 IBM Corporation

Standard Representation of an RPG Program Data Storage: § Contains all data used by the program Instruction Set: § Sequence, logic, manipulation of data storage File Buffers: § I/O to and from the program © 2007 IBM Corporation

Coding and Compiling a Program CRTBNDRPG Editor MYPGM Member Type RPGLE QRPGLESRC *FILE (PF-SRC) © 2007 IBM Corporation MYPGM *PGM

Hello World The ubiquitous “Hello World”. § A very simple program § Uses Free Form RPG Basic Rules for Free Form § § § Starts with /Free in position 7 of a line Ends with /End-Free in position 7 of a line All statements must be coded within positions 8 to 80 A statement must end with a semi-colon (; ) A statement may be on multiple lines . . . . 1. . . . 2. . . . 3. . . . 4. . . . 5 /Free Dsply 'Hello World'; *In. LR = *On; /End-Free © 2007 IBM Corporation

Coding in RPG © 2007 IBM Corporation

Program Development Cycle The program development cycle is the same for all languages § § § Define the problem Design the solution Design and Code the program Compile, Test and debug the program Document the program Maintain the program © 2007 IBM Corporation

RPG Code RPG specifications stem from punched cards § i. e. each line was 80 characters long First five characters were for a sequence number § No longer used § May be used as required - e. g. to identify modified lines Sixth position contains a “specification” identifier § Identifies the type of RPG line being entered § Defines how the rest of the line is interpreted § Not used in /Free style RPG Code may be entered in "mixed" case § Traditional RPG was upper case only § But code and variable names are not case sensitive - e. g. Field. Name = fieldname = FIELDNAME In 2001, RPG Calculation specifications became "free format“ § But most existing code still has the traditional columnar look and feel © 2007 IBM Corporation

RPG Specification Types The specification types are: § H(eader) Compiler directives and execution information. § F(ile) Declares files used in the program. § D(efinition) Defines data items used in the program. - Arrays, tables, data structures, subfields, constants, standalone fields, procedure interfaces, and prototypes. § I(nput) Input record layouts. (Rarely, if ever, used today) § C(alculation) What the program does! - Fixed Form - Extended Factor 2 - Free Form § O(utput) Declares output record layouts. (Rarely, if ever, used). § P(rocedure) Marks the beginning and end of a subprocedure. Specifications, when used, must be in the order above. § Except that D-specs and C-Specs are permitted within subprocedures Blank lines are permitted - so use them. © 2007 IBM Corporation

Flavors of RPG There are now three flavors of RPG program § Based on the way “calculation lines” are entered § Fixed Format - Traditional RPG. Everything in the correct column § Extended Factor 2 - More flexible than Fixed Format. Still requires some column positioning § Free Format - Most recent, so tends to appear mainly in new programs For the most part, on this course you will be using Free Format. . . CL 0 N 01 Factor 1+++++++Opcode(E)+Factor 2+++++++Result++++Len++D+Hi. Lo. Eq C b Add c a . . . CL 0 N 01 Factor 1+++++++Opcode(E)+Extended-factor 2+++++++++++++++ C Eval a = b + c; © 2007 IBM Corporation

Comments Comment lines may be placed anywhere in a program. § “Traditional” style - Identified by an * in position 7 - The rest of the line contains any required comments - Does not require a line identifier in position 6 – although often coded § “Modern” style - Comment may follow a double slash - Must be used in free format - Also used for end-of-line comments following the “; ” at the end of the line. . +. . . 1. . . +. . . 2. . . +. . . 3. . . +. . . 4. . . +. . . 5. . . +. . . 6. . . +. . . *--------------------------------* These are comments entered * using an asterisk * in position 7 of the line *--------------------------------// These are comments entered // using a double slash // anywhere on the line a = b + c; // This is a comment on a line with code © 2007 IBM Corporation

Program Variables and Basic Data Types Program Variable § Refers to a location in memory that can store data § RPG uses the term Field rather than variable Must have a name, length and data type § Fields are defined on D Specs - May also be externally defined (more later) - May also be defined on fixed form Calc specs (more later) All fields in RPG are fixed in length § Even Varying length character fields occupy a fixed amount of memory Type Description A Character (default) – Fixed and Varying Length S Zoned Decimal P Packed Numeric (default) I Integer U Unsigned Integer © 2007 IBM Corporation

Zoned and Packed Numbers Zoned – a digit is represented by a byte 0 1111 0000 F 0 5 1111 0101 F 5 1 1111 0001 F 1 6 1111 0110 F 6 2 1111 0010 F 2 7 1111 0111 F 7 3 1111 0011 F 3 8 1111 1000 F 8 4 1111 0100 F 4 9 1111 1001 F 9 § Half byte (high) of right most digit indicates sign (D is negative) 12345 F F F 12345 - F F D 1 2 3 4 5 Packed – a digit is represented by a half byte (nibble) § Low order (right most) nibble of right most digit indicates sign 12345 1 3 5 12345 - 2 4 F 1 3 5 2 4 D © 2007 IBM Corporation

Integers RPG Bytes Range 3 I 0 1 -128 to 127 5 I 0 2 -32, 768 to 32, 767 10 I 0 4 -2, 147, 483, 648 to 2, 147, 483, 647 20 I 0 8 -9, 223, 372, 036, 854, 775, 807 to 9, 223, 372, 036, 854, 775, 807 3 U 0 1 0 to 256 5 U 0 2 0 to 65535 10 U 0 4 0 to 4, 294, 967, 295 20 U 0 8 0 to 18, 446, 744, 073, 709, 551, 615 © 2007 IBM Corporation

D Spec (Definition) D spec entries are “column specific” § With the exception of the keyword area D Specs are used to define fields § Also used to define other items (more later) Name § The name of the field. § It is recommended that you leave a space between the D (specification) and the beginning of the name. Type of Definition (Ds) § S for Stand Alone Field Length (To/L), Internal Data Type (I) and Decimal Positions (Dc) § The From entry is rarely used in modern RPG programs Keywords DName++++++ETDs. From+++To/L+++IDc. Keywords+++++++++++++ © 2007 IBM Corporation

D Spec (Definition) To define a standalone field, enter § § Field name Definition type of S Length of field (number of characters or digits) Internal data type (blank, A, P, S, I, U) - Defaults to A if Decimal Positions is blank - Defaults to P If Decimal Positions is entered § Decimal positions - Positions are implicit . . . DName++++++ETDs. From+++To/L+++IDc. Keywords++++++++++ D Character S 30 A D Character. Dft S 20 D Packed S 9 P 0 D Packed. Dft S 11 2 D Integer S 10 I 0 D Unsigned. Int S 5 U 0 © 2007 IBM Corporation

D Spec (Definition) Long Names § Continue the name along the line and end with an ellipse (…) § Continue the name on the next line Basic Keywords § INZ (Initialize) allows you to specify an initial value for a field § LIKE allows you to define a field whose length and type are the same as ("like“) another field’s. § There are many more keywords that we will meet later DName++++++ETDs. From+++To/L+++IDc. Keywords++++++. . . D This. Is. AField. With. AVery. . . D Long. Name S 20 D Count S 5 I 0 Inz(1) D Count. B S Like(Count) © 2007 IBM Corporation

Names Uniquely identify specific entities in a program or procedure § Fields, Arrays, Key Field Lists, Named Constants, Parameter Lists, Data Structures, Subroutines, Subprocedures et al. Naming rules: § First character must be alphabetic (including $, #, and @) - Use of special characters not recommended § § § Remaining characters must be alphabetic, numeric or underscore (_) The name can be from 1 to 4096 characters External names can be from 1 to 10 (a restriction of DDS) Names must be unique Must not be a reserved word - It is not hard to avoid these in RPG, there are very few - While not technically reserved words, it is good to avoid field names that are operation codes © 2007 IBM Corporation

Literals are used to specify an actual value Character § Enclose the contents in single apostrophes - Or as a hex literal e. g. X’F 1’ § Can be repeated by prefixing with *ALL - E. g. *ALL’ABC’ Numeric § Must not be enclosed in apostrophes § May include digits 0 thru 9 § May include a decimal point and/or sign. - The sign must be the left most character of the literal § May not contain commas, currency signs or percent sign © 2007 IBM Corporation

Simple Arithmetic Expressions (1 of 3) Set the value of a numeric field equal to the result of a numeric expression Based on an EVAL operation § The actual EVAL op-code is optional unless an extender such as halfadjust is in use Extender of H (half adjust) required for rounding § There are other extenders which will be covered in later units D D a b c d S S a = b + c; a = b + d; Eval(H) a = b + d; 7 7 5 I 5 2 5 Inz(1. 79766) 0 Inz(750) 3 Inz(2. 101) // a = 751. 79 // a = 3. 89 // a = 3. 90 © 2007 IBM Corporation

Simple Arithmetic Expressions (2 of 3) Arithmetic Expression Rules § Operands and result field must be numeric § Operators may be + (add), - (subtract), * (multiply), / (divide) or ** (exponentiation) § Parentheses should be used to - ensure components are calculated in the correct sequence - Ensure accurate results - Remove ambiguity from an expression § Numeric overflow or division by zero will cause a run time error - Result fields must be large enough to hold the calculated result of the expression § Such errors can be trapped through the use of the MONITOR op-code which will be covered in later units Eval(H) Pay = (Rate*39) + ((Hours-39)*(Rate*1. 5)); © 2007 IBM Corporation

Simple Arithmetic Expressions (3 of 3) Components are calculated in the following sequence § § Parentheses Exponentiation Multiply and Divide Add and Subtract In this example, what is the value of Result? D D D x y a b c Result /Free Result = a + b S S S 5 I 5 I 5 I 0 0 0 * c ** (x*y); © 2007 IBM Corporation Inz(1) Inz(2) Inz(3) Inz(4) Inz(5)

Simple Character Expressions (1 of 2) Set the value of a character field equal to the result of a character expression Based on an EVAL or an EVALR operation § § EVAL is assumed if no op-code is coded EVAL means the result of the expression will be left justified EVALR means the result of the expression will be right justified The “+” operator is used for concatenation D D Phone. No S 13 Area. Code S 3 Inz('1') Exchange S 3 Inz('234') Suffix S 4 Inz('5678') /Free Phone. No = '(' + Area. Code + ') ' + Exchange + '-' + Suffix; // Phone. No = (1 ) 234 -5678 © 2007 IBM Corporation

Simple Character Expressions (2 of 2) Character Expression Rules § Operands and result field must be character § Operator may be + (concatenate) § Result field may be smaller than result of expression - Result is justified depending on use of EVAL or EVALR § If result field is larger it will be padded with leading (EVALR) or trailing (EVAL) blanks D Small S 6 D Char 1 S 4 D Char 2 S 4 /Free Small = Char 1 + Char 2; // Small = 'AAAABB' Eval. R Small = Char 1 + Char 2; // Small = 'AABBBB' © 2007 IBM Corporation Inz('AAAA') Inz('BBBB')

The DSPLY Operation DSPLY { message { output-option { response} } } § Can display up to 52 characters of text - This limit includes the length of any response field involved - Can display character or numeric field or literal ¨ But numeric display is primitive § Allows for the entry of a single response field - May be character or numeric - If a response is used specify a single space (‘ ‘) as the output option § Very useful when starting to program in RPG § Very useful when writing “test” programs D Entered D Over /Free Dsply S S 10 10 Inz('All Done!') 'This is some text'; 'Enter a value: ' ' ' Entered; ('You Entered ' + Entered); Over; © 2007 IBM Corporation

Indicators Logical switches or Boolean fields § on/off, true/false § set to indicate a condition RPG has built-in indicators § 01 -99 - General Purpose RPG Indicators - Referenced as *IN 01 or *IN(01) § LR - Last Record - Used to specify that the program is to close all files etc. on return to its caller § There are others, however their use is not covered in this unit. You can define your own indicators - with meaningful names § RPG IV is far less dependent on built-in indicators § You should avoid using the built in indicators - But they are used extensively in legacy applications - You will need to know how to use the built in indicators – more later © 2007 IBM Corporation

Exiting a Program A program exits § When a RETURN operation is used § When the end of the Mainline is reached and the LR indicator is on - It is irrelevant where in the logic the LR indicator was set on Recommendation: Always end your mainline with a RETURN operation § This prevents you from inadvertently using the RPG Cycle *In. LR = *On; Return; © 2007 IBM Corporation

Structured Operation Codes © 2007 IBM Corporation

Structured Operation Codes RPG supports the standard structured operation codes. § § IF/ELSEIF FOR DOW (Do While) DOU (Do Until) Condition code Loop a number of times Loop while a condition is true Loop until a condition is true Plus a form of case statement § SELECT/WHEN/OTHER Every structured op-code must have a corresponding END § ENDIF, ENDFOR, ENDDO, ENDSL - A simple END operation may be used but is not advisable © 2007 IBM Corporation

IF, ELSEIF Causes a group of statements to be executed if a conditional expression is true. § The logical expression uses standard relational operators - = (equal), > (greater then), < (less then), >= (greater then or equal to). <= (less then or equal to), NOT (negate), OR/ AND - Parentheses may be used for precedence If a <= b; Dsply 'The condition is true'; End. If; If ((a = b) and (c = d)) OR (a > c); Dsply 'The condition is true'; End. If; If x = y; Dsply ‘x and y are the same’; Else. If x > y; Dsply ‘x is bigger than y’; Else; Dsply ‘x is smaller than y’; End. If; © 2007 IBM Corporation

Nested IFs IF groups may be nested one within another § Each IF requires an ENDIF. If a <= b; Dsply 'The first condition is true'; If c = d; Dsply 'The secondition is true'; Else; Dsply 'The secondition is true'; End. If © 2007 IBM Corporation

FOR index { = start-value } { BY increment } { TO|DOWNTO limit } • Processes a group of operations a number of times For x = 1 to 10; Dsply x; End. For; For x = 1 by 2 to 10; Dsply x; End. For; For x = Start By Step To Until; Dsply x; End. For; For x = 10 Down. To 1; Dsply x; End. For; © 2007 IBM Corporation

DOW (Do While) Processes a group of statements while a conditional expression is true § Code within the loop must cause the conditional expression to be false or the loop will never end x = 5; Do. W x > 0; Dsply x; x = x – 1; End. Do; x = 0; Do. W x > 0; Dsply x; x = x – 1; End. Do; © 2007 IBM Corporation

DOU (Do Until) Processes a group of statements until a conditional expression is true § Code within the loop must cause the conditional expression to be false or the loop will never end Unlike a DOW, a DOU group is always executed at least once x = 5; Do. U x = 0; Dsply x; x = x – 1; End. Do; x = 0; Do. U x <= 0; Dsply x; x = x – 1; End. Do; © 2007 IBM Corporation

ITER (Iterate) and LEAVE ITER (Iterate) transfers control to the END statement § The conditional expression for the loop is re-tested LEAVE transfers control to the statement following the END statement. Do. W x > 0; If x = y; Iter; End. If; If x = z; Leave; End. If; End. Do; © 2007 IBM Corporation

Indicators and Built-In-Functions (BIFs) © 2007 IBM Corporation

Defining and Setting Indicators may be defined on D Specs § Data type is N § You do not need to specify a length - But it must be 1 if specified Indicators are true or false § May use figurative constants *ON and *OFF § May use character literals '1' and '0' D Bad. Rate S /Free If Rate < 0; Bad. Rate = *On; Else; Bad. Rate = *Off End. If; N © 2007 IBM Corporation

Using Indicators Can be set by assigning the result of a logical expression § Since a logical expression is true (*On) or false (*Off) No need to specify a test value when testing an indicator § Since an indicator is true or false Use the NOT operator to test for an indicator being false D Bad. Rate S /Free Bad. Rate = (Rate < 0); N If Bad. Rate; Dsply 'The rate is negative'; End. If; If Not Bad. Rate; Dsply 'The rate is positive'; End. If; © 2007 IBM Corporation

RPG’s Built-In Indicators Used extensively in legacy applications § Dependent on comments or standards to know what they mean The built-in indicators can be referred to as fields § The compiler maintains 99 one byte alpha fields which exactly reflect the settings of the 99 general purpose indicators. § They are called *IN 01 to *IN 99. § The field contains a "1" for On and a '0' for Off. § There is also a compiler maintained array of 99 elements called *IN which fulfils the same function. e. g. Indicator 55 is *IN(55) *In 30 = *In 31 or *In 32; If Not *In 30; *In 51 = *On; *In 52 = *Off; End. If; © 2007 IBM Corporation

Built-In Functions (BIFs) BIFs are one of the most versatile features of RPG § As of V 5 R 4 there are 70 BIFs available BIFs are commonly used in expressions § They return a value § BIFs may also be used in other places - Such as with keywords on the D specs We will cover some of the more commonly used in the next few charts © 2007 IBM Corporation

%TRIM – Trim Blanks %TRIM( string ) %TRIML( string ) %TRIMR( string ) § %TRIM strips leading and trailing blanks from character fields § %TRIML strips leading blanks only § %TRIMR strips trailing blanks only D First. Name S D Last. Name S D Print. Name S 15 15 25 Inz('Paul') Inz('Tuohy') Print. Name = First. Name + Last. Name; // Print. Name = 'Paul Tuohy ' Print. Name = %Trim. R(First. Name) + ' ' + Last. Name; // Print. Name = 'Paul Tuohy ' © 2007 IBM Corporation

%SCAN – Search for Character String %SCAN( needle : haystack { : start } ) § Returns the position of the first occurrence of the string needle in string haystack starting the search at position start - The optional start parameter is useful when searching a string which may contain multiple instances of the target string § Returns zero (0) if no match was found D Inp. String D Position 20 3 Inz('Dr. Doolittle') 0 Position = %Scan('tt‘ : Inp. String); // Position = 10 Position = %Scan('D‘ : Inp. String : 2); // Position = 5 © 2007 IBM Corporation

%SUBST – Return or Set Substring %SUBST( basestring : start { : length } ) § Returns the substring of the basestring - If optional length not specified, the rest of the string from the start to the end of the string is returned § %SUBST can also be used when specifying the result field - i. e. To control which part of the field is to be changed D D Name. Field First. Name Last. Name x S S 20 INZ ('Paul Tuohy 10 10 5 I 0 x = %Scan(' ' : Name. Field); First. Name = %Sub. St(Name. Field : 1 : x-1); // First. Name = 'Paul ' Last. Name = %Sub. St(Name. Field : X+1); // Last. Name = 'Tuohy ' %Sub. St(Name. Field : X+1 : 4) = 'Huth' // Name. Field = 'Paul Huthy ' © 2007 IBM Corporation ')

Putting it All Together Combining %TRIM, %SUBST, %SCAN § Second example combines the operations into a single statement but is more difficult to read D Name D Reverse D x S S S 20 INZ ('Paul Tuohy 20 5 I 0 ') x = %SCAN(' ' : Name); Reverse = %Trim. R(%Subst(Name : x+1)) + ', ' + %SUBST(Name : 1 : x-1); // Reverse = 'Tuohy, Paul ' Reverse = %Trim. R(%SUBST(Name : %Scan(' ' : Name) + 1) ) + ', ' + %SUBST(Name: 1 : %Scan(' ' : Name)- 1); © 2007 IBM Corporation

Numeric Conversion and Editing BIFs %CHAR is the most basic editing BIF § It returns a character field containing the edited value of a numeric field or expression § Leading zeros are removed and a decimal point inserted if required § Negative values will be preceded by a minus sign %EDITC and %EDITW provide more sophisticated editing § They are based on the Edit codes (%EDITC) and Edit words (%EDITW) used when defining output on O-specs D Text S 50 a Text = 'Your balance of ' + %Char( Balance ) + ' is now seriously overdue‘; © 2007 IBM Corporation

Using Files in RPG © 2007 IBM Corporation

Terminology File (Database) Hierarchy § File (Table) - Collection of data about a given kind of entity or object - Set of data elements (values) that is organized using a model of horizontal rows and vertical columns. § Record (Row) - Represents a set of related data about one specific instance of the entity - Every record in the table has the same structure § Field (Column) - An element of data in the record. © 2007 IBM Corporation

Creating a File from DDS Format Access Path DDS Source QDDSSRC Access Path Data Logical File Physical File Formats CRTPF CRTLF CRTDSPF CRTPRTF Display File Formats Print File © 2007 IBM Corporation

Files in RPG An RPG program processes a *FILE object § § Opens a file Gets records from a file Puts records to a file Closes a file *FILE objects may be for § § disk (Physical - PF, or Logical - LF) display (DSPF) printer (PRTF) All of these are *FILE objects with a different attribute All *FILE objects may be defined using traditional Data Description Specifications (DDS) § SQL may also be used to define disk files Files are normally externally described for RPG programs © 2007 IBM Corporation

Data Description Specifications (DDS) DDS format is similar to RPG § It is a “fixed” form § Column Based DDS is divided into three levels: § File Level identifies information about the file - Introduced by blank Type (T) and Name entries § Record Level identifies information about a record format - Introduced by the “R” prior to the name § Field Level identifies information about a field. - Introduced by a blank Type (T) entry and a non-blank Name Keywords apply to the level where they appear. . . A. . T. Name++++++RLen++TDp. B. . . Functions+++++++++ A REF(FLDREF) File A R CUSTREC A CCODE TEXT('Customer Record') Record Field R © 2007 IBM Corporation

Data Description Specifications The meaning of the headings are: § Type of entry (T) - Record (R), Field (blank), Key (K) § Name. The name of the record, field, or key field § Reference field (R) - R if referencing another field (more later) § § Length (Len++). Length of the field Data Type (T). Data type of the field Decimal Positions (Dp). Decimal precision for a numeric field Usage (B). - Input (I), Output (O), Both (B – default for database files) § Functions. Used to supply keywords to refine the definition - The real strength of DDS A. . T. Name++++++RLen++TDp. B. . . Functions+++++++++ © 2007 IBM Corporation

DDS for a Physical File This is the DDS for a simple Physical File name EMPLOYEE § It defines a record format named EMPLOYEER § It defines the fields EMPID, NAME, BIRTH and JOINED - The TEXT, COLHDG and EDTWRD keywords do not affect the data - They are used to provide default headings etc. when the data is displayed . . . A. . T. Name++++++RLen++TDp. B. . . Functions+++++++++ A R EMPLOYEER A EMPID 5 0 TEXT('Employee Id. ') A COLHDG('Employee' ' Id. ') A NAME 25 COLHDG('Name') A BIRTH 8 0 TEXT('Date of Birth') A COLHDG('Date of' ' Birth') A EDTWRD(' 0 - - ') A JOINED 8 0 TEXT('Date Joined') A COLHDG(' Date' 'Joined') A EDTWRD(' 0 - - ') © 2007 IBM Corporation

DDS for Logical Files This is the DDS for a simple Logical File named EMPLOYEE 1 § This file is sequenced by the Employee Id (EMPID). . . A. . T. Name++++++. Len++TDp. B. . . Functions++++++ A R EMPLOYEER PFILE(EMPLOYEE) A K EMPID This is a more complex example named EMPLOYEE 2 § It is sequenced on Date of birth (BIRTH) and Employee Id (EMPID) § Only the fields EMPID, NAME and BIRTH are included. . . A. . T. Name++++++. Len++TDp. B. . . Functions++++ A R EMPLOYEER 2 PFILE(EMPLOYEE) A EMPID A NAME A BIRTH A K BIRTH DESCEND A K EMPID A S BIRTH COMP(GT 19800101) © 2007 IBM Corporation

DDS Keywords are essential to the use of DDS § Some keywords are common to all file types - e. g. TEXT, COLHDG § Some keywords may be used at all levels (File, Record and Field) - e. g. SPACEA, SPACEB § Some keywords are specific to file types - e. g. DSPATR for Display Files By externally defining a file, a program is protected from needing to know about device specific information For a complete description of the DDS coding rules and keywords, please refer to the Data Description Specification Reference manual. © 2007 IBM Corporation

Additional DDS columns for DSPF and PRTF Additional columns are used for Display and Print files § i. e. PRTF and DSPF Conditioning indicators § Control the inclusion of a field or keyword(s) Field Usage (B) § For Print files - Output (O – Default) § For Display files - Input (I), Output (O), Both (B), Hidden (H) Lin. § The line number Pos. § The column starting position . . . A. . T. Name++++++RLen++TDp. B. . . Functions+++++++++. . . AAN 01 N 02 N 03 T. Name++++++RLen++TDp. BLin. Pos. Functions+++++++++ © 2007 IBM Corporation

Example - DDS for a Print File (PRTF) Keywords specific to print files § SKIPx and SPACEx keywords control where the line is printed - x = B for Before printing and A for After printing Len entry supplies start position for fields and literals. . . AAN 01 N 02 N 03 T. Name++++++RLen++TDp. BLin. Pos. Functions+++++++++ A R HEAD SKIPB(3) A 100 DATE EDTCDE(Y) A 120 PAGNBR EDTCDE(Z) A SPACEA(1) A 1'A/c Code' A 10'Name' A 41'Address' A 85'Balance' A 95'Department' A 117'Classification' A R DETL SPACEB(2) A CCODE 6 2 © 2007 IBM Corporation

Example - DDS for a Display File (DSPF) Differences are: Keywords specific to DSPF § DSPSIZ and CA 03 Specification of both the row and column for a field or literal . . . AAN 01 N 02 N 03 T. Name++++++RLen++TDp. BLin. Pos. Functions+++++++++ A DSPSIZ(24 80 *DS 3) A CA 03(03 'Exit') A A A R FORMAT 1 CCODE 31 6 B 1 24'Maintain Customer Master' 3 3'Customer Code : ' 3 20 COLOR(RED) © 2007 IBM Corporation

Creating Files Create the DDS source Source members may be created/maintained using: § An editor § CODE Designer for Display and Print Files § One of the older design tools - Screen Design Aid (SDA) for Display Files - Report Layout Utility (RLU) for Print Files Then create the file object using the appropriate command § § § CRTPF for a Physical file CRTLF for a logical CRTDSPF for a Display file And CRTPRTF for a Print file There are many other CRTxxx commands for creating other file types © 2007 IBM Corporation

Field Reference File A Field Reference File is just another file § Contains one record format § Contains the definition of ALL fields in the application - Usually listed alphabetically § Never contains actual data - Although there is no rule that says you cannot use a conventional file as a Field Reference File Sometimes referred to as a Data Dictionary © 2007 IBM Corporation

DDS for a Physical File using a Field Reference File This is an alternative DDS definition for the EMPLOYEE file § In this version all columns are specified by referencing the master definitions in a file named FIELDREF § Note the R in the Reference column for the fields - It tells the DDS compiler to get the field definition from FIELDREF . . . A. . T. Name++++++RLen++TDp. B. . . Functions++++++ A REF(FIELDREF) A R EMPLOYEER A EMPID R A NAME R A BIRTH R A JOINED R © 2007 IBM Corporation

Field Reference Files and External Definitions Field Reference Physical Logical RPG Compiler Display Print © 2007 IBM Corporation

F Spec (File) (1 of 2) F Specs identify the files that will be used by the program § Each file requires an F spec. The main points to note are: § File Name - Note the 10 character restriction § File Type (I) - I = Input, O = Output, U = Update, C = Combined (WORKSTN Files only) § File Designation (P) - Blank = Output - F = Full Procedural (for Types I, U and C) - Other types not commonly used in modern RPG programming (see notes). . . FFilename++IPEASFRLen+LKLen+AIDevice+. Keywords+++++++++++ FCUSTMR 0 UF A E K DISK USROPN FREPORT O E PRINTER OFLIND(*IN 96) FSCREEN CF E WORKSTN © 2007 IBM Corporation

F Spec (File) (2 of 2) § Record Addition (A) - Disk Files Only - Must be specified as A if records are to be added to the file § Format (F) - Specify as E if file is Externally Described § Record Address Type (Heading A - just before the Device entry) - Disk Files Only - If left blank file will be read in physical - Specify K if Keyed access is to be used § Device - DISK, PRINTER, WORKSTN § Keywords - “Extend” the definition of how the file is used in the program. . . FFilename++IPEASFRLen+LKLen+AIDevice+. Keywords+++++++++++ FCUSTMR 0 UF A E K DISK USROPN FREPORT O E PRINTER OFLIND(*IN 96) FSCREEN CF E WORKSTN © 2007 IBM Corporation

External Definitions An RPG program requires an F spec for each file it will use The example below shows the F specs for four files § Each of these files is externally described Compiler will search the library list to locate the file § It then generates all required record formats and field definitions § We will see an example of the generated field definitions later . . . FFilename++IPEASFRLen+LKLen+AIDevice+. Keywords+++++++++++ FCust IF E K Disk FAddr IF E K Disk FList O E Printer Ofl. Ind(Over. Flow) © 2007 IBM Corporation

Compiler picks up the External Definition External definitions retrieved are shown in the compile listing 15 FCust IF E K Disk *------------------------------* RPG name External name * File name. . : CUST RPGIVLAB/CUST * Record format(s). . . : CUSTR *------------------------------16 FAddr IF E K Disk *------------------------------* RPG name External name * File name. . : ADDR RPGIVLAB/ADDR * Record format(s). . . : ADDRR *------------------------------17 FList O E Printer Ofl. Ind(Over. Flow) *-------------------------------* RPG name External name * File name. . : LIST RPGIVLAB/LIST * Record format(s). . . : HEAD * DETL * FOOTR © 2007 IBM Corporation

Example of automatically defined input fields For the file CUSTR the following fields are defined § § CUSNO is a 6 character field. CBAL is a 9 digit numeric field with 2 decimal positions CDEPT is a 3 character field. CCLAS is a 3 character field. 26=ICUSTR *--------------------------* RPG record format. . : CUSTR * External format. . . : CUSTR : RPGIVLAB/CUST * Format text. . . . : Customer Master *--------------------------27=I A 1 6 CCODE 28=I P 7 11 2 CBAL 29=I A 12 14 CDEPT 30=I A 15 17 CCLAS © 2007 IBM Corporation

LIKE Revisited The LIKE keyword simplifies the definition of work fields § A work field can be defined as being LIKE an Externally Defined field § If the external field’s definition changes, then on recompile, the work field will also be redefined D Last. Cust S Like(CCode) © 2007 IBM Corporation

"PUT" and "GET" Operations A program “PUTs” a record to a file A program “GETs” a record from a file All PUTs and GETs are record based § i. e. A program will PUT or GET a single record at a time There are many PUT operation codes § WRITE, UPDATE, DELETE, EXFMT, EXCEPT There are many GET operation codes § CHAIN, EXFMT, READE, READPE, READC Notice that EXFMT combines both a PUT and a GET § First it performs a WRITE to the display file § Then performs a READ once the user has provided input © 2007 IBM Corporation

A “PUT” Operation 1234 Paul 1234 Paul. Y Y Write Record; 1201 Mary. Y 1202 Fred. N 1203 Joan. N 1204 Mike. Y © 2007 IBM Corporation

A “GET” Operation 1234 Paul. Y 1201 Mary. Y 1202 Fred. N 1203 Joan. N 1204 Mike. Y 1234 Paul. Y Chain '1234' Record; © 2007 IBM Corporation

External Definitions for a “GET” On a “GET” operation to CUST § § Copy positions 1 to 6 to the CCODE field. Copy positions 7 to 11 to the CBAL field. Copy positions 12 to 14 to the CDEPT field Copy positions 15 to 17 to the CCLAS field 26=ICUSTR *--------------------------* RPG record format. . : CUSTR * External format. . . : CUSTR : RPGIVLAB/CUST * Format text. . . . : Customer Master *--------------------------27=I A 1 6 CCODE 28=I P 7 11 2 CBAL 29=I A 12 14 CDEPT 30=I A 15 17 CCLAS © 2007 IBM Corporation

CHAIN search-key file-or-record {data-structure} CHAIN randomly retrieves a record by key § K must have been specified for Record Address Type on the F spec Or by relative record number Use %FOUND( ) to determine whether a record was retrieved § %FOUND( ) must specify the file name - Even if a record format name was used on the CHAIN FCust IF E FDept IF E /Free Chain Key. Fld Cust; If %Found(Cust); Chain 25 Dept; End. If; K Disk © 2007 IBM Corporation

READ name {data-structure} READ reads the next record from a file § The name entry can specify a file or record format Use the %EOF( ) BIF to determine when end of file is reached § i. e. There are no more records to read Note the “K” entry on the F spec § This ensures that the file is processed in key sequence § Without it the file would be processed in physical sequence FCust IF E /Free Read Cust; If Not %EOF(Cust); // Process record End. If; K Disk © 2007 IBM Corporation

READ All Records Use a DOW loop to READ all records from a file § READ the first record from the file § DOW loop condition on Not %EOF § Last statement of loop reads next record FCust IF E /Free Read Cust; Do. W Not %EOF(Cust); // Process record Read Cust; End. Do; K Disk © 2007 IBM Corporation 1201 Mary. Y 1202 Fred. N 1203 Joan. N 1204 Mike. Y 1234 Paul. Y

WRITE name {data-structure} Writes a record of the specified format to the file WRITE is used to: § Add records to Disk files § Display formats on Workstation files § Print records on Printer files. For externally described files record format must be specified FReport O E /Free Write Detail; Printer Ofl. Ind(Over. Flow) © 2007 IBM Corporation

Page Overflow A means of determining when to print page headings § § A print file has an overflow line F spec keyword OFLIND associates an overflow indicator with the file Indicator is set when overflow line is passed Program logic must set off the overflow indicator FReport O E /Free. . . Write Detail; If Over. Flow; Write Header; Over. Flow = *Off; End. If; Printer Ofl. Ind(Over. Flow) © 2007 IBM Corporation

Screen Handling and Other Features © 2007 IBM Corporation

Conditioning and Resulting Indicators on Display and Print files are mapped to the built in indicators *IN 01 - *IN 99 § This is the default - you will see how to change this later Conditioning Indicators are set by the program § If indicator *IN 31 is set the message text will be displayed Resulting Indicators are returned to the programs § In this example indicator *IN 03 will be on if the user pressed F 3 . . . AAN 01 N 02 N 03 T. Name++++++RLen++TDp. BLin. Pos. Functions+++++++++ A CA 03(03 'Exit') A REF(CUST) * A R FORMAT 1 A 1 24'Maintain Customer Master' A 3 3'Customer Code : ' A CCODE R I 3 20 A 31 ERRMSG('Bad Customer Code') © 2007 IBM Corporation

Execute Format - EXFMT format-name Writes and then reads a screen format § The screen is displayed and the program waits for the operator § Screen will be returned when the Enter key is pressed - Will also be returned when an enabled function key is pressed § Must use a Record Format name § Available for Workstation files only . . . FFilename++IPEASFRLen+LKLen+AIDevice+. Keywords+++++++++++ FScreen CF E Work. Stn /Free Ex. Fmt Screen. Fmt; Do. W Not *In 03; // Process the screen Ex. Fmt Screen. Fmt; End. Do; © 2007 IBM Corporation

Response Keywords in DDS The Enter key is always enabled § Other function keys must be enabled specifically § In the example only Command Attention and Command Function keys are used Available function keys and their associated keywords are: § Command Attention (CAxx) xx = 01 - 24 - E. g. Function keys F 3 and F 12 in this example § Command Function (CFxx) xx = 01 – 24 - E. g. Function key F 4 in the example § § § Rollup and Rolldown Help Clear Print Home (ROLLUP/ROLLDOWN) (HELP) (CLEAR) (PRINT) (HOME) . . . AAN 01 N 02 N 03 T. Name++++++RLen++TDp. BLin. Pos. Functions+++++++++ A CA 03(03 'Exit') A CF 04(04 'Prompt') A CA 12(12 'Cancel') © 2007 IBM Corporation

Attribute Keywords in DDS Attribute Keywords condition the appearance of a field § DSPATR defines the display attributes of a field - Blinking, Column separator, High intensity, Non-display, Position cursor, Reverse image, Underline § DSPATR may also define input attributes of a field - Protect contents of field from input typing, Select by light pen § COLOR defines the color of a field - Green, White, Red, Turquoise, Yellow, Pink, Blue . . . AAN 01 N 02 N 03 T. Name++++++RLen++TDp. BLin. Pos. Functions+++++++++ A CCODE R I 3 20 A 31 DSPATR(BL PC) A 31 COLOR(RED) A 61 DSPATR(PR) © 2007 IBM Corporation

Displaying Error Messages ERRMSG § Displays the text provided to the user ERRMSGID § Displays the first level text of the specified message id from the specified message file § The preferred method since it allows common messages to be shared between display files Messages are displayed on the message line § By default this is line 24 . . . AAN 01 N 02 N 03 T. Name++++++RLen++TDp. BLin. Pos. Functions+++++++++ A 3 3'Customer Code : ' A CCODE R I 3 20 A 31 ERRMSG('A bad code, dude') A 32 ERRMSGID(USR 0001 RPG 4 MSGF) © 2007 IBM Corporation

Some Other Useful DDS Keywords Field validation may be specified: § CHECK, COMP, RANGE, VALUE Displays may appear in Windows: § WINDOW, WDWBORDER, RMVWDW, USRRSTDSP Online Help may be specified: § HLP* (A set of Help related keywords) Please refer to the DDS Reference manual for further details © 2007 IBM Corporation

H Spec (Header) The H specification is optional § It is completely free format, consisting of keywords Keywords control: § Run time options § Compile time options Every program should have Option(*Src. Stmt: *No. Debug. IO) H Debug Dat. Edit(*DMY/) Option(*Src. Stmt: *No. Debug. IO) © 2007 IBM Corporation

Reserved Names RPG reserves the use of certain names § Nearly all start with an '*‘ § But there a few exceptions Reserved date fields provide the job date § § § § UDATE UDAY UMONTH UYEAR *DATE *DAY *MONTH *YEAR Job Date( Year is YY ) Job Day Job Month Job Year( Year is YY ) Job Date( Year is YYYY ) Job Day Job Month Job Year( Year is YYYY ) All of these reserved date fields are numbers – NOT “real” dates © 2007 IBM Corporation

Reserved Names Figurative constants remove the necessity of creating "work constants. § § § *BLANK/*BLANKS *ZERO/*ZEROS *HIVAL *LOVAL *ALL‘xxx' All blanks All zeros Highest value Lowest value Repeated string ‘xxx’ - Can also be used with hex values e. g. *ALLX’ 00’ § *NULL Null Value (used only with pointers) § *ON § *OFF True ( for indicator ) False ( for indicator ) © 2007 IBM Corporation

Reserved Names Miscellaneous § *INnn § *IN( ) Corresponding Field names for indicators Corresponding array for indicators 01 to 99 § *START § *END Used to position at start of file Used to position at end of file RPG also has some reserved subroutine names § *INZSR § *PSSR Program Initialization Subroutine. Program Status Subroutine. © 2007 IBM Corporation

Compiler Directives Identified by a '/' in position 7, followed by the directive The most commonly used directives are: § /FREE and /END-FREE - Which you have already seen § /COPY and /INCLUDE - Two different ways of saying the same thing but … There also § § § § /DEFINE /UNDEFINE /IF /ELSE /ENDIF /EOF © 2007 IBM Corporation

/Copy and /Include Perhaps the most useful compiler directive Identifies a source member § The contents of which will be inserted at that point, at compile time § A standard H Spec is a good candidate for /COPY A Copy member may, in turn, contain other /COPY directives § Copy. Nest keyword on the H Spec can be used to control level of nesting Syntax: /COPY libraryname/filename, membername § Library name may be omitted – Library list is used § Filename can also be omitted – QRPGLESRC is assumed Alternatively an IFS file may be referenced § Path name can be relative or absolute – must be in quotes if name includes blanks D/COPY STANDARD (Syntax) /COPY Library/File, Member © 2007 IBM Corporation

More File Handling © 2007 IBM Corporation

F Spec - Keywords define further processing options for a file § You have already seen OFLIND Most refer to more "advanced" file handling techniques § E. g. Subfiles, Exception Error Handling, Commitment Control But some are worth examining… . . . FFilename++IPEASFRLen+LKLen+AIDevice+. Keywords+++++++++++ FScreen CF E Work. Stn SFile(Sub. Fil: RRN) FProd. Ms 0 F F UF E K DISK © 2007 IBM Corporation Rename(Prod. Ms: Upd. Fmt) Prefix(PM_) Commit(Some. Times) Inf. DS(DS 1 SDS) Inf. SR(*PSSR)

Prefix PREFIXes externally defined field names § Adds characters to start of externally defined field names - All externally defined fields from the file will have the prefix applied § Optionally removes characters at the start of externally defined field names Syntax: PREFIX( prefix-chars { : chars-to-remove } ) § prefix-chars can be any characters valid in an RPG name - Can also be a null string (i. e. two consecutive quotes) § chars-to-remove is the number of characters to strip from the beginning of the existing field name . . . FFilename++IPEASFRLen+LKLen+AIDevice+. Keywords+++++++++++ FCust IF E K Disk Prefix(I_) FDept UF E K Disk © 2007 IBM Corporation Prefix(M: 1)

Rename RENAMEs a record format in a file § May be required for SQL defined tables § Sometimes used for more "generic" code Syntax: RENAME( ext-format : int-format ) § Where ext-format is the name of the format in the file and int-format is the name by which you want to reference the format in the program . . . FFilename++IPEASFRLen+LKLen+AIDevice+. Keywords+++++++++++ FCust IF E K Disk Rename(Cust. R: Upd. Fmt) © 2007 IBM Corporation

Ignore and Include IGNORE and INCLUDE allow you to specify which externally defined record formats are to be used by the program § This can save on the number of record format level checks in an application. § In this example SCREENS contains the six record formats SCREEN 1, SCREEN 2, SCREEN 3, SCREEN 4, SCREEN 5 and SCREEN 6 § Both of these sets of F Specs would achieve the same result - In the first case by including only those formats that are required - In the second case by ignoring those that are not required . . . FFilename++IPEASFRLen+LKLen+AIDevice+. Keywords+++++++++++ FScreens CF E Work. Stn Include(Screen 1: F Screen 2: Screen 6) FScreens F F CF E Work. Stn Ignore(Screen 3: Screen 4: Screen 5) © 2007 IBM Corporation

File Handling - OPEN and CLOSE Files are usually opened automatically § This is one of the few parts of the RPG cycle that is still commonly used Use keyword USROPN to override this behaviour for a file § Indicates that the programmer will explicitly open and close the file § Can only be used with full procedural files OPEN operation opens the file § Requires the USROPN keyword on the F Spec for the file CLOSE operation can be used regardless of how file was opened § Using *ALL in place of file name closes all open files. . . FFilename++IPEASFRLen+LKLen+AIDevice+. Keywords+++++++++++ FCust IF E K Disk Usr. Opn /Free Open Cust; Close *ALL; © 2007 IBM Corporation

Multi Field Keys (1 of 2) This is the DDS for the file used in the following examples § The key (index) for a file may consist of more than one field - In this case the key consists of the fields CUSNO, PRODCD, and DATE The key structure must be reflected in the RPG program . . . A. . T. Name++++++RLen++TDp. B. . . Functions++++++++ * DDS for SALES file A REF(FLDREFF) A R SALESR TEXT('Sales Record') A PRODCD R A CUSNO R A DATE R A QTY R A VALUE R A A A K CUSNO K PRODCD K DATE © 2007 IBM Corporation

Multiple Key Fields (2 of 2) There are multiple ways to specify the key field(s) § These are applicable to all operations that specify keys - E. g. CHAIN, DELETE, READPE, SETGT, and SETLL The simplest approach is to simply specify the keys § List fields in parentheses § Delimited by a colon You can specify fewer keys than the file uses § Just list only those you want § You can of course only omit the low order keys § More on this technique in a moment Chain (Get. Cusno: Get. Product: Get. Invoice) Sales; Chain (Get. Cus. No: '0000001': Get. Invoice) Sales; Set. LL (Get. Cus. No) Sales; © 2007 IBM Corporation

Partial Keys RPG allows you to use Partial Keys to access a file § A Partial Key must be a subset of the actual key A file with a key of: § Customer Code, Product Code, and Invoice Number Allows keys of: § Customer Code, Product Code, Invoice Number § Customer Code, Product Code § Customer Code Particularly useful when processing records between limits § e. g. Process all records for a specific customer © 2007 IBM Corporation

File Positioning - SETLL and SETGT SETLL (Set Lower Limit) § Positions the file pointer at the first record that is greater than or equal to the requested key SETGT (Set Greater Than) § Positions the file pointer after the last record that is less than or equal to the requested key SETLL and SETGT simply position the file pointer § They do not retrieve any data § SETLL sets the %EQUAL and %EOF BIFs § SETGT sets the %EOF BIF Set. LL (Cusno: Prod. Cd) Sales; If %Equal(); Dsply ('The next record is a match'); End. If; Set. Gt (Cusno) Sales; © 2007 IBM Corporation

Other READ Operations In addition to the basic READ operation there are: READP (Read Prior) § Read the prior (or previous) record § %EOF( ) will be set if the beginning of the file is reached READE (Read Equal) § Read the next record with a record key that matches the requested key § If the next record does not have a matching key %EOF( ) is set REDPE (Read Prior Equal) § Read the prior record with a record key that matches the requested key § If the prior record’s key does not match %EOF( ) is set Read Sales; Read. P Sales; Read. E (Cusno: Prod. Cd) Sales; Red. PE (Cusno: Prod. Cd) Sales; © 2007 IBM Corporation

Read between limits This demonstrates the process of reading records between limits § The SALES file is keyed by Customer Code, Product Code and Invoice Number § You wish to process all records for the Customer identified by CUSNO § The SETLL positions the pointer at the first record for CUSNO § The READE loop reads all records for CUSNO Set. LL Cus. No Sales; Read. E Cusno Sales; Do. W Not %EOF(Sales); Dsply 'Just read a record'; Read. E Cus. No Sales; End. Do © 2007 IBM Corporation

Record Locking Record is locked whenever a file open for update is input § Other program cannot retrieve the record for update § But they can retrieve it for input Lock can be avoided by using an 'N' extender The lock on the record is released when § The program issues another “GET” operation to the file § A “PUT” operation is issued to the file § An UNLOCK operation is used on the file FCust UF A E /Free Chain Cusno Cust; Update Cust. R; K Disk // Record is locked // Lock is released Chain(N) Cusno Cust; Delete Cust. R; // Record is NOT locked // Error – no record locked Chain Cusno Cust; Un. Lock Cust; // Record is locked // Lock is released © 2007 IBM Corporation

File Handling - PUT operations WRITE can be used to: § Add a new record to a disk file § Display a format on a workstation file § Print a record format on a printer file UPDATE: § Updates the currently locked record DELETE: § Delete the currently locked record for a disk file § Can also be used as a combined CHAIN/DELETE FCust UF A E K Disk /Free Write Cust. R; Update Cust. R; Delete Cus. No Cust. R; © 2007 IBM Corporation

Legacy RPG © 2007 IBM Corporation

Legacy RPG Legacy applications have a combination of fixed format and extended Factor 2 C specs § § Mostly fixed format RPG originated in the days of punched cards. Hence the columns Can be difficult to read Takes some getting used to . . . CL 0 N 01 Factor 1+++++++Opcode(E)+Factor 2+++++++Result++++Len++D+Hi. Lo. Eq C Key. Add Chain Add. R 90 C Key. Dep Chain Dept 90 C Write Detl C C If Write Eval End. If *In 96 Head *In 96 = *Off C Read Cust © 2007 IBM Corporation

Fixed Format C Spec The Operation is performed using Factor 1 and Factor 2 and the result placed in the Result Field Level (L 0) and Conditioning Indicators (N 01) § Not used with modern structured code Factor 1 § Usually a field name or literal depending on the Operation Code (Op code) § Certain operation codes may have an extender in parentheses - This modifies or enhances the way in which the operation is performed. Factor 2 § Usually a Field name, File name, or Record Format name . . . CL 0 N 01 Factor 1+++++++Opcode++++Factor 2+++++++Result++++Len++D+Hi. Lo. Eq © 2007 IBM Corporation

Fixed Format C Spec (cont’d. ) Result Field § Usually a field or Data Structure name Result Field Length (Len) § Specified as number of characters or number of digits Number of Decimal Positions (D) in the Result § Must be specified when a numeric field is Resulting Indicators (Hi. Lo. Eq) § No longer required - Replaced by BIFs such as %EOF( ), %FOUND( ), etc. § Operation code dictates which indicators (Hi, Lo, Eq) are available § Operation code results in indicator being set on or off . . . CL 0 N 01 Factor 1+++++++Opcode++++Factor 2+++++++Result++++Len++D+Hi. Lo. Eq © 2007 IBM Corporation

Extended Factor 2 Calc Spec Hybrid step between Fixed Format and Free Format § Introduced for the first time with RPG IV Level (L 0) and Conditioning Indicators (N 01) § As for Fixed Format Factor 1 § Not used Operation Code § Must be one of the op-codes EVAL, EVALR, IF, FOR, DOW, DOU, WHEN Extended Factor 2 § Expression - may be extended across multiple lines - C is required in column 6 of continuation lines and all other columns prior to Extended factor 2 must be blank . . . CL 0 N 01 Factor 1+++++++Opcode(E)+Extended-factor 2+++++++++++++ © 2007 IBM Corporation

Fixed Format Arithmetic Operations The base arithmetic operations are: § ADD (add), SUB (subtract), MULT (multiply) and DIV (divide) § The operation is performed between the Factor 1 and Factor 2 fields and the result is placed in the Result Field § If numeric overflow occurs it is simply ignored. . . CL 0 N 01 Factor 1+++++++Opcode++++Factor 2+++++++Result++++Len++D+Hi. Lo. Eq C Value 1 Add Value 2 Total C 100 Add Value 2 Total C C C Value 1 Sub Sub Value 2 100 Value 2 Total C C Value 1 Mult(H) Mult Value 2 Total C C Value 1 Div(H) Div Value 2 Total © 2007 IBM Corporation

Extended Factor 2 Arithmetic Operations Compare the previous page to its Extended Factor 2 equivalent . . . CL 0 N 01 Factor 1+++++++Opcode++++Extended-factor 2+++++++++++++ C Eval Total = Value 1 + Value 2 C Eval Total = Value 2 + 100 C Eval Total = Total + Value 2 C C C Eval Total = Value 1 - Value 2 Total = Value 2 - 100 Total = Total - Value 2 C C Eval (H) Eval Total = Value 1 * Value 2 Total = Total * Value 2 C C Eval (H) Eval Total = Value 1 / Value 2 Total = Total / Value 2 © 2007 IBM Corporation

More complex Arithmetic Operations A payroll calculation. . . Note the temporary result fields (in RED). . . CL 0 N 01 Factor 1+++++++Opcode&Ext. Factor 2+++++++Result++++Len++D+Hi. Lo. Eq C Hours If. Le 39 C Rate Mult (H) Hours Pay C Else C Rate Mult (H) 39 Temp. Pay 11 2 C Hours Sub 40 OTHours 11 2 C Rate Mult 1. 5 OTRate 9 5 C OTRate Mult (H) OTHours Pay C Add Temp. Pay C Endif. . . CL 0 N 01 Factor 1+++++++Opcode&Ext. Extended-factor 2+++++++++++++ C If Hours <= 39 C Eval (H) Pay = Rate * Hours C Else C Eval (H) Pay = (Rate*39) + ((Hours-39)*(Rate*1. 5)) C End. If © 2007 IBM Corporation

More Arithmetic Operations (1 of 2) You also have: § Z-ADD § Z-SUB § SQRT Zero the result field and then add Factor 2 to it Zero the result field and then subtract Factor 2 from it Put the square root of Factor 2 in the Result Field All the above operations perform decimal alignment. . . CL 0 N 01 Factor 1+++++++Opcode++++Factor 2+++++++Result++++Len++D+Hi. Lo. Eq C Z-Add 50 Total C Z-Add Value 2 Total C Z-Sub Value 2 Total C SQRT Value 2 Total . . . CL 0 N 01 Factor 1+++++++Opcode&Ext. Extended-factor 2++++++++++ C Eval Total = 50 C Eval Total = Value 2 C Eval Total = 0 - Value 2 C Eval Total = Value 2**(1/2) © 2007 IBM Corporation

More Arithmetic Operations (2 of 2) MVR – Move Remainder § Move the remainder from the previous DIV operation to the Result field § The DIV operation must not have specified Half Adjust %REM( ) BIF § An alternative to MVR when the result of the division is not required . . . CL 0 N 01 Factor 1+++++++Opcode++++Factor 2+++++++Result++++Len++D+Hi. Lo. Eq C Value 1 Div 4 Total 1 2 0 C MVR Total 2 4 2 CL 0 N 01 Factor 1+++++++Opcode&Ext. Extended-factor 2++++++++++ C Eval Total 2 = %Rem(Value 1: 4) © 2007 IBM Corporation

MOVE Operations Used to move data from one field to another § MOVEL (Move Left) operation § MOVE (Move Right) operation Can also be used to convert data § From a numeric field to a character field § From a character field to a numeric field Operation ceases when the shorter operand is exhausted § Therefore residual data may remain in the Result field - This was the primary way to concatenate fields in older versions of RPG § Result field may be padded with blanks - Use an extender of P – e. g. MOVE(P) Modern alternatives are EVAL and EVALR § EVAL and EVALR are the equivalent moving with the P extender § But BIFs must be used to move data between character and numeric © 2007 IBM Corporation

MOVEL (Move Left) A left adjusted move from Factor 2 to the Result Field § In this example CHAR is a 5 character field If the Result field is longer than the source, residual data will remain in the result § Unless the Pad option (P extender) is used . . . CL 0 N 01 Factor 1+++++++Opcode++++Factor 2+++++++Result++++Len++D+Hi. Lo. Eq * CHAR will = 'ABCD ' C Move. L 'ABCD' Char * CHAR will = 'XYCD ' C Move. L 'XY' Char * CHAR will = 'ABC ' C Move. L(P) 'ABC' Char * CHAR will = 'ABCD ' C Eval Char = 'ABCD' * CHAR will = 'XYCD ' C Eval %Sub. St(Char: 1: 2) = 'XY' © 2007 IBM Corporation

MOVE (Move Right) A right adjusted move from Factor 2 to the Result Field § In this example CHAR is a 5 character field If the Result field is longer than the source, residual data will remain in the result § Unless the Pad option (P extender) is used . . . CL 0 N 01 Factor 1+++++++Opcode++++Factor 2+++++++Result++++Len++D+Hi. Lo. Eq * CHAR will = ' ABCD' C Move 'ABCD' Char * CHAR will = ' ABXY' C Move 'XY' Char * CHAR will = ' ABC' C Move(P) 'ABC' Char * CHAR will = ' ABCD' C Eval. R Char = 'ABCD' * CHAR will = ' XYCD' C Eval. R %Sub. St(Char: 4: 2) = ' ABXY ' © 2007 IBM Corporation

Move Numeric to Character Watch out for: § Decimal point is implicit § Negative numbers result in the character representation of the negative digit i. e. N is x'D 5' D Num. Fld 1 D Num. Fld 2 D Char. Fld 1 S S S 5 5 9 2 Inz(123. 45) 2 Inz(-123. 45) * Char. Fld 1 will be '12345 ' C Move. L(P) Num. Fld 1 * Char. Fld 1 will be ' 12345' C Move(P) Num. Fld 1 * Char. Fld 1 will be '1234 N ' C Move. L(P) Num. Fld 2 * Char. Fld 1 will be ' 1234 N' C Move(P) Num. Fld 2 © 2007 IBM Corporation Char. Fld 1

EVAL Numeric to Character Expressions require the use of a BIF to cast characters to numbers § The %CHAR( ) BIF is the easiest to use - But will remove leading blanks and so does not produce equivalent results to MOVE/MOVEL § %EDITC( ) with the edit code ‘X’ is the most commonly used - It retains the leading zeros § %EDITW( ) can also be used with an appropriate edit word D Num. Fld 1 D Num. Fld 2 D Char. Fld 1 S S S * Char. Fld 1 will be '123. 45 C Eval * Char. Fld 1 will be '-123. 45 C Eval 5 5 9 2 Inz(123. 45) 2 Inz(-123. 45) Inz('123456. 78') ' Char. Fld 1 = %Char(Num. Fld 1) ' Char. Fld 1 = %Char(Num. Fld 2) © 2007 IBM Corporation

Move Character to Numeric Watch out! § Can generate decimal data errors § Not the reverse of number to character – especially for negatives D D D Num. Fld 1 Char. Fld 2 Char. Fld 3 Char. Fld 4 S S S 5 9 9 7 7 2 Inz('123456. 78') Inz('-12345. 67') Inz('123. 4 N') Inz('1234 N') * Num. Fld 1 will be 123. 45 C Movel Char. Fld 1 * This will cause a decimal data error C Move Char. Fld 1 * Num. Fld 1 will be 012. 34 C Movel Char. Fld 2 * This will cause a decimal data error C Movel Char. Fld 3 * Num. Fld 1 will be 123. 45 (not -123. 45) C Movel Char. Fld 4 © 2007 IBM Corporation Num. Fld 1

EVAL Character to Numeric Expressions require the use of a BIF to cast numbers to characters • You can use %DEC and %DECH to convert to Decimal • You can use %INT and %INTH to convert to Integer • You can use %UNS and %UNSH to convert to Unsigned Integer D D Num. Fld 1 Char. Fld 2 Char. Fld 3 S S 5 9 7 7 2 Inz('123456. 78') Inz('123. 45') Inz('-123. 45') * This will cause an error - result field too small C Eval Num. Fld 1 = %Dec(Char. Fld 1: 5: 2) * Num. Fld 1 will be 123. 45 C Eval Num. Fld 1 = %Dec(Char. Fld 2: 5: 2) * Num. Fld 1 will be -123. 45 C Eval Num. Fld 1 = %Dec(Char. Fld 3: 5: 2) © 2007 IBM Corporation

Structured Operation Codes Traditional RPG supports the standard structured op codes § § § IFxx Condition code DO Iterate a loop a number of times DOWxx (Do While) Iterate a loop while a condition is true DOUxx (Do Until) Iterate a loop until a condition is true These are the fixed format equivalent of FOR, DOW, DOU and IF Structures op codes supported in Free Form can also be used in Extended Factor 2 § Actual expression is coded in the Extended Factor 2 area All code conditioned by a structured op code must be terminated by a corresponding END operation § ENDIF for an IFxx operation § ENDDO for DO, DOWxx and DOUxx operations - A simple END operation may be used but is not recommended © 2007 IBM Corporation

Relational Operators Apply to the IFxx, DOWxx, DOUxx, ANDxx and ORxx operations § They also apply to other structured operation codes (more later) The Operators are: § § § § GT Greater Than LT Less Than EQ Equal To NE Not Equal GE Greater Than or Equal LE Less Than or Equal e. g. DOWEQ, DOWLT, IFGT, IFLE Comparisons are made between operands in Factors 1 and 2 © 2007 IBM Corporation

IFxx and ELSE Causes groups of statements to be executed dependent on whether or not the condition is true . . . CL 0 N 01 Factor 1+++++++Opcode++++Factor 2+++++++Result++++Len++D+Hi. Lo. Eq C a If. LE b C 'It is True' Dsply C Else C 'It is False' Dsply C End. If © 2007 IBM Corporation

DO Loops through a group of instructions a number of times § § Factor 1 may specify the starting point Factor 2 specifies the limit or number of iterations Result field is automatically incremented on each iteration Factor 2 on the ENDDO operation may specify the incremental step . . . CL 0 N 01 Factor 1+++++++Opcode++++Factor 2+++++++Result++++Len++D+Hi. Lo. Eq C Do 5 C Add 1 Count C Count Dsply C End. Do C C C Count Start Do Dsply End. Do 5 Count Do End. Do Limit Step Count For End. For Count = Start by Step to Limit © 2007 IBM Corporation

DOWxx and DOUxx DOWxx § Processes a group of statements while the condition is true DOUxx § Processes a group of statements until the condition is true Code within the loop must cause the expression to be false or the loop will never end . . . CL 0 N 01 Factor 1+++++++Opcode++++Factor 2+++++++Result++++Len++D+Hi. Lo. Eq C Z-Add 5 x C x Do. WGT 0 C x Dsply C End. Do C C x x Z-Add Do. ULE Dsply End. Do 5 0 © 2007 IBM Corporation x

ANDxx / ORxx May be used in conjunction with IFxx, DOWxx, and DOUxx § Basically the same as the AND and OR operators in conventional expressions . . . CL 0 N 01 Factor 1+++++++Opcode++++Factor 2+++++++Result++++Len++D+Hi. Lo. Eq C AFld If. Eq BFld C CFld And. NE DFld C DFld Or. GT EFld C C C End. If AFld C C C C Do. WEq And. NE BFld DFld End. Do AFld CFld Do. UEq Or. Eq BFld DFld End. Do © 2007 IBM Corporation

A Caveat on the ORxx Operation An OR operation implies that ALL testing restarts § There is no "bracketing" with fixed format operations!. . . CL 0 N 01 Factor 1+++++++Opcode&Ext. Extended-factor 2++++++++++ C If (a = b And (c = d Or e = f)) C 'It is True' Dsply C End. If. . . CL 0 N 01 Factor 1+++++++Opcode++++Factor 2+++++++Result++++Len++D+Hi. Lo. Eq C a If. Eq b C c And. Eq d C e Or. Eq f C 'It is True' Dsply C End. If C C C a c e 'It is True' If. Eq Or. Eq Dsply End. If b d f © 2007 IBM Corporation

Resulting Indicators on I/O Operations CHAIN § The High Indicator is set if a record is NOT found - This is the Inverse of the setting of the %FOUND( ) BIF READ § The Equal indicator is set on if end of file is reached - Or there were no more matching records on a READE or READPE § Either way no record was retrieved by the read. . . CL 0 N 01 Factor 1+++++++Opcode++++Factor 2+++++++Result++++Len++D+Hi. Lo. Eq C Key Chain Cust 90 C *In 90 If. Eq *On C 'No Record' Dsply C End. If C C C Read *In 90 Do. WEq 'Read Record' Dsply Read End. Do Cust *Off 90 Cust 90 © 2007 IBM Corporation

Resulting Indicators SETLL Operation § The Equal Indicator is set if the next record’s key is equal to the key specified in Factor 1 § The High Indicator is set if the file pointer is at end of file SETGT Operation § The High Indicator is set if the file pointer is at end of file . . . CL 0 N 01 Factor 1+++++++Opcode++++Factor 2+++++++Result++++Len++D+Hi. Lo. Eq C Key. Fld Set. LL Sales 91 90 C Key. Fld Set. GT Sales © 2007 IBM Corporation 91

Key Lists Used in fixed form RPG when keys consist of more than one field § It specifies that the values of a group of fields are to be treated as the key value for a record The KLIST op code identifies the name of the key list § No actual operation takes place for this or the KFLD op code The KFLD op codes identify each of the key fields in turn. . . CL 0 N 01 Factor 1+++++++Opcode++++Factor 2+++++++Result++++Len++D+Hi. Lo. Eq C Key. Fld KList C KFld Cus. N C KFld Prod C Key. Fld Chain Sales C Key. Fld Set. LL Sales C Key. Fld Read. E Sales ------------------------------------Chain (Cus. N: Prod) Sales; © 2007 IBM Corporation

*LIKE DEFN allows you to define a field like a field § Prior to D Specs and the LIKE keyword § But they are not exactly the same - For numeric fields, the type of the field is not duplicated Using DEFN to define a field § Factor 1 contains *LIKE § Factor 2 is the base field § Result field is the new field In this example § DSPECVALUE is 10 I 0 § CSPECVALUE is 10 P 0 D Value D DSpec. Value S S 10 I 0 Like(Value) . . . CL 0 N 01 Factor 1+++++++Opcode++++Factor 2+++++++Result++++Len++D+Hi. Lo. Eq C *Like Defn Value CSpec. Value © 2007 IBM Corporation

I Spec (Input) - File Field Definition I Specs for file field definitions are only used if: § A file needs to be internally defined § Fields need to be renamed - Modern programmers would use the PREFIX keyword on the F Spec § Record identifying indicators or Level Break indicators need to be assigned. - Which means you are using the RPG Cycle. * * Input Specifications for File ( Rarely, if ever, used ) *. . . IRcdname+++. . Ri. . . . ICustomer 01. . . I. . . Ext-field+. . . . Field+++++L 1 M 1. . Pl. Mn. Zr. . . . I Cust. Ref Cust. No. . . I Geo. Loc L 1. . . I. . . Fmt+SPFrom+To+++Dc. Field+++++L 1 M 1 Fr. Pl. Mn. Zr. . © 2007 IBM Corporation

O Specs (Output) Used if: § A file needs to be internally defined - So there is not a lot of need for them! § Mostly used these days for PRINTER files. . . OName++++++DF. . N 01 N 02 N 03 Excnam++++B++A++Sb+Sa+. . . OList E Head 3 O UDate Y 108 O Page Z 208 O E Head 1 O 8 'A/C Code' O 13 'Name' O 47 'Address' O E Detl 2 O CCode 7 O AName 39 O AAdd 1 70 O E Detl 1 O AAdd 2 70 O. . . N 01 N 02 N 03 Field+++++YB. End++PConstant/Editword/DTformat © 2007 IBM Corporation

GOTO and CAB – Just hope you never see them! Legacy code includes operations that should never be used § GOTO § TAG § CAB Branch (or jump) to the specified label Identifies the label that is the target of a GOTO or CAB Is a combination IF / GOTO operation Do NOT Use Them! You may also encounter CASxx operations § This means Conditionally Execute Subroutine § The ‘xx’ represents one of the Relational Operators discussed earlier § Not as bad as GOTO etc. but there are better ways to do things today . . . CL 0 N 01 Factor 1+++++++Opcode++++Factor 2+++++++Result++++Len++D+Hi. Lo. Eq C Go. To Tag. A C AFld Cab. Eq C Tag. A Tag BFld © 2007 IBM Corporation Tag. A

The Legacy You are dealing with legacy code if you come across § § § § Fixed Format C Specs All code in upper case Use of Built In Indicators (01 to 99) Use of Resulting Indicators Use of Key Lists Use of *LIKE Result Fields defined on C Specs Use of ADD, SUM, MULT, DIV etc. You may also come across § The RPG cycle § Conditioning indicators § Use of “non-modular” operation codes (GOTO, etc. ) Third party conversion tools available § May be used to convert to modern methods Convert to Free Form option available in WDSC © 2007 IBM Corporation
- Slides: 142