1 / 142

RPG Basics

RPG Basics. Module 1. 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. Course Prerequisites.

grayl
Download Presentation

RPG Basics

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. RPG Basics Module 1

  2. 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

  3. 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.)

  4. 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" (SG24-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 SG24-5402 International Technical Support Organization Rochester, Minnesota

  5. Introduction

  6. 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!

  7. A Brief History • RPG – 1960s (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. iSeries, i5) • Enhancements • New operation codes, Named constants, Initialization subroutines • Embedded SQL statements

  8. RPG IV • RPG IV • First available with OS/400 V3R1 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 V2R3 • Greater modularity • Better performance

  9. Standard Representation of an RPG Program Data Storage I/O Buffers Instruction Set

  10. 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

  11. Coding and Compiling a Program Editor CRTBNDRPG QRPGLESRC *FILE (PF-SRC) MYPGM Member Type RPGLE MYPGM *PGM

  12. 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'; *InLR = *On; /End-Free

  13. Coding in RPG

  14. 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

  15. 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. FieldName = fieldname = FIELDNAME • In 2001, RPG Calculation specifications became "free format“ • But most existing code still has the traditional columnar look and feel

  16. 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.

  17. 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 .....CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq C b Add c a .....CL0N01Factor1+++++++Opcode(E)+Extended-factor2+++++++++++++++++++++++++++++ C Eval a = b + c a = b + c;

  18. 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

  19. 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

  20. Zoned and Packed Numbers • Zoned – a digit is represented by a byte • Half byte (high) of right most digit indicates sign (D is negative) 12345 12345- • Packed – a digit is represented by a half byte (nibble) • Low order (right most) nibble of right most digit indicates sign 12345 12345-

  21. Integers

  22. 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+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++

  23. 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+++++++++++ETDsFrom+++To/L+++IDc.Keywords++++++++++++++++++++ D Character S 30A D CharacterDft S 20 D Packed S 9P 0 D PackedDft S 11 2 D Integer S 10I 0 D UnsignedInt S 5U 0

  24. 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+++++++++++ETDsFrom+++To/L+++IDc.Keywords++++++++++++... D ThisIsAFieldWithAVeryVeryVeryVeryVeryVeryVery... D LongName S 20 D Count S 5I 0 Inz(1) D CountB S Like(Count)

  25. 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

  26. Literals • Literals are used to specify an actual value • Character • Enclose the contents in single apostrophes • Or as a hex literal e.g. X’F1’ • 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

  27. 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 half-adjust is in use • Extender of H (half adjust) required for rounding • There are other extenders which will be covered in later units D a S 7 2 D b S 7 5 Inz(1.79766) D c S 5I 0 Inz(750) D d S 5 3 Inz(2.101) a = b + c; // a = 751.79 a = b + d; // a = 3.89 Eval(H) a = b + d; // a = 3.90

  28. 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));

  29. 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 x S 5I 0 Inz(1) D y S 5I 0 Inz(2) D a S 5I 0 Inz(3) D b S 5I 0 Inz(4) D c S 5I 0 Inz(5) D Result S 5I 0 /Free Result = a + b * c ** (x*y);

  30. 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 PhoneNo S 13 D AreaCode S 3 Inz('1') D Exchange S 3 Inz('234') D Suffix S 4 Inz('5678') /Free PhoneNo = '(' + AreaCode + ') ' + Exchange + '-' + Suffix; // PhoneNo = (1 ) 234-5678

  31. 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 Char1 S 4 Inz('AAAA') D Char2 S 4 Inz('BBBB') /Free Small = Char1 + Char2; // Small = 'AAAABB' EvalR Small = Char1 + Char2; // Small = 'AABBBB'

  32. 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 S 10 D Over S 10 Inz('All Done!') /Free Dsply 'This is some text'; Dsply 'Enter a value:' ' ' Entered; Dsply ('You Entered ' + Entered); Dsply Over;

  33. 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 *IN01 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

  34. 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 *InLR = *On; Return;

  35. Structured Operation Codes

  36. Structured Operation Codes • RPG supports the standard structured operation codes. • IF/ELSE/ELSEIF Condition code • FOR Loop a number of times • DOW (Do While) Loop while a condition is true • DOU (Do Until) 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

  37. IF, ELSE, 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'; EndIf; If ((a = b) and (c = d)) OR (a > c); Dsply 'The condition is true'; EndIf; If x = y; Dsply ‘x and y are the same’; ElseIf x > y; Dsply ‘x is bigger than y’; Else; Dsply ‘x is smaller than y’; EndIf;

  38. 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 second condition is true'; Else; Dsply 'The second condition is true'; EndIf EndIf

  39. FOR 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; EndFor; For x = 1 by 2 to 10; Dsply x; EndFor; For x = Start By Step To Until; Dsply x; EndFor; For x = 10 DownTo 1; Dsply x; EndFor;

  40. 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; DoW x > 0; Dsply x; x = x – 1; EndDo; x = 0; DoW x > 0; Dsply x; x = x – 1; EndDo;

  41. 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; DoU x = 0; Dsply x; x = x – 1; EndDo; x = 0; DoU x <= 0; Dsply x; x = x – 1; EndDo;

  42. 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. DoW x > 0; If x = y; Iter; EndIf; If x = z; Leave; EndIf; EndDo;

  43. Indicators and Built-In-Functions (BIFs)

  44. Defining and Setting Indicators • 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 BadRate S N /Free If Rate < 0; BadRate = *On; Else; BadRate = *Off EndIf;

  45. 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 BadRate S N /Free BadRate = (Rate < 0); If BadRate; Dsply 'The rate is negative'; EndIf; If Not BadRate; Dsply 'The rate is positive'; EndIf;

  46. 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 *IN01 to *IN99. • 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 *IN55 is *IN(55) *In30 = *In31 or *In32; If Not *In30; *In51 = *On; *In52 = *Off; EndIf;

  47. Built-In Functions (BIFs) • BIFs are one of the most versatile features of RPG • As of V5R4 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

  48. %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 FirstName S 15 Inz('Paul') D LastName S 15 Inz('Tuohy') D PrintName S 25 PrintName = FirstName + LastName; // PrintName = 'Paul Tuohy ' PrintName = %TrimR(FirstName) + ' ' + LastName; // PrintName = 'Paul Tuohy '

  49. %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 InpString 20 Inz('Dr. Doolittle') D Position 3 0 Position = %Scan('tt‘ : InpString); // Position = 10 Position = %Scan('D‘ : InpString : 2); // Position = 5

  50. %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 NameField S 20 INZ ('Paul Tuohy ') D FirstName S 10 D LastName S 10 D x S 5I 0 x = %Scan(' ' : NameField); FirstName = %SubSt(NameField :1 : x-1); // FirstName = 'Paul ' LastName = %SubSt(NameField : X+1); // LastName = 'Tuohy ' %SubSt(NameField : X+1 : 4) = 'Huth' // NameField = 'Paul Huthy '

More Related