2d142a3edd9d3a5e2a550ff6802900b6.ppt
- Количество слайдов: 79
® IBM Software Group Enterprise COBOL Education Using Rational Developer for System Z Module 3 – Basic COBOL Statements Jon Sayles, IBM Software Group, Rational Eco. Systems Team © 2006 IBM Corporation
IBM Trademarks and Copyrights 4 © Copyright IBM Corporation 2007, 2008, 2009. All rights reserved. 4 The information contained in these materials is provided for informational purposes only, and is provided AS IS without warranty of any kind, express or implied. IBM shall not be responsible for any damages arising out of the use of, or otherwise related to, these materials. Nothing contained in these materials is intended to, nor shall have the effect of, creating any warranties or representations from IBM or its suppliers or licensors, or altering the terms and conditions of the applicable license agreement governing the use of IBM software. References in these materials to IBM products, programs, or services do not imply that they will be available in all countries in which IBM operates. 4 This information is based on current IBM product plans and strategy, which are subject to change by IBM without notice. Product release dates and/or capabilities referenced in these materials may change at any time at IBM’s sole discretion based on market opportunities or other factors, and are not intended to be a commitment to future product or feature availability in any way. 4 IBM, the IBM logo, the on-demand business logo, Rational, the Rational logo, and other IBM Rational products and services are trademarks or registered trademarks of the International Business Machines Corporation, in the United States, other countries or both. Other company, product, or service names may be trademarks or service marks of others. 2
Course Contributing Authors § Thanks to the following individuals, for assisting with this course: 4 4 4 David Myers/IBM Ka Yin Lam/IBM Don Higgins/Automated Software Tools Corporation Steve Wilcenski/Sabre Systems, Inc. Mike Wrzinski/Sentry Insurance 3
Course Description 4 Course Name: COBOL Foundation Training - with RDz 4 Course Description: Learn the COBOL language, RDz and learn z/OS terms, concepts and development skills in this course. 4 Pre-requisites: Some experience in a 3 rd or 4 th Generation Language is expected. SQL is also recommended. 4 Course Length: 10 days 4 Topics (Agenda) § § § § Getting Started - installing and configuring RDz - and the course materials, and using Eclipse to edit COBOL General Language Rules Basic COBOL Statements Advanced record and table handling Debugging Programs - Note: Deep dive on using RDz for common COBOL programming errors (001, 0 C 4, 0 C 7, infinite loops, fall-thru, etc. ) Input/Output and Report Writing Patterns COBOL Subprograms and the Linkage Section Structured Programming Concepts, professional COBOL development practices and Coding Patterns Advanced Character Manipulation, COBOL Intrinsic Functions, Date and Time coding patterns, and Language Environment calls OS/390 Concepts and JCL - Compile/Link & Run Procs on the mainframe Indexed file Coding Patterns Sort/Merge, Sequential File Match/Merge and Master File Update Coding Patterns Accessing DB 2 Data and DB 2 Stored Procedures COBOL in the Real World: – CICS - lecture only – IMS (DL/I and TM) - ditto – Batch processing - ditto – Java calling COBOL – COBOL and XML Statements – SOA and COBOL - creating and calling Web Services – Web 2. 0 using Rich UI 4
Course Details § Audience 4 This course is designed for application developers who have programmed in some language before, and who wish to learn COBOL. § Prerequisites 4 This course assumes that the student has the basic knowledge of IS technologies, data processing, software and have programmed for at least two or more years in a language such as: Java, VB, RPG, PL/1, Pascal, or some 4 th Generation Language or tool. 4 Knowledge of SQL (Structured Query Language) for database access is assumed as well. 4 Basic PC and mouse-driven development skills is also assumed. 4 Finally, it is assumed that you have been following along in this course, and have successfully completed the learning modules in sequence. § Or have the equivalent COBOL background obtained through some other form of COBOL study or on-the-job work. 5
Unit COBOL General Language Rules Topics: § Assignment Statements and Internal Data Representation § Math Operations § Conditional Logic § Transfer of control § COBOL Looping Constructs § Sequential File Processing Patterns § Java and. NET Equivalents 6
Topic objectives After completing this topic, you should be able to: 4 Describe the COBOL MOVE and assignment operation 4 List the three types of COBOL assignment statements – and what causes the COBOL compiler to choose one type over the other 4 Define the rules for: § Alphanumeric moves § Numeric moves § Group or structure moves 4 List a few optional MOVE clauses, and describe what they do, including: § MOVE CORRESPONDING 4 Code MOVE statements that are syntactically correct 4 Describe the underlying COBOL storage representation for: § Alphanumeric data § Numeric data 4 List the common COBOL Figurative Constants 4 Describe what the COBOL INITIALIZE statement does 7
COBOL Picture Clauses and Internal Data Representation COBOL Data types are PIC clause dependent, and come in several broad categories: § Character Data: 4 Fixed Length: PIC X(nn) – or PIC A(nn) … Note, A "Alphabetic data" 4 Stored as EBCDIC bytes – examples: A Hex: C 1, B Hex: C 2, 9 Hex: F 9, etc C 1 C 2 F 9 http: //theamericanprogrammer. com/code 7302/ebcdic. txt § Numeric Data: 4 Display numeric (aka Zoned Decimal): PIC 9(5), PIC S 9(5)V 99 § Stored as EBCDIC bytes, with "assumed" decimal place – one byte per digit – Hex values: F 0 F 9 § With V in declaration – COBOL takes care of decimal alignment in math/MOVE operations § With S (sign) in declaration, the last byte of internal storage holds the sign (C or D): – – C - is positive number: – PIC S 9(5)V 99 - value: 321. 19 F 0 F 3 F 2 F 1 C 9 D - is negative number – PIC S 9(5)V 99 - value: 321. 19 F 0 F 3 F 2 F 1 D 9 EBCDIC Internal Data Representation 4 Binary (COMP) numeric – used to improve run-time COBOL arithmetic instruction performance: § § Small binary: PIC S 9(4) COMP – stored in two bytes, pure binary (base 16) data Medium binary: PIC S 9(9) COMP – stored in four bytes Large binary: PIC S 9(18) COMP – stored in eight bytes With or without Signs, and assumed decimal places: Ex. – – PIC S 9(4) COMP Value 123. Stored as: 0123 PIC S 9(4) COMP Value 123. PIC S 9(4) COMP Value -123. Stored as twos complement of 123: FF 85 PIC S 9(4) COMP Value -123. 4 Packed decimal (COMP-3) numeric – frequently used to reduce the size of a file: § Two digits per/byte. Sign bit – in last "nibble" (bottom 1/2 of last byte). "Slack bytes" (other high-order/leading zeroes) may need to be added to the internal storage to account for evenly divisible PIC clause + sign nibble Ex. – – PIC S 9(5)V 99 COMP-3 Value 123. 99. Stored as: 00 12 39 9 C PIC S 9(5)V 99 COMP-3 Value 123. 99. PIC S 9(5)V 99 COMP-3 Value -123. 99. Stored as: 00 12 39 9 D PIC S 9(5)V 99 COMP-3 Value -123. 99. Important – See Slide Notes 8
COBOL Picture Clause Editing and External (Output) Field Values § There a number of other PIC clauses used for output result data on reports and greenscreen I/O. They are simple to understand, and very convenient. Note that the numeric PIC clauses force decimal-point alignment. The alphanumeric PIC clauses all align the data left. § Z § § § Suppress leading zeroes – insert floating blanks PIC ZZ, Z 99. 99 B Alphanumeric "mask" – Positionally insert a blank into alphanumeric data PIC XBXBXB 0 Numeric "mask" - Positionally insert a zero into a numeric field. PIC 990990 / Data mask - Insert a slash into alphanumeric data – typically used for dates PIC XX/XX/XX , Insert a comma into numeric data PIC Z, ZZZ, Z 99. Insert a decimal point, into numeric data Z, ZZZ, Z 99. 99 + Insert a plus sign – IF the value in the variable is > 0 PIC Z, ZZZ, Z 99. 99+ Insert a negative sign – IF the value in the variable is < 0 PIC Z, ZZZ, Z 99. 99 CR Insert a "CR" literal – IF the value in the variable is < 0 PIC Z, ZZZ, Z 99. 99 CR DB Insert a "DB" literal – IF the value in the variable is < 0 PIC Z, ZZZ, Z 99. 99 DB * Insert asterisks instead of leading zeros for numeric values PIC ****9999 $ Dollar-sign suppressions - Insert a floating, left-justified $ sign for numeric values PIC $$, $99. 99 9
ILE Reference Manual – Picture Clause Editing Examples – 1 of 2 § The ILE reference manual has an excellent sample guide to Picture Clause editing 4 http: //publib. boulder. ibm. com/infocenter/iadthelp/v 7 r 0/index. jsp? topic=/com. ibm. etools. iseries. langref. doc/c 0925395267. htm 10
ILE Reference Manual – Picture Clause Editing Examples – 2 of 2 § The ILE reference manual has an excellent sample guide to Picture Clause editing 4 http: //publib. boulder. ibm. com/infocenter/iadthelp/v 7 r 0/index. jsp? topic=/com. ibm. etools. iseries. langref. doc/c 0925395267. htm 11
COBOL Storage Representation – Reference Chart Value Internal Storage (EBCDIC bytes) Picture Clause Meaning PIC X(10) Fixed alpha-numeric data PIC 9(5) Display numeric (Zoned Decimal) numbers -321 00321 - Note - without S (sign) value get "absolute value" FFFFF 00321 PIC S 9(5) Zoned decimal - with sign -321 00321 - Value is negative in math operations FFFFD 00321 PIC S 9(5)V 99 Zoned decimal with implied decimal place 321. 5 00321 V 50 PIC S 9(4) COMP Small binary number - 2 byte - note, negative binary #s stored as two's complement 321 0321 PIC S 9(5) ==> S 9(9) COMP Binary number - 4 bytes 321 00000321 PIC S 9(9) ==> S 9(18) COMP Large Binary number 321 00000000321 PIC 9(4) COMP-3 Packed decimal number 321 0321 PIC S 9(5)V 99 COMP-3 Packed decimal number 321. 99 00321. 99 0319 029 C PIC S 9(5)V 99 COMP-3 Packed decimal number -321. 99 00321. 99 – Value is negative in math operations 0319 029 D 'ABC' Internal Value CCC 4444444 1230000 ABCbbbbbbb (seven trailing blanks) FFFFFFC 0032150 04 11 0004 0011 00000004 00000011 031 02 F External PIC clauses Value Output/Display Value Notes PIC Z(3) Zero-suppressed -2. 99 PIC ZZ, ZZZ. 99 - Zero-suppressed, with commas and minus sign -321. 99 PIC $$, $99. 99 Dollar-sign suppressed -321. 99 PIC XBXBXB Blank insertion ABC PIC 990990 Zero insertion -321. 99 PIC XX/XX/XX Slash insertion 012099 PIC Z, ZZZ, Z 99. 99 CR Zero-suppressed, with commas and Credit sign -321. 99 PIC ****9999 Asterisk suppressed PIC Z, ZZZ, Z 99. 99 DB Zero-suppressed, with commas and Debit sign -333321. 99 12 2 No decimal places, no sign 321. 99 - Sign on right (can be on left). Zeroes suppressed $321. 99 One resulting $, if need sign, must use dash (-) Ab. Bb. Cb Positional blank (b) inserted 030210 01/10/99 High-order inserted, numbers inserted @ PIC 9 Date mask 321. 99 CR **321 321. 99 If number was positive, CR would not appear Like Z and $ - asterisk suppresses leading zeros If number was negative, DB would appear
88 -Level Variables in the Data Division § § 88 -level variables in COBOL programs are "conditionals, built in to the variable declarations" They: 4 Have no PIC clause 4 Have one or more VALUES – specified as literals (see a few valid expressions below) 4 Are used effectively to make COBOL IF conditional expressions readable/maintain-able 01 MONTH-IND PIC XXX. 88 SHORTEST-MONTH VALUE 'FEB'. 88 THIRTY-DAY-MONTH VALUES ARE 'JUN', 'SEP', 'APR', 'NOV'. 88 THIRTY-ONE-DAY MONTH VALUES ARE 'JAN' 'MAR' 'MAY' 'JUL' 'AUG' 'OCT' 'DEC'. … IF THIRTY-DAY-MONTH … 01 STUDENT-GRADE-RANGE PIC S 9(3). 88 A-OK VALUE 90 THRU 100. 88 NOT-BAD VALUE 80 THRU 89. 88 PRETTY-GOOD VALUE 70 THRU 79. 88 RUH-ROH VALUE 60 THRU 79. 88 FAIL VALUE 0 THRU 59. … IF NOT-BAD MOVE 'DOIN ALRIGHT' TO MSG-TEXT DISPLAY GRADE-MSG 13 Pluses: • Make code more "English" read-able • Allow you to centralize conditions in one place in the DATA DIVISION Minuses: • Force you to refer to the DATA DIVISION for the actual values tested in the code in the PROCEDURE DIVISION
Review – Imperative Statements – MOVE FILE SECTION … 01 OUT-REC PIC X(80). … WORKING-STORAGE SECTION. 77 INPUT-DATA PIC X(40). … PROCEDURE DIVISION. … ACCEPT INPUT-DATA. MOVE INPUT-DATA TO OUT-REC. Syntax: MOVE <to-variable> TO <from-variable>. § MOVE copies the value in the to-variable to the from-variable (receiving field), over-writing the from-variable’s storage contents. § There are two types of MOVE operations: 4 Alphanumeric MOVE 4 Numeric MOVE § § The receiving field's datatype (PIC clause) dictates the type of MOVE operation It is important to understand how the contents of variable storage are affected by MOVE. So, let's drill-down now, on PIC clauses and COBOL internal data MOVE storage representation 14
Alphanumeric MOVE Statements MOVE Alphanumeric MOVE statements: 4 Occur when the receiving field is considered Alphanumeric by the compiler § PIC X § PIC A § The Alphanumeric formatted output PIC clauses: – PIC with B, etc. 4 Proceed from left-to-right – and copy byte-for-byte § When the sending and receiving fields are not the same size: 4 Space (blank) fill to the right, if the receiving field is longer than the sending field 4 Truncate if the receiving field is shorter than the sending field (typically you will get a W-level diagnostic when you compile a program with a MOVE statement that truncates data) 4 Except – can JUSTIFY the receiving field data RIGHT § FLD 1 PIC X(4) VALUE 'ABCD'. § FLD 2 PIC X(10) JUSTIFY RIGHT. … § MOVE FLD 1 TO FLD 2. – Results in FLD 2 value of: bbbbbb. ABCD § § § If JUSTIFY RIGHT, and the receiving field is shorter than the sending field, truncation occurs in the right-most JUSTIFY RIGHT characters If JUSTIFY RIGHT, and the receiving field is longer than the sending field, blanks are added to the left-most JUSTIFY RIGHT positions Note: if, FLD 1 PIC X(10) VALUE 'ABCD' result of MOVE is: ABCDbbbbbb – Why? 4 Copy: § Internal storage values byte for byte § For the # of bytes in the receiving field § Group data (structures) are considered Alphanumeric – in MOVE operations 15
Numeric MOVE Statements MOVE § Numeric MOVE statements: 4 Occur when the receiving field's PIC clause is numeric § 9 … anywhere in the PIC clause 9 … PIC § Input field declaration: – V, S § Output (formatted numeric PIC clause in declaration) – Z, $, 0, DB, CR, +, -, period (. ), comma (, ) § MOVE copies the algebraic value of the sending field to the receiving field as follows: 4 Automatically aligns at the decimal place § Or assumed decimal place if no V in PIC clause 4 Pad to the left with leading, and to the right with trailing zeroes, if the receiving field has zeroes more decimal digits to the left or the right of the (assumed) decimal positions 4 If sign (S) or numeric edited sign MOVE will value the receiving positively or negatively depending on the sending field's value. If no sign, the receiving field gets absolute value 4 Will numerically truncate – if receiving field has fewer decimal digits to the left of the decimal place, or less digits (decimal precision) to the right of the decimal place What about mixed datatype MOVE statements? (next slide…) 16
MOVE Statements When the Datatypes Are Not The Same § Obviously you can move PIC X fields to other PIC X – and PIC 9 fields to other PIC 9 fields, but sometimes, due to business requirements you will have to code MOVE statements of unlike (mixed) datatypes. § Here are the general rules: 4 4 § Anything can be moved to an alphanumeric PIC X field Only other PIC 9 (input) fields can be moved to PIC 9 fields And only PIC 9 fields can be moved to numeric edited fields PIC 9 numeric edited fields can be moved to PIC 9 fields Group moves are considered exactly the same as an alphanumeric PIC X field move by the compiler 4 And all the rules you just learned about truncation, padding and decimal alignment also apply § This table may help clarify the rules for mixed data type MOVE Sending Fields PIC X PIC 9 Receiving Fields PIC X Y PIC 9 N Y Numeric Edited N Y Y Y N Treated as an alphanumeric MOVE (digits may be lost, trailing blanks may be added, etc. ) Numeric Edited Y 17
Allowable MOVE Statements § Please consult this verbose (!) table to see the complete list of COBOL allowable MOVE statements – based on sending and receiving field PIC types. § Don't worry if there are terms you're not up to speed on just yet – we'll get you there. § Patience 18
Alphanumeric MOVE Statements - Examples MOVE Sending Field Receiving Field Sending Field Value Result in Receiving Field PIC X(5) ABCDE PIC X(5) PIC X(3) ABCDE ABC PIC X(5) PIC X(8) ABCDEbbb PIC 9(5) PIC X(8) 12345 bbb PIC X(5) PIC 9(5) Not allowed by the compiler N/A PIC S 9(5)V 99 COMP-3 PIC X(8) Not allowed by the compiler – as is noninteger numeric (see table of moves) 13574444 246 C 0000 PIC S 9(4) COMP PIC X(4) 1234 1344 2400 PIC X(4) PIC X(10) JUSTIFY RIGHT. ABCD bbbbbb. ABCD (hex) Numeric Value PIC 9(5)V 99 PIC 9(3)V 9 12345. 67 PIC S 9(7)V 99 PIC 9(4) COMP 123456789. 99 6789 PIC S 9(5)V 99 PIC S 9(7)V 999 COMP-3 -12345. 67 0012345. 670 (minus carried in sign bit) PIC S 9(9) COMP PIC 9(5)V 99 1234567912. 00 PIC S 9(5)V 99 COMP-3 PIC 9 -12345. 67 5 CUSTOMER-NAME PIC X(18) SMITHbbbbb. AALEXAND CUSTOMER-RECORD PIC X(40) 1201 SMITHbbbbb. AALEXANDERbbbbbbbbbbb Group Moves 01 CUSTOMER-RECORD. 05 ID-NUMBER 05 CUST-TYPE 05 CUSTOMER-NAME. 10 FIRST-NAME 10 MIDINIT 10 LAST-NAME PIC 9(2) VALUE 12. PIC 9(2) VALUE 01. PIC X(10) PIC X(01) PIC X(10) VALUE 'SMITH'. VALUE 'ALEXANDER'. 19
MOVE With OF Modifier FILE SECTION. … 01 CUSTOMER-RECORD-IN. 05 ID-NUMBER PIC 9(2). 05 CUST-TYPE PIC 9(2). 05 CUSTOMER-NAME. 10 FIRST-NAME PIC X(10). 10 MIDINIT PIC X(01). 10 LAST-NAME PIC X(10). 01 CUSTOMER-RECORD-OUT. 05 ID-NUMBER PIC 9(2). 05 CUST-TYPE PIC 9(2). 05 CUSTOMER-NAME. 10 FIRST-NAME PIC X(10). 10 MIDINIT PIC X(01). 10 LAST-NAME PIC X(10). … PROCEDURE DIVISION. MOVE FIRST-NAME OF CUSTOMER-RECORD-IN TO FIRST-NAME OF CUSTOMER-RECORD-OUT. § Syntax: MOVE <from-variable> of <from-Group> to <to-variable>. § The OF modifier allows you to: 4 Fully-qualify elementary field names – making large programs with 1, 000's variables easier to maintain 4 Compile programs with duplicate elementary field names 20
MOVE CORRESPONDING FILE SECTION. … 01 CUSTOMER-RECORD-IN. 05 ID-NUMBER PIC 9(2). 05 CUST-TYPE PIC 9(2). 05 CUSTOMER-NAME. 10 FIRST-NAME PIC X(10). 10 MIDINIT PIC X(01). 10 LAST-NAME PIC X(10). 01 CUSTOMER-RECORD-OUT. 05 ID-NUMBER PIC 9(2). Field's data not moved 05 CUSTTYP PIC 9(2). 05 CUSTOMER-NAME. Field's data not moved 10 FIRSTNAME PIC X(10). 10 MIDINIT PIC X(01). 10 LAST-NAME PIC X(10). … PROCEDURE DIVISION. MOVE CORRESPONDING CUSTOMER-RECORD-IN TO CUSTOMER-RECORD-OUT. § Syntax: MOVE CORRESPONDING <from-group-variable> to <to-group-variable>. § The CORRESPONDING modifier allows you to MOVE group records: 4 When COBOL variable names match between the from and to groups, data is copied 4 And only when COBOL variable names match 21 See Notes
COBOL INITIALIZE Statement INITIALIZE § INITIALIZE values selected types of data fields. The default is: 4 Numeric data to zeros 4 alphanumeric data (PIC X or Group Data Items) to spaces. § You can also INITIALIZE fields, replacing classes of datatypes with specific values 4 This is used less frequently, and is shown in the slide notes § Initializing a structure (INITIALIZE) 4 You can reset the values of all subordinate data items in a group item by applying the INITIALIZE statement to that group item. 22
COBOL Figurative Constants FILE SECTION. … 01 CUSTOMER-RECORD-IN. … 77 COBOL-CHAR-FIELD PIC X(4). 77 COBOL-NUM-FIELD PIC X(4). 77 COBOL-QT PIC X(1) VALUE QUOTE. PROCEDURE DIVISION. MOVE LOW-VALUES to CUSTOMER-RECORD-IN. MOVE HIGH-VALUES to COBOL-CHAR-FIELD. MOVE SPACES to COBOL-CHAR-FIELD. MOVE ZEROS to COBOL-NUM-FIELD. MOVE ALL '_' TO COBOL-CHAR-FIELD. § Syntax: MOVE <figurative constant> to <Cobol variable>. § There a number of COBOL figurative constants available to fill the storage of alphanumeric fields (or in the case of ZEROS), either: 4 With MOVE statements 4 In VALUE clauses of field declarations § § The figurative constants are reserved words, and there a number of alternative spellings (see the COBOL language reference, or RDz Help system) They are sometimes used by convention to signal some processing event: 4 READ <file. Name> AT END MOVE HIGH-VALUES TO <input. Record>. 23
Lab Assignment From the course workshop documents, do the following labs: 1. Data Representation and assignment (MOVE statement) Lab 2. Open ended workshop 24
Unit COBOL General Language Rules Topics: § Assignment Statements and Internal Data Representation § Math Operations § Conditional Logic § Transfer of control § COBOL Looping Constructs § Sequential File Processing Patterns § Java and. NET Equivalents 25
COBOL Mathematical Operators § As you'd expect from a a business oriented language, COBOL's math language capabilities are simple, flexible, deep and robust. 4 Simple operations: § § ADD SUBTRACT MULTIPLY DIVIDE …with a number of variations of operand/operator expressions and automatic decimal alignment across all numeric types 4 Algebraic statements: § COMPUTE – uses arithmetic operators (next slide) to perform math operations 4 COBOL Intrinsic "Built-in" math Functions § Here a few of the math-oriented COBOL intrinsic functions: ACOS ANNUITY ASIN ATAN CHAR COS FACTORIAL LOG 10 MAX MEAN MEDIAN MIDRANGE MIN MOD PRESENT-VALUE RANDOM 26 RANDOM RANGE REM REVERSE SIN SQRT STANDARD-DEVIATION SUM TAN VARIANCE
Fixed-Point Arithmetic Statements*** – ADD WORKING-STORAGE SECTION. 01 WORK-FIELDS. 05 ITEM-1 PIC S 9(3)V 99 VALUE 85. 52. 05 ITEM-2 PIC S 9(3)V 99 VALUE 2. 34. 05 SUM PIC S 9(5)V 99 VALUE 0. PROCEDURE DIVISION. … ADD ITEM-1, ITEM-2 TO SUM ROUNDED ON SIZE ERROR MOVE 0 TO SUM END-ADD ITEM-1 ITEM-2 GIVING SUM ROUNDED ON SIZE ERROR MOVE 0 TO SUM DISPLAY '** ON SIZE ERROR **' END-ADD § Format 1 § Rounded 4 Rounds to the decimal digits in the PIC clause (See Slide Notes) § ON SIZE ERROR 4 Allows you to handle arithmetic overflow conditions with imperative statements. § Additional note: You can Additional note: substitute a numeric literal for the variables in the ADD and TO (but not GIVING) clauses in the GIVING statement 4 Adds the addend to the sum § Format 2 4 The values of all operands preceding the word GIVING are added together, and the sum is stored as the new value. 4 None of the values in the operands preceding GIVING are changed § Note: There is a Format 3 statement: ADD CORRESPONDING 27 ***See Notes
Arithmetic Statements – ROUNDED and ON SIZE ERROR WORKING-STORAGE SECTION. 01 WORK-FIELDS. 05 ITEM-1 PIC S 9(5)V 99 VALUE 85. 56. 05 RESULT PIC S 9(6) VALUE 100. PROCEDURE DIVISION. … ADD ITEM-1 TO RESULT. Value: 185 MOVE 100 TO RESULT. ADD ITEM-1 TO RESULT ROUNDED. Value: 186 The ROUNDED phrase allows you to specify rounding up to the nearest low-order decimal digit of precision. This means that ROUNDED adds 1 to the absolute value of the low-order digit of the result variable IF the absolute value of the next least IF significant digit of the intermediate variable value is >= to 5. MOVE 140156. 33 TO ITEM-1. MOVE 900000 TO RESULT. ADD ITEM-1 TO RESULT ROUNDED. Value: 040156 MOVE 900000 TO RESULT. ADD ITEM-1 TO RESULT ON SIZE ERROR MOVE 0 TO SUM DISPLAY '** ON SIZE ERROR **'. 28 Value: 000000
Arithmetic Statements – SUBTRACT § WORKING-STORAGE SECTION. 01 WORK-FIELDS. 05 ITEM-1 PIC S 9(3)V 99 VALUE 85. 52. 05 ITEM-2 PIC S 9(3)V 99 VALUE 2. 34. 05 DIFFERENCE PIC S 9(5)V 99 VALUE 0. PROCEDURE DIVISION. … SUBTRACT ITEM-1, ITEM-2 FROM DIFFERENCE ROUNDED ON SIZE ERROR MOVE 0 TO DIFFERENCE END-SUBTRACT ITEM-1 FROM ITEM-2 GIVING DIFFERENCE ROUNDED ON SIZE ERROR MOVE 0 TO DIFFERENCE DISPLAY '** ON SIZE ERROR **' END-SUBTRACT § § § Rounded 4 Rounds to the decimal digits in the PIC clause § ON SIZE ERROR 4 Allows you to handle arithmetic overflow conditions with imperative statements. § Additional note: You Additional note: can substitute a numeric literal for the variables in the SUBTRACT and FROM (but not GIVING) clauses GIVING in the statement Format 1 4 Subtracts all minuends from the sum Format 2 4 The values of all operands preceding the word GIVING are added together, and the sum is subtracted from the difference (in the above) 4 None of the values in the operands preceding GIVING are changed Note: There is a Format 3: SUBTRACT CORRESPONDING 29
Arithmetic Statements – MULTIPLY WORKING-STORAGE SECTION. 01 INPUT-FIELDS. 05 ITEM-1 PIC S 9(3)V 99 VALUE 85. 52. 05 ITEM-2 PIC S 9(3)V 99 VALUE 2. 34. 05 ITEM-3 PIC S 9(3)V 99 VALUE 6. 01. 05 RESULT PIC S 9(5)V 99. PROCEDURE DIVISION. MULTIPLY ITEM-1 BY ITEM-3 ROUNDED ON SIZE ERROR MOVE 0 TO DIFFERENCE END-MULTIPLY ITEM-1 BY ITEM-2 GIVING RESULT ROUNDED ON SIZE ERROR MOVE 0 TO DIFFERENCE DISPLAY '** ON SIZE ERROR **' END-MULTIPLY § § Format 1 4 The values of the operand preceding the word BY is multiplied by the operand after the word BY Format 2 4 The value of the operand after the word GIVING is replaced by the multiplication of ITEM-1 BY ITEM-2 4 None of the values in the operands preceding GIVING are changed 30
Arithmetic Statements – DIVIDE – Common Usage and DIVIDE Formats § WORKING-STORAGE SECTION. 01 INPUT-FIELDS. 05 ITEM-1 PIC S 9(3)V 99 VALUE 85. 52. 05 ITEM-2 PIC S 9(3)V 99 VALUE 2. 34. 05 ITEM-3 PIC S 9(3)V 99 VALUE 6. 01. 05 RESULT PIC S 9(5)V 99. PROCEDURE DIVISION. DIVIDE ITEM-1 INTO ITEM-3 ROUNDED ON SIZE ERROR MOVE 0 TO DIFFERENCE END-DIVIDE ITEM-1 INTO ITEM-2 GIVING RESULT ROUNDED ON SIZE ERROR MOVE 0 TO DIFFERENCE DISPLAY '** ON SIZE ERROR **' END-DIVIDE ITEM-1 BY ITEM-3 ROUNDED REMAINDER ITEM-3 END-DIVIDE ITEM-1 INTO ITEM-2 GIVING RESULT ROUNDED REMAINDER ITEM-3 END-DIVIDE § Five separate Formats for DIVIDE (see Slide Notes) 31 Rounded 4 Rounds to the decimal digits in the PIC clause § ON SIZE ERROR 4 Allows you to handle arithmetic overflow conditions with imperative statements. § Additional note: You Additional note: can substitute a numeric literal for the variables in the DIVIDE, BY and INTO, (but not GIVING) INTO GIVING clauses in the statement
Arithmetic Statements – COMPUTE WORKING-STORAGE SECTION. … 01 INPUT-FIELDS. 05 ITEM-1 PIC S 9(3)V 99 VALUE 85. 52. 05 ITEM-2 PIC S 9(3)V 99 VALUE 2. 34. 05 ITEM-3 PIC S 9(3)V 99 VALUE 6. 01. 05 RESULT PIC S 9(5)V 99. PROCEDURE DIVISION. … COMPUTE RESULT ROUNDED = (ITEM-1 * ITEM-2 / ITEM-3). Note: Blanks (the white space) between elements of your equation are significant with COMPUTE. For example : Compute celsius rounded = (5/9) * (fahrenheit - 32). (fahrenheit Compute celsius rounded = ( 5 / 9 ) * (fahrenheit - 32). (fahrenheit --- will not work --- will work § The COMPUTE statement assigns the value of an arithmetic (think algebraic) expression to one or more data items. § It allows you to combine arithmetic operations without the restrictions on receiving data items that the rules for the ADD, SUBTRACT, MULTIPLY, and ADD, SUBTRACT, MULTIPLY, DIVIDE statements impose. § When you need to combine arithmetic operations, using the COMPUTE statement may be more efficient than writing a series of separate arithmetic statements. § You may use any of the arithmetic operators shown on the next slide inside a compute statement § Additionally, you can combine COMPUTE with COBOL intrinsic functions 32
COMPUTE Arithmetic Operators § Use the above arithmetic operators to in your COMPUTE statements § The operations proceed as follows: 4 Unary Operators 4 Multiplication/Division/Exponentiation 4 Addition/Subtraction … from left to right within the COMPUTE – and following the order of parenthesis § Thus, it's always a good idea to force an explicit arithmetic order of precedence using parenthesis in COMPUTE statements 4 These two statements are not algebraically equivalent: COMPUTE RESULT ROUNDED = (ITEM-1 * ITEM-2 + ITEM-3). COMPUTE RESULT ROUNDED = (ITEM-1 * (ITEM-2 + ITEM-3)). 33
Intermediate Results of Fixed Point Math From the IBM Enterprise COBOL Programmer's Guide - Document Number: SC 23 -8529 -00 § § § The compiler handles arithmetic statements as a succession of operations performed according to operator precedence, and sets up intermediate fields to contain the results of those operations. The compiler uses algorithms to determine the number of integer and decimal places to reserve. Intermediate results are possible in the following cases: 4 4 4 § In an ADD or SUBTRACT statement that contains more than one operand immediately after the verb In a COMPUTE statement that specifies a series of arithmetic operations or multiple result fields In an arithmetic expression contained in a conditional statement or in a reference-modification specification In an ADD, SUBTRACT, MULTIPLY, or DIVIDE statement that uses the GIVING option and multiple result fields In a statement that uses an intrinsic function as an operand The precision of intermediate results also depends on whether you compile using the default option ARITH(COMPAT) or using ARITH(EXTEND) Net: 4 Because of the effect of the intermediate results on your arithmetic calculations can produce incorrect results (mostly truncation errors) 4 And because the above list is a lot to remember (and is actually only the entry point into the topic)! 4 You can – and should follow these simple rules-of-thumb: § § Be particularly careful to define your numeric datatypes to the precision necessary for your requirements When using literals in your calculations always add the necessary decimal digits of precision to them, in order to force the compiler to create intermediate results to your level of requirements Example: Instead of: COMPUTE FIELD-1 ROUNDED = 100 * (32. 78 / 1000). § Include decimal places in your literals: COMPUTE FIELD-1 ROUNDED = 100. 000 * (32. 78 / 1000. 000). 34
Lab Assignment From the course workshop documents, do the following labs – create and debug COBOL program that calculates simple interest based on the following variables amount principal interest nbr. Years PIC 9(7)V 99. PIC 9(2)V 99. PIC 9(4) COMP. //Business logic – in pseudo-code. //Initialize values amount = 0; principal = 10000. 01; interest =. 05; nbr. Years = 10; //Invoke simple interest calculation function calculate. Simple. Interest(); end function calculate. Simple. Interest() amount = principal * (1 + (nbr. Years * interest)); end 35
Unit COBOL General Language Rules Topics: § Assignment Statements and Internal Data Representation § Math Operations § Conditional Logic § Transfer of control § COBOL Looping Constructs § Sequential File Processing Patterns § Java and. NET Equivalents 36
COBOL Conditional Expressions § Two statement options: 4 IF/ELSE 4 EVALUATE statement § Both useful – and have many language patterns and options (you'll see ) § In general: 4 Use IF for coding: § Simple expressions § Conditional statements with tests against multiple fields § Complex statements – with tests against multiple fields 4 Use EVALUATE for: § Implementing "decision table" logic § Coding statements with multiple tests against a single field § Let's take a close look at both statements See Slide Notes 37
Conditional Statements – IF Statement Overview § IF statement has two operational modes: IF condition Alphanumeric compare: § On variables of type: – – ELSE Statement Block PIC X PIC A Group data items Alphanumeric literal § EBCDIC (or ASCII) value "byte-for-byte" comparison THEN Statement Block END-IF – Comparison proceeds from Left-to-Right – Alphanumeric range ( < or > ) is based on platform's collating sequence § Shorter fields are padded with spaces (HEX '40') to length of longer variable HEX '40 the – Regardless of which side of the IF statement is shorter/longer Numeric comparison: § On variables of type PIC 9 or a numeric literal PIC 9 § Algebraic compare § Decimal positions automatically aligned § Note that overall, the IF statement comparison values must be "data type compatible" 38
IF Statement Examples Simple IF - No ELSE IF/ELSE Note – matching END-IF for each END-IF IF/ELSE "Nested" IF/ELSE Nested IF/ELSE refactored as IF with AND connectors Note – only one END-IF IF POLICY-OVERDUE-DAYS > 90 ADD +100 TO AMT-DUE END-IF ___________________________________ IF EMPLOYEE-SALARY-TYPE = "H" PERFORM 400 -PROCESS-HOURLY-PAY ELSE IF EMPLOYEE-SALARY-TYPE = "S" PERFORM 400 -PROCESS-SALARIED-PAY ELSE MOVE "***" TO EMPLOYEE-SALARY-TYP ADD +1 TO ERRORS-FOUND-KTR END-IF ___________________________________ IF HOURS-WORKED > 40 IF HOURLY-EMPLOYEE = "Y" IF NO-ERRORS-FOUND PERFORM 900 -CALCULATE-HOURLY-OT END-IF ___________________________________ IF HOURS-WORKED > 40 AND HOURLY-EMPLOYEE = "Y" AND NO-ERRORS-FOUND PERFORM 900 -CALCULATE-HOURLY-OT END-IF 39
COBOL Conditional Statements – IF Statement Overview § § Condition may be simple or complex (> 1 simple condition) There are five simple conditions, which have a truth value of either true or false: 1. Class condition: § 2. Condition-name condition: § 3. 4. 88 -LEVEL Data Items Relation condition (value-based comparisons) Sign condition § 5. ALPHABETIC, NUMERIC, ALPHABETIC-UPPER POSITIVE, NEGATIVE, ZERO Switch-status condition – used with SPECIAL NAMES (rare) § Use Content-Assist (Ctrl/Spacebar) to view options § A complex condition is formed by combining simple conditions, combined conditions, and/or complex conditions with logical operators, or negating these conditions with logical negation: 4 AND 4 OR 4 NOT If complex condition, comparisons proceed from Left-to-Right: 4 But you can (and most of the time should) specify your own comparison operation precedence by surrounding separate conditions with parenthesis to make the logic apparent § § To humans who read/maintain your code, as well as to the compiler 40 See Notes
IF/ELSE – Examples – and See Slide Notes IF/ELSE FILE SECTION … 01 OUT-REC PIC X(80). … WORKING-STORAGE SECTION. 77 ITEM-1 PIC X(12). 77 ITEM-2 PIC X(15). 77 ITEM-3 PIC 9(05). 88 VALID-ITEM VALUES ARE 11111, 22222. … PROCEDURE DIVISION. Simple IF ITEM-1 > "10" Relation Condition MOVE "X" TO ITEMB ELSE PERFORM PROC-A END-IF Complex IF ITEM-1 > "10" Nested IF Relation IF ITEM-1 = ITEM-2 Condition ADD 1 TO ITEM-3 MOVE ALL "X" TO OUT-REC END-IF MOVE "X" TO ITEM-2 END-IF IF ITEM-1 NUMERIC Class Condition MOVE ITEM-1 TO ITEM-3 END-IF IF VALID-ITEM Condition-Name Condition MOVE ITEM-2 TO ITEM-1 ELSE MOVE FUNCTION UPPER-CASE(ITEM-2) TO ITEM-1 END-IF Complex Nested IF IF ( ITEM-3 IS POSITIVE ) AND Relation ( ITEM-1 NOT > ITEM-2 ) Condition THEN IF ITEM-3 = 22222 THEN DISPLAY "22222 -RECORD" ELSE DISPLAY "11111 -RECORD" END-IF ELSE DISPLAY "BAD RECORD" END-IF IF NOT (ITEM-3 < 10 OR ITEM-3 > 500) AND ITEM-1 <= "Z" Complex Nested IF THEN DISPLAY "Done" Condition END-IF Combing OR/AND 41
Implied IF Condition Statements IF ITEM-1 NUMERIC AND > 10000 MOVE ITEM-1 TO ITEM-3 END-IF IF ITEM-2 = "AABBCC" OR "AACCDD" Example: OR "AADDEE" IF EMPLOYEE-ID > 20 MOVE ITEM-2 TO ITEM-1 AND EMPLOYEE-ID < 3000 ELSE MOVE FUNCTION UPPER-CASE(ITEM-2) Can be coded as: TO ITEM-1 IF EMPLOYEE-ID > 2000 AND < 3000 END-IF § When referring to the same field on both sides of a compound condition, you do not have to repeat the variable name § There is no hard and fast rule (or even rule-of-thumb) on this coding idiom. IF NOT (ITEM-3 < 10 OR > 500) AND ITEM-1 <= "Z" THEN DISPLAY "Done" END-IF 4 Pluses: § Creates more compact easily code § Can be more easily readable Examples of implied IF statement conditions 4 Minuses § Written semantics are not as exact and explicit – Many modern languages do not permit this § Might be misunderstood if merely browsing or scanning code 42
Bypassing Conditional Logic (NEXT SENTENCE and NEXT SENTENCE CONTINUE) CONTINUE § There are two standard ways for you to skip over logic in a complex IF statement that you must avoid as per business requirements § Code (after the if condition) either: IF ITEM-2 ALPHABETIC-UPPER NEXT SENTENCE ELSE MOVE FUNCTION UPPER-CASE(ITEM-2)TO ITEM-1 ADD +10 TO AMOUNT-SUB-TOTAL END-IF ADD +1 TO REC-KTR ADD REC-TOTAL TO WS-TOTAL-CLAIMS-PYMNTS WRITE OUTPUT-RECORD FROM WS-OUT-REC. 4 NEXT SENTENCE – which branches to the next sequential statement after an ending period …or… 4 CONTINUE – which branches to the next sequential statement after an ending period – OR the IF statement's scope terminator. GOBACK. § An important distinction – to be sure 4 Because NEXT SENTENCE is looking for the next physical period in the source – and scope-terminators/indentation mean nothing whatsoever to it, you will probably want to use: CONTINUE – if you're coding style is to use scope-delimiters (a best practice). 4 Note also that, when you're coding new programs this is not as problematic as when you are maintaining existing COBOL applications What if I want to bypass more than the current logic statement block? See Slide Notes IF ITEM-2 ALPHABETIC-UPPER CONTINUE ELSE MOVE FUNCTION UPPER-CASE(ITEM-2)TO ITEM-1 ADD +10 TO AMOUNT-SUB-TOTAL END-IF ADD +1 TO REC-KTR ADD REC-TOTAL TO WS-TOTAL-CLAIMS-PYMNTS WRITE OUTPUT-RECORD FROM WS-OUT-REC. GOBACK. 43
Conditional Statements – EVALUATE Statement § The EVALUATE statement is COBOL's version of the (in other programming languages) "case" or "switch) statement. § EVALUATE provides a shorthand notation for a series of nested IF statements. § When your program has to test a single variable for more than two values, EVALUATE is probably a better choice than nest IF 4 See next slide § EVALUATE parses a variable value § WHEN is used as the condition expression EVALUATE Statement WHEN condition TRUE Statement Block WHEN condition … 4 You can a single WHEN condition 4 You can use multiple WHEN statements when several WHEN conditions lead to the same processing action OTHER 4 You can use a WHEN <value> THRU <value> phrase to easily code several conditions in a range of values 4 You can specify "TRUE" or "FALSE" as the testing TRUE FALSE criteria – and can combine with "ALSO" ALSO END-EVALUATE 44 TRUE Statement Block
EVALUATE versus Nested IF Statement Comparison Example 1 IF CARPOOL-SIZE = 1 THEN MOVE "SINGLE" TO PRINT-CARPOOL-STATUS ELSE IF CARPOOL-SIZE = 2 THEN MOVE "COUPLE" TO PRINT-CARPOOL-STATUS ELSE IF CARPOOL-SIZE >= 3 and CARPOOL-SIZE <= 6 THEN MOVE "SMALL GRP" TO PRINT-CARPOOL-STATUS ELSE MOVE "BIG GRP" TO PRINT-CARPOOL-STATUS END-IF IF MARITAL-CODE = "M" THEN ADD 2 TO PEOPLE-COUNT ELSE IF MARITAL-CODE = "S" OR MARITAL-CODE = "D" OR MARITAL-CODE = "W" THEN ADD 1 TO PEOPLE-COUNT END-IF EVALUATE CARPOOL-SIZE WHEN 1 MOVE "SINGLE" TO PRINT-CARPOOL-STATUS WHEN 2 MOVE "COUPLE" TO PRINT-CARPOOL-STATUS WHEN 3 THRU 6 MOVE "SMALL GRP" TO PRINT-CARPOOL STATUS WHEN OTHER MOVE "BIG GRP" TO PRINT-CARPOOL STATUS END-EVALUATE Example 2 EVALUATE MARITAL-CODE WHEN "M" ADD 2 TO PEOPLE-COUNT WHEN "S" WHEN "D" WHEN "W" ADD 1 TO PEOPLE-COUNT END-EVALUATE 45
Conditional Statements – EVALUATE – Complex Examples EVALUATE FILE SECTION … 01 OUT-REC PIC X(80). … Working-Storage Section. 01 Age PIC 999. 01 Sex PIC X. 01 Description PIC X(15). 01 A PIC 999. 01 B PIC 9999. 01 C PIC 9999. 01 D PIC 9999. 01 E PIC 99999. 01 F PIC 999999. Evaluate True Also True When Age < 13 Also Sex = "M" Move "Young Boy" To Description When Age < 13 Also Sex = "F" Move "Young Girl" To Description When Age > 12 And Age < 20 Also Sex = "M" Move "Teenage Boy" To Description When Age > 12 And Age < 20 Also Sex = "F" Move "Teenage Girl" To Description When Age > 19 Also Sex = "M" Move "Adult Man" To Description When Age > 19 Also Sex = "F" Move "Adult Woman" To Description When Other Move "Invalid Data" To Description End-Evaluate True Also True When A + B < 10 Also C = 10 Move "Case 1" To Description When A + B > 50 Also C = ( D + E ) / F Move "Case 2" To Description When Other Move "Case Other" To Description End-Evaluate "True ALSO True" means that both conditions in the WHEN clause must be true to take the WHEN path 46
Lab Assignment From the course workshop documents, do the following labs: 1. Conditionals Lab 47
Unit COBOL General Language Rules Topics: § Assignment Statements and Internal Data Representation § Math Operations § Conditional Logic § Transfer of control § COBOL Looping Constructs § Sequential File Processing Patterns § Java and. NET Equivalents 48
Topic objectives By the end of this unit you should § Understand how the PERFORM can be used to transfer control to block of code contained in a paragraph or section. . § Know how to use the PERFORM. . THRU and the GO TO and understand the restrictions placed on using them. § Understand the difference between in-line and out-of-line Performs 49
COBOL Transfer of Control Options § Three keywords used to transfer control in traditional COBOL PERFORM § Branches to the first statement in a block of code – Inline – Or, organized in a labeled paragraph or section somewhere else in the PROCEDURE DIVISION § At the end of the performed code, control is automatically returned to the next sequential instruction following PERFORM § PERFORM is a statement with a number of useful options and extensions GO TO § Unconditional branch to a labeled paragraph or section § All statements are executed at that point in time – forward in the program CALL § Invoke another COBOL program § Pass parameters with a USING statement § We will discuss CALL in a future section of this course § Of the above three options: 4 PERFORM and CALL are best practices for "structured programming" PERFORM CALL 4 GO TO is not a best practice, but we will present it, as you will see many GO TO examples of GO TO in production COBOL, and need to understand it GO TO 50
PERFORM – External Paragraph or Section § Structured coding method of branching to – and returning from COBOL paragraphs or sections § With PERFORM, the compiler automatically returns PERFORM control to the "next sequential instruction" after the block of statements in the paragraph or section ends 4 This makes the program's flow of control easy to read, easy to understand easy to maintain 4 Less worry about "fall thru" logic § PERFORM 4 May be nested: § This is known as a "PERFORM chain" – or a series of PERFORM and return branches controlled by the Operating System at run-time. 4 May NOT be recursive: § In this example, within 200 -OPEN-FILES you may not PERFORM 100 -HOUSEKEEPING 4 Does not depend on physical placement or ordering in the source files: § Although it can help from a read-ability standpoint to PERFORM paragraphs lower (down) in the PERFORM program listing. 4 Allows you do "divide and conquer" the design and development of large complex applications. § Do not scope external paragraph PERFORM with END-PERFORM 51 PROCEDURE DIVISION. PERFORM 100 -HOUSEKEEPING. PERFORM 300 -MAINLINE-RTN. PERFORM 500 -CLEANUP. GOBACK. 100 -HOUSEKEEPING. PERFORM 150 -INITIALIZE-FIELDS. PERFORM 200 -OPEN-FILES. PERFORM 800 -READ-RTN. 150 -INITIALIZE-FIELDS. … 200 -OPEN-FILES. … 300 -MAINLINE-RTN. PERFORM 400 -PROCESS-RECORD. PERFORM 700 -WRITE-RTN. PERFORM 800 -READ-RTN. 400 -PROCESS-RECORD. … 500 -CLEANUP. PERFORM 900 -CLOSE-FILES. … 700 -WRITE-RTN. …
PERFORM THRU § One variation on PERFORM is PERFORM … THRU § PERFORM … THRU allows you to explicitly PERFORM … THRU mark & bound the end of the PERFORM chain with a labeled paragraph § All of the procedural statements between: PERFORM <paragraph. Name> PERFORM and THRU <paragraph. Name> THRU …are executed § The best practice is for the exit paragraph to have one COBOL reserved word in it: EXIT 4 This returns control to the next sequential instruction in the perform chain § Technically, you could PERFORM a COBOL paragraph THRU any other paragraph. However, this often leads to complex and unstructured code 4 Difficult to understand maintain § So the convention is to PERFORM THRU a single paragraph EXIT (as shown) 52 PROCEDURE DIVISION. PERFORM 100 -HOUSEKEEPING THRU 100 -EXIT. PERFORM 300 -MAINLINE-RTN THRU 300 -EXIT. PERFORM 500 -CLEANUP THRU 500 -EXIT. GOBACK. 100 -HOUSEKEEPING. PERFORM 150 -INITIALIZE-FIELDS THRU 150 -EXIT. PERFORM 200 -OPEN-FILES THRU 200 -EXIT. PERFORM 800 -READ-RTN THRU 800 -EXIT. 100 -EXIT. 150 -INITIALIZE-FIELDS. … 150 -EXIT. 200 -OPEN-FILES. … 200 -EXIT. … See Slide Notes
Inline PERFORM § Another variation on PERFORM is what's known as an "inline perform" § An inline PERFORM allows you to encase COBOL statements and business logic within a structured statement block – which you can group or loop through (looping is the next topic, but Inline PERFORM is often used to control loops. PERFORM <statement> … PROCEDURE DIVISION. PERFORM UNTIL END-OF-FILE IF NOT END-OF-FILE PERFORM 800 -READ-INPUT-FILE IF NOT END-OF-FILE MOVE INPUT-REC TO OUTPUT-REC PERFORM 900 -WRITE-RECORD ELSE MOVE HIGH-VALUES TO INPUT-REC PERFORM 1000 -CLOSE-FILES DISPLAY 'NORMAL EOJ END-IF END-PERFORM. … PERFORM VARYING IDX FROM 1 BY 1 UNTIL IDX > 100 MOVE REC-IN TO REC-TABLE(IDX) END-PERFORM. § An in-line PERFORM must be delimited by the END-PERFORM phrase. 53 …
Scope Terminators and Paragraph Names § You have seen that many of the COBOL statements can have Scope Terminators: 4 END-IF 4 END-READ 4 END-COMPUTE 4… 100 -HOUSEKEEPING. … IF ITEM-2 = "AABBCC" OR "AACCDD" OR "AADDEE" MOVE ITEM-2 TO ITEM-1 ELSE MOVE ITEM-3 TO ITEM-1 END-IF 100 -EXIT. This will not compile! EXIT. § This is actually a coding best practice § However, the last statement before the paragraph (or "exit paragraph") must end in a period. 54 Type a period after END-IF 100 -HOUSEKEEPING. … IF ITEM-2 = "AABBCC" OR "AACCDD" OR "AADDEE" MOVE ITEM-2 TO ITEM-1 ELSE MOVE ITEM-3 TO ITEM-1 END-IF. 100 -EXIT.
GO TO – Unconditional Transfer of Control § GO TO branches to the paragraph or section label after the statement. 4 With no automatic, compiler-managed return to the next sequential instruction 4 Ergo all subsequent statements "fall through" § This can create what is termed "spaghetti code" – which is typically § Difficult to read § Very difficult to maintain and modify § The use of GO TO is universally denounced in the academic computing world 4 And we agree – except for under one very key and common design pattern (combining GO TO with PERFORM … THRU) PERFORM … THRU § Our "Best Practices" advice: 4 Do not use GO TO in COBOL coding, for transferring control § EXCEPT under one condition – when you are using GO TO - for branching to the exit paragraph in a PERFORM … THRU 4 This honors the Perform Chain and execution will not "fall through" 55 PROCEDURE DIVISION. PERFORM 100 -HOUSEKEEPING THRU 100 -EXIT. PERFORM 300 -MAINLINE-RTN THRU 300 -EXIT. GOBACK. 100 -HOUSEKEEPING. PERFORM 200 -OPEN-FILES THRU 200 -EXIT. PERFORM 800 -READ-RTN THRU 800 -EXIT. IF END-OF-FILE DISPLAY "END-OF-JOB" PERFORM 900 -CLOSE FILES THRU 900 -EXIT GO TO 100 -EXIT ELSE ADD +1 TO REC-KTR MOVE ZEROS TO AMOUNT-TOT END-IF Perform 300 -INIT-FIELDS. 100 -EXIT. …
Transfer of Control Best Practices § We will cover structured COBOL programming and logic patterns and design in one of the upcoming units, but for now, consider the following: 4 Structure your program as a chain of PERFORM THRU paragraphs PERFORM 4 Within the paragraphs code anything you need to satisfy your business logic requirements, including: § § § CALLs to external programs – CALL is covered in an upcoming unit CALL Nested PERFORM Inline PERFORM Sequence and conditional logic GO TO – BUT ONLY GO TO a PERFORM THRU paragraph EXIT 4 Try not to use COBOL SECTIONs SECTION § Within COBOL SECTIONs – COBOL paragraphs are considered at the level of SECTION statements – blocks of code where fall through will occur § The only time you will need a COBOL SECTION is when you're programming is invoking the COBOL SORT verb (which is tied to INPUT and OUTPUT SORT SECTIONs) SECTION 56
Unit COBOL General Language Rules Topics: § Assignment Statements and Internal Data Representation § Math Operations § Conditional Logic § Transfer of control § COBOL Looping Constructs § Sequential File Processing Patterns § Java and. NET Equivalents 57
Topic objectives By the end of this unit you should § Be able to use the PERFORM. . TIMES. § Understand how the PERFORM. . UNTIL works and be able to use it to implement while or do/repeat loops. § Be able to use PERFORM. . VARYING to implement counting iteration such as that implemented in other languages by the for construct. 58
COBOL Looping Options § There are three COBOL programming ways to loop: 4 GO TO <paragraph. Name> combined with an IF condition that ends the loop: § Unstructured – creates complex, un-maintainable code § NOT a best practice – hence will not be covered 4 PERFORM <paragraph. Name> n TIMES § Structured and simple to understand § But only applicable in cases where the number of loop iterations is known at design time 4 PERFORM <paragraph. Name> UNTIL a condition is met § Structured ("Good") § Can be used when the number of loop iterations is variable or known § Net: Use PERFORM <paragraph. Name> UNTIL for your COBOL looping requirements. § When do you need to loop in your COBOL programs? 4 Reading/Writing a file until no more records 4 Looping through rows returned from a database 4 Loading a COBOL internal table 4 Processing a COBOL table sequentially 4 Calculations 4 Algorithms …in general – you will write few programs that don't loop 59
PERFORM <paragraph. Name> n TIMES § Can PERFORM a paragraph a specified number of times, in a loop controlled by a: 4 Numeric literal 4 Numeric integer variable WORKKING-STORAGE SECTION. 77 NBR-REPS S 9(4) COMP. PROCEDURE DIVISION. … PERFORM 300 -MAINLINE-RTN THRU 300 -EXIT 12 TIMES. § Examples: 4 Performs all of the COBOL statements between 300 -MAINLINE-RTN and 300 -EXIT 12 TIMES GOBACK. 300 -MAINLINE-RTN. … MOVE IN-REC-KTR TO NBR-REPS. PERFORM 310 -SUBTOTALS THRU 310 -EXIT NBR-REPS TIMES. … 4 Performs all of the COBOL statements between 310 -SUBTOTALS and 310 -EXIT the number of times represented by the integer value in NBR 300 -EXIT. -REPS Use PERFORM … n TIMES – when you know PERFORM … n TIMES during development how many loop iterations should be performed at run-time. 60
PERFORM UNTIL <condition> PROCEDURE DIVISION. PERFORM 100 -HOUSEKEEPING THRU 100 -EXIT. § Structured method of looping when you only know at run-time how many times the loop should be iterated over PERFORM 300 -MAINLINE-RTN § UNTIL GOBACK. 4 Tests a condition for TRUE/FALSE § If NOT TRUE (repeat – if the condition is FALSE) PERFORM the specified Paragraph § If TRUE – End the loop – Return program control to the next sequential instruction following the PERFORM UNTIL statement § Additional notes: 4 If the UNTIL condition never becomes true? § Infinite loop – If the program is batch, the TIME= parameter on the JCL will most likely cancel it – If the program is an online transaction, the operator will cancel it – Either way, this is not a good thing § There actually two additional options for PERFORM UNTIL (next slide) 61 THRU 300 -EXIT UNTIL NO-MORE-RECORDS. 100 -HOUSEKEEPING. OPEN INPUT IN-FILE. PERFORM 800 -READ-RTN THRU 800 -EXIT. 100 -EXIT. 300 -MAINLINE-RTN. … PERFORM 800 -READ-RTN. 300 -EXIT. 800 -READ-RTN. READ IN-FILE INTO WS-RECORD AT END MOVE 'Y' TO SW-NO-MORE-RECORDS. 800 -EXIT.
PERFORM UNTIL – With TEST BEFORE or AFTER § PERFORM …UNTIL may be modified by one of two clauses, coded before UNTIL and after the paragraph name: 1. WITH TEST BEFORE § The UNTIL condition is tested before each PERFORM execution. § The Paragraphs will be executed 0 or more times § Is the default – if this clause is left unspecified 2. WITH TEST AFTER § The UNTIL condition is tested after each PERFORM execution. § The Paragraphs will be executed 1 or more times 62 PROCEDURE DIVISION. PERFORM 100 -HOUSEKEEPING THRU 100 -EXIT. PERFORM 300 -MAINLINE-RTN THRU 300 -EXIT WITH TEST BEFORE UNTIL NO-MORE-RECORDS. GOBACK. 100 -HOUSEKEEPING. OPEN INPUT IN-FILE. PERFORM 800 -READ-RTN THRU 800 -EXIT. 100 -EXIT. 300 -MAINLINE-RTN. … PERFORM 800 -READ-RTN. 300 -EXIT. 800 -READ-RTN. READ IN-FILE INTO WS-RECORD … 800 -EXIT.
Lab Assignment From the course workshop documents, do the following labs: 1. COBOL Looping Lab 63
Unit COBOL General Language Rules Topics: § Assignment Statements and Internal Data Representation § Math Operations § Conditional Logic § Transfer of control § COBOL Looping Constructs § Sequential File Processing Patterns § Java and. NET Equivalents 64
Topic objectives This topic covers basic (simple) sequential file processing – patterns: 4 Open files 4 Read an initial record from the input file 4 Process all records until end-of-input-file § § Edit and validate data Compute totals, subtotals and accumulators Write output records Read the next input file record 4 Close files and end the job § In subsequent topics of this course, we will dive much more deeply into file handling, as a majority of COBOL batch processing depends on concepts and coding patterns that are variations of the above § We will also touch on the basic batch program design patterns you will want to use going forward in this course and later in your production COBOL work By the end of this chapter you will be able to: § OPEN, READ, WRITE and CLOSE files § Loop through and input file, processing all of the records until completed 65
Sequential File Processing § Sequential File Processing consists of a well-documented set of processing – or a pattern that you will see in many program requirements 4 You read one or more input files until: § Your business logic requirements are fulfilled § End-of-File 4 While reading files you typically: § § Edit or evaluate data Add numeric values to total and sub-total fields – perform business calculations Assign (MOVE) values WRITE output record(s) – either to an output file, report or both 4 You must be cognizant of: § Bad or invalid data (and know what to do about it when it shows up in your fields) § Empty input files § READ/WRITE I/O errors that may occur 4 After reaching end-of-file you will typically: Input File Note - more than likely NOT a tape Device COBOL Program Business Logic 66 Record Buffer WRITE a final output record, with summary computed values CLOSE all files DISPLAY a successful end-of-job message Record Buffer § § § Output Report Output File
Sequential File Processing Pattern – Simple Batch Design Pattern This first batch application pattern "Process One Input File" – consists of the following pattern § Perform an initialization routine 4 Initialize values in Working-Storage 4 OPEN the files – for either input or output 4 PERFORM a "priming" input-record read – an initial read statement that simplifies: § Empty input-file-processing problems § Reading past end-of-file logic problems § Perform a process-the-file routine, until end-of-input-file 4 Validate the data – using the conditional logic statements learned in this unit 4 Move the data – using the assignment statements learned in this unit 4 Do computations, calculations, etc. – using the COBOL math statements 4 Write the record 4 Read the next input record § Perform an end-of-job routine 4 Complete final computations 4 WRITE final output record with final computations 4 CLOSE all files and display an end-of-job message on the Console 67
File I/O Review – OPEN … ENVIRONMENT DIVISION. External Device INPUT-OUTPUT SECTION. External File SELECT INTFILENAME ASSIGN TO … … DATA DIVISION. FILE SECTION Record Buffer FD INTFILENAME… 01 OUT-REC. … Recall the following: PROCEDURE DIVISION. 4 SELECT/ASSIGN connects your … internal (logical) filename with external (physical) file-spec 4 FILE SECTION is required for each SELECT/ASSIGN file 4 OPEN references the logical (internal) filename 4 Can OPEN multiple files with one statement (as shown) OPEN INPUT FILE 1, FILE 2 OUTPUT FILE 3, FILE 4. … § Note carefully the syntax for OPEN See Slide Notes, for additional learning content 68
File I/O Review – READ INTO ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. SELECT INTFILENAME ASSIGN TO … DATA DIVISION. FILE SECTION FD INTFILENAME … Record Buffer 01 IN-REC. WORKING-STORAGE SECTION 01 IN-REC-WS. 01 END-OF-FILE-FLAG PIC X. PROCEDURE DIVISION. OPEN INPUT INTFILENAME. READ INTFILENAME INTO IN-REC AT END MOVE ‘Y’ to END-OF-FILE-FLAG. … Recall the following: 4 File must be OPEN before you try to READ from it 4 READ retrieves each record from an external file: - Into the record specified in your FILE SECTION External Device External File F I L E R E A D See Slide Notes, for additional learning content * Note that the DATA DIVISION's FILE SECTION is sometimes referred to as an I/O "buffer" - Into WORKING-STORAGE - if you've coded READ INTO 4 AT END condition occurs after the last record is READ from the file - If you attempt to read past end-of-file your program will ABEND 69
File I/O Review – WRITE FROM ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. SELECT OUTFILENAME ASSIGN TO … DATA DIVISION. FILE SECTION FD OUTFILENAME… Record Buffer 01 OUT-REC. WORKING-STORAGE SECTION 01 OUT-REC-WS. PROCEDURE DIVISION. OPEN OUTPUT OUTFILENAME. External Device External File W R I T E O P E R A T I O N WRITE OUT-REC FROM OUT-REC-WS. … Recall the following: 4 File must be OPEN before you try to WRITE a record to it - An ABEND condition occurs, if try to write to an un-opened file 4 WRITE creates a new record at the end of a sequential/external file: - From the record specified in your FILE SECTION - From WORKING-STORAGE - if you've coded WRITE FROM 4 Close opened output files before your program ends 70 See Slide Notes, for additional learning content
File I/O Review – CLOSE ENVIRONMENT DIVISION. F I INPUT-OUTPUT SECTION. L E SELECT INTFILENAME ASSIGN TO … C L … O S DATA DIVISION. E FILE SECTION Record Buffer FD INTFILENAME… 01 OUT-REC. … PROCEDURE DIVISION. Recall the following: … External Device External File 4 CLOSE every opened file CLOSE FILE 1, FILE 2, FILE 3, FILE 4. - Input file - Output file 4 Can CLOSE multiple files with one statement (as shown) 4 Can re-OPEN a file after closing … § Note carefully the syntax for CLOSE See Slide Notes, for additional learning content 71
Sequential File Processing Pattern – Pseudo-Code § In a subsequent unit of this course we will cover the concept of design and programming patterns with COBOL § For now, here is your first simple, sequential file-handling pattern, in pseudo-code. § Study the control-flow to understand the paragraph PERFORM process, and purpose of each statement block § Tie this back to the code you the previous slide in this unit. § What is not part of this processing pattern are the actual details of the: 4 Data Validation 4 Calculations and computations … which can be extremely complex and will most likely take up the majority percentage of your coding cycles. § There are other algorithms that can do the same sequential process, but we feel this is a simple, easy-to-read/maintain/debugsupport/and extend approach 72 PROCEDURE DIVISION. Do Init-Routine Do Process-Files until No-More-Data Do End-of-Job-Routine GOBACK. Init-Routine. Open files READ Input-File Process-Files. Validate input data Perform calculations and sub-totals Move data to output Record Write Output-Record READ Input-File End-of-Job-Routine. Final computations Move Data to output Record Write output record Close Files
Putting it All Together - A Complete Example of a Sequential File Processing Program § Read through (study) the code in this sample small sequential file processing program. 4 Trace the concepts, COBOL syntax and statement semantics learned in this, and the previous Unit to the actual code in this program. 4 Feel free to refer-back to your slides, the course supplemental text or your notes – if necessary Select External File Assign to COBOL (internal) file name FILE SECTION FDs Matching the SELECT/ASSIGN Clauses for each external file Note – this example continues over the next three slides 73
A Complete Example of a Sequential File Processing Program – WORKING-STORAGE SECTION File Status fields Automatically updated By COBOL and the O. S. A final-totals output record Input and Output records You will often see these coded in WORKINGSTORAGE because they are easier to find in a System log file (called a DUMP file) if your program files (ABENDS) when executing on the mainframe Holding fields for intermediate result calculations and values 74
A Complete Example of a Sequential File Processing Program – PROCEDURE DIVISION E D I T S Processing • Calculations • Computations Our Sequential File Pattern – in COBOL M O V E Read the code line-by-line (as if you were debugging it – In other words, if there's a PERFORM – jump down to the Performed paragraph. When finished jump back, etc. ) Note the use of: • PERFORM THRU • AT END/GO TO "EXIT" • PERFORM UNTIL • For each record in the input file, do 100 -MAINLINE Write the current record Read the next record in the file 75
A Complete Example of a Sequential File Processing Program – No More Records in the File § When there are no more records left to process 4 Do final calculations 4 Move the fields to final output record 4 WRITE 4 CLOSE all files 4 Display a message on the console 76
Lab Assignment From the course workshop documents, do the following labs: 1. Process Input File 1 2. Process Input. File 2 77
Unit COBOL General Language Rules Topics: § Assignment Statements and Internal Data Representation § Math Operations § Conditional Logic § Transfer of control § COBOL Looping Constructs § Reading and Writing Files - Review § Java and. NET Equivalents 78
Java. NET COBOL Equivalents COBOL JAVA VB. NET MOVE (elementary field) Java variable assignment (right to left) Variable assignment (right to left) MOVE (group field move) Java OBJECT assignment (right to left) Variable assignment (right to left) MOVE CORRESPONDING N/A MOVE with OF qualifier Qualified assignment var 1. var 2. var 3 ADD Standard math computation (no separate statement) SUBTRACT " " MULTIPLY " " DIVIDE " " COMPUTE " " IF/ELSE AND/OR If If EVALUATE case PERFORM Method invocation PERFORM THRU While or FOR – method invocation COBOL Paragraphs and Sections Java Labels Label GO TO Break/Continue can refer to a Label (same behavior as GO TO EXIT) PERFORM THRU UNTIL While or FOR – method invocation OPEN //comment, as Java opens files automatically OPEN() CLOSE Data. Input. Stream. close() CLOSE() WRITE Data. Input. Stream/Buffered. Input. Stream/File. Input. Stream. Writer/Binary. Writer READ Data. Input. Stream/Buffered. Input. Stream/File. Input. Stream. Reader/Binary. Reader ACCEPT Java. util. Scannner (System. in) Console. Read DISPLAY System. out. println Console. Write. Line – or Console. Write 79
2d142a3edd9d3a5e2a550ff6802900b6.ppt