8QSAM Files Unkeyed, Sequentially created and processed Records cannot change length or positionQSAM files on direct access storage can be modified with REWRITEENVIRONMENT DIVISION.FILE-CONTROL paragraphSELECTI-O-CONTOL paragraphAPPLY WRITE-ONLYDATA DIVISIONFILE SECTIONFD
10Environment Division - File Control SELECT file-name1OPTIONALASSIGN assignment-nameTO
11Environment Division File-CONTROL Optional – used for files opened in I-O, INPUT, or EXTEND. File doesn’t have to be present when the program is executed.File-name1 – identifies an FD entry (internal file name)Assignment-name – identifies the external file. If name component of the SELECT clause is found in the JCL it is treated as a DD name. If not found in the JCL, then “name” is treated an an environment variable
12QSAM File Name name label- S- Label – documents for the programmer the device and device class to which the file is assigned. No effect on execution. Must end with a dashS – Optional. Indicates sequential organization
14Exercise A (Dynamic Files) Statically allocate and read BCST.SICCC01.TESTPDS(DYNAMDAT)This file contains member names of other members in BCST.SICCC01.TESTPDSDynamically Read each member that is listed and display the records in each memberAfter you can display all the records, try writing out the records to a dynamically allocated fileUse BCST.SICCC01.PDSLIB(DYNAM2) to help you read a file dynamicallyUse BCSC.SICCC01.PDSLIB(DYNAM1) to help you write a file dynamically
15Environment Variables Defined as WORKING-STORAGE fields using value clauses01 FILE-ENV-VAR PIC X(39)VALUE “DYNFILE=DSN(INPUT.FILE) SHR”.Can be used to access QSAM files or existing VSAM clusters.
17RESERVE ClauseSpecifies the number of I/O buffers allocated the file at run-timeIf omitted, the number of buffers is taken from the DD statement. If none are specified, the system default is taken
18QSAM BufferingQSAM buffers can be allocated above the 16 MB line if all of the following are true:- Enterprise COBOL- z/OS Language Environment- the programs are compiled with RENT and DATA(31)orcompiled with NORENT and | RMODE(ANY)- the program is executing in AMODE 31- the program is executing on MVS- the ALL31(ON) run-time option is used (for EXTERNAL files)
19ORGANIZATION Clause (optional) ORGANIZATION IS SEQUENTIALOther non-QSAM options: INDEXED, RELATIVE, LINE SEQUENTIALRecords are read and written in a serial manner
20PADDING Clause PADDING data name CHARACTER IS literal Specifies a character for block padding on sequential filesData name – a one character fieldLiteral – a one character alphanumeric literal or national symbol
21ACCESS MODE Clause ACCESS SEQUENTIAL MODE IS Default mode is SEQUENTIALOptions for other types of files include RANDOM and DYNAMIC
22FILE STATUS Clause STATUS dname1 FILE IS dname2 - The operating system moves a value to dname1 and possibly dname2 after each I/O operation.dname1 - a two character alphanumeric or national fielddname2 – used for VSAM
23Environment Division I-O-CONTROL INPUT-OUTPUT SECTION.FILE-CONTROL.SELECT …I-O-CONTROL.APPLY WRITE-ONLY ON MYFILE.(Used for sequential variable blocked files.)
24Defining QSAM Files and Records FILE-CONTROL.SELECT CUSTOMER-MASTERASSIGN TO CUSTMASTORGANIZATION IS SEQUENTIALACCESS MODE IS SEQUENTIALFILE STATUS IS RC.
28EXTERNALThe EXTERNAL clause specifies that a file connector is external, permitting file sharing between two programs in the same run unit
29GLOBALGLOBAL clause specifies the file-connector name is available to the declaring program and all programs contained directly or indirectlyUsed for nested programs
30BLOCK CONTAINS BLOCK CONTAINS 0 RECORDS If this clause is omitted, records are unblocked by default!Allows the blocksize to be specified in the JCL or by the operating systemCode this Statement! (TSYS Standard)
31RECORD ClauseSpecifies the number of bytes in a record (fixed or variable)When omitted, the compiler determines lengths based on record descriptions.RECORD CONTAINS 80 CHARACTERSRECORD CONTAINS 50 TO 80 CHARACTERSRECORD IS VARYING IN SIZEFROM 40 TO 60 CHARACTERSDEPENDING ON REC-COUNT.
32RECORDING MODESpecifies the format of physical records in a QSAM file (ignored for VSAM)F – fixed size, V – variable size, U – unblocked, fixed or variable, S – spanned, large records that span a blockRECORDING MODE IS FRECORDING MODE IS VRECORDING MODE IS URECORDING MODE IS S
33DATA RECORD ClauseDATA RECORD clause identifies the data areas associated with the fileSyntax checked but is only documentationDATA RECORD IS INPUT-AREA.DATA RECORDS ARE INPUT-AREA1INPUT-AREA2
34FD Example FD IN-FILE IS GLOBAL RECORDING MODE F BLOCK CONTAINS 0 RECORDSLABEL RECORDS ARE STANDARDRECORD CONTAINS 80 CHARACTERSDATA RECORD IS IN-AREA.01 IN-AREA.05 …
35LABEL RECORDSLabel records are records written at the beginning and end of DASD and Tape files that provide information about fileEnterprise COBOL only supports standard labelsLABEL RECORDS ARE STANDARDLABEL RECORDS ARE OMITTED
37Calling a Subprogram Syntax for CALL CALL “subprog name”[ USING [BY REFERENCE | BY CONTENT]ident1 …]END-CALLThe subprog name usually refers to an 8 byte field that contains the program name to be calledStatic call is made when subprogram name is hard-coded and compiler option = NODYNAMSubprogram can be written in any supported language
38Calling a SubprogramCALL variable-name[ USING [BY REFERENCE |BY CONTENT |BY CONTENT LENGTH OF |BY CONTENT ADDRESS OF ]ident1 …]END-CALLThe variable-name usually refers to an 8 byte field that contains the program name to be calledNames can be longer with Enterprise COBOLThe variable-name can be modified as the program is running to call different programs
39Calling a Subprogram Linking to the called program is dynamic At TSYS, all calls are dynamic ( DYNAM compiler option)BY REFERENCE is the defaultBY REFERENCE provides the subprogram with access to a main program variable. The receiving variable is an alias for the passed variableBY CONTENT provides the subprogram with access to a copy of a main program variable
40Calling a SubprogramBY CONTENT ADDRESS OF provides a copy of the address of the passed variable (must be a linkage area name)BY CONTENT LENGTH provides a copy of the length of a variable
42The Called ProgramSpecifies the names of the receiving variables with a USING statement in the PROCEDURE DIVISION statement or in an ENTRY statementPROCEDURE DIVISION USING A.OrENTRY “COMPUTE” USING COST RESULT.PROCEDURE DIVISION USING A COST RESULT.The variables in the using statement are 01 group items defined in the LINKAGE SECTION or 77 itemsLINKAGE SECTION.01 A PIC X(8).O1 COST PIC S9(5) PACKED-DECIMAL.01 RESULT PIC S9(5) BINARY.
43The Called ProgramThe called program can return values to the calling program by modifying variables that are passed by referencePROCEDURE DIVISION USINGCOST.…MOVE ITEM-COST TO COST
44Exercise #1 Create a main program that calls a subprogram Print “I am in the main program” in the main programCall the subprogramPrint “I am in the subprogram” in the subprogramPrint “I am back in the main program” in the main.
45Exercise #2Create a two variables X and Y in the main program (you pick the type and value).Print the values of X and Y in the main programPass X BY REFERENCE and Y BY CONTENT to the subprogramPrint the variables in the subprogramChange the values of each variable in the subprogramPrint the length of x by passing the length using BY CONTENT LENGTH (Receiving variable PIC S9(8) BINARY)Print the values of the variables again in the main program
46Canceling a Subprogram CANCEL syntaxCANCEL literalCANCEL identifierCanceling a program means the program will be in its initial state if the program is called againCanceling a program closes all files associated with an internal file connector of the canceled programNo action is taken when canceling a previously canceled program or one that has not been dynamically called
47Exercise #3 Have the main program call a subprogram four times. Create a local numeric variable Z in the subprogram with initial value 1.Each time the program is called, print Z and then add 1 to it.Repeat the experiment after adding “IS INITIAL” to the PROGRAM-IDPROGRAM-ID. MYPROG IS INITIAL.
48SubprogramsSubprograms remain in their last used state when they terminate with EXIT PROGRAM or GOBACKA program that is coded with INITIAL will always be called with its initial state
49Exercise #4Repeat Exercise #3, canceling each program after each subprogram call
50Return CodesUse the RETURN-CODE special register to test and transmit return codes through register 15After calling a subprogram, test RETURN-CODE to see if the subprogram completed normallyAt the end of a suprogram, set RETURN-CODE to indicate the results of the call
51Exercise #5Write a main program that passes a numeric parameter, say X, to a subprogram. If the parameter is negative have the subprogram set a return code of 4. If the parameter is non-negative, the subprogram should set the return code to 0. Have the main program test the return code after the subprogram has completed. The main program should print a message indicating the type of number the subprogram received. Try running the main program passing negative and non-negative values for X.
52External FilesFiles can be shared by multiple programs in the same run unit.Each program declares the file to be “EXTERNAL”FD MYFILE IS EXTERNALRECORD CONTAINS 80 CHARACTERSRECORDING MODE IS F.01 MY-RECORD.…
53External Files Each program has the same SELECT statement: SELECT MY-FILEASSIGN TO MYFILEFILE STATUS IS MYSTATUSORGANIZATION IS SEQUENTIAL.
54Reading Records READ MYFILE INTO MY-RECORD READ MYFILE Move mode IO – Data flows from an I/O buffer into working storage.READ MYFILELocate mode I/O – Data remains in an I/O buffer. Efficient processing techniqueTSYS standard
55External FilesMake the file status field external so there is only one shared field for all programs. Each program declares:01 MYSTATUS PIC 99 EXTERNAL.Be sure to work in locate-mode.
56Exercise #6Write a main program that opens a sequential file and calls a subprogram each time it needs a record. Write a subprogram that reads a single record and returns to the main program. Have the main program print all the records in the sequential file and then close the file.Share the same file between the two programs by making the file external with a shared file status field.
57PROCEDURE DIVISION…RETURNING An alternate form of passing information back to a calling program is provided:PROCEDURE DIVISION RETURNING datanameTo call a “Function” the invocation is:CALL program-name RETURNING datanameAvoid this alternative in favor of Pass By Reference.
58Nested Programs Avoided in production programs at TSYS Convenient for developing (one file, one compilation)Nested programs can be separated easily into regular programs after debuggingCan be used instead of PERFORMCALL to a nested program is as efficient as a PERFORMEach program ends with END PROGRAM
59Nested Program Structure ID DIVISION.PROGRAM-ID. X.PROCEDURE DIVISION.CALL “X1”GOBACK.PROGRAM-ID. X1.DISPLAY “I AM IN X1”END PROGRAM X1.END PROGRAM X.PROGRAM XPROGRAMX1
60Exercise #7Convert one of your main programs and subprograms to a nested program versionCanceling only makes sense for dynamically called programsCause an abend in your subprogram. Look at the storage dump and error information. Is it any harder to debug than a regular program?
61COBOL is Recursive Now A COBOL program can call itself To make a program recursive, add “IS RECURSIVE” to the PROGRAM-ID statementPROGRAM-ID. SUBPROG IS RECURSIVE.Nested programs cannot be recursive
62Passing a Parm with JCLA parm can be coded on the EXEC statement in order to pass a parameter to the program that is being executed:// EXEC PGM=PROGNAME,PARM=‘HI there!'The COBOL program will receive the parm through the LINKAGE SECTIONCode a LINKAGE SECTION description similar to this:01 PARM-BUFF.05 PARM-LEN PIC S9(4) BINARY.05 PARM-DATA PIC X(256).Code a using statement on the PROCEDURE DIVISIONPROCEDURE DIVISION USING PARM-BUFF.
63Passing a Parm with JCL The parm field is variable in length Use the length field and reference modification to move variable length dataMOVE PARM-DATA(1:PARM-LEN)TO PARMO
64Exercise #8Try coding a main program that receives a parm and prints it outRun the program with the following EXEC statements:// EXEC PGM=PROGNAME,PARM=‘HI!‘// EXEC PGM=PROGNAME,PARM=‘HI THERE!‘// EXEC PGM=PROGNAME,PARM=‘ABCDEFGHIJKLMNOPQRSTUV'
65Omitted ParametersYou can leave out some arguments when coding a CALL statement by coding OMITTED in place of the passed variableCALL “THATPROG” USING P1,OMITTED,P3Test for the OMITTED parameter by checking to see if the address of the received parm is NULL.PROCEDURE DIVISION USING X Y Z.…IF ADDRESS OF Y = NULLDISPLAY “PARM Y WAS NOT PASSED”END-IF
66Exercise 8AWrite a main program that passes three parameters to a subprogram. The subprogram detects and prints the passed parameters.Try calling the subprogram with each parameter omitted.
68Creating A Single Dimension Table Build a storage area with list of data values defined with multiple picture clausesRedefine the storage area as a single dimension table by defining a typical table entry as an “occuring” item.
69Creating A Single Dimension Table 01 DAY-TABLE-VALUES.PIC X(9) VALUE 'SUNDAY '.PIC X(9) VALUE 'MONDAY '.PIC X(9) VALUE 'TUESDAY '.PIC X(9) VALUE 'WEDNESDAY'.PIC X(9) VALUE 'THURSDAY '.PIC X(9) VALUE 'FRIDAY '.PIC X(9) VALUE 'SATURDAY '.01 DAY-TABLE REDEFINES DAY-TABLE-VALUES.05 WEEKDAY PIC X(9) OCCURS 7 TIMES.
71Employee Table 12345 Joe Brown 10 20 12345 Joe Brown 10 20 EMPLOYEE-REC(1)Joe BrownJoe BrownJoe BrownBetty SmithJoy DokesJim DoyleLOC-CODE(3)NAME(3)EMP-NO(4)
72Exercise #9Implement a single dimension table of days. Print the table from beginning to endTurn the table into a “fat” table by adding a column with the number of letters in each day name.Print each day name and the number of letters it contains.
73Multi-Dimension Tables COBOL supports up to 7 dimensions in tablesUse OCCURS within OCCURS to add multiple dimensions01 EMP-TABLE05 EMPLOYEE OCCURS 100 TIMES.10 NAME PIC X(30).10 HOURS PIC S99 OCCURS 7 TIMES.
75Exercise #10 Create a table of integers with 4 rows and 5 columns. Print the table row by rowPrint the table column by columnCompute and print the sum of each rowCompute and print the sum of each columnCompute and print the sum of all entries in the table
76Creating Tables with Indexes 01 EMPLOYEE –TABLE.05 EMPLOYEE OCCURS 100 TIMESINDEXED BY I,J.01 SALES-TABLE.05 MONTH-RECORD OCCURS 12 TIMESINDEXED BY M.10 NAME PIC X(30).2O AMOUNT PIC 9(5)V99 PACKED-DECIMALOCCURS 31 TIMESINDEXED BY D.
77Subscripts vs Indexes Subscripts Represent an occurrence number User defined as a numeric field – best to choose USAGE IS BINARYPrintable (since they are numeric)Can use relative subscripts J+1 or J-3Manipulated with PERFORM loops, assignments, and arithmetic commands
78Subscripts vs Indexes Indexes Represent a displacement value from the start of a table.More efficient than subscriptsCreated automatically when a table is defined with indexesNot really designed to be printedManipulated with PERFORM loops, and SET statements
79SET Statements Examples SET J TO K SET J TO 1 SET K UP BY 1 SET K DOWN BY 1SET K TO K + 1
80Exercise #11Convert Exercise #10 so that you are using indexes instead of subscripts
81Sequential SearchCOBOL provides a SEARCH command that provides a sequential search for tables that have indexesTable entries do not have to be sortedAT END clause provides code in the situation that the search is unsuccessfulSearching starts with the current index value
85Sequential SearchSearch can be continued in a loop after setting index value up or downSET I-NDX TO 1PERFORM UNTIL …SEARCH EMPLOYEEAT ENDDISPLAY ‘NOT FOUND’WHEN EMP-NO(I-NDX) = 12345DISPLAY EMP-RANK(I-NDX)SET I-NDX UP BY 1END-SEARCHEND-PERFORM
86Exercise #12Create a fat single dimension table with the data in the file DATA1. Read the file and store the second (Item #) and third fields (Item name) in the table.Assume a fixed size table of 40 items.Sequentially search the table for item #s in the range 400 to Print out the results of the search.
87Binary SearchingEntire table is searched. No need to initialize an indexTable must have an ASCENDING or DESCENDING KEY IS clause. Table must be sorted.Only one WHEN clause allowed. The WHEN clause is comprised of one or more “equal” tests joined by AND operatorsAT END clause is invoked if the WHEN clause is never satisfied
89Binary Searching 01 EMPLOYEE-TABLE. 05 EMPLOYEE OCCURS 100 TIMES ASCENDING KEY IS EMP-NOINDEXED BY I-NDX.10 EMP-NO PIC 9(5).10 EMP-RANK PIC X(5).…SEARCH ALL EMPLOYEEAT ENDDISPLAY ‘NOT FOUND’WHEN EMP-NO(I-NDX) = 12345DISPLAY EMP-RANK(I-NDX)END-SEARCH
90SEARCH ALL SEARCH ALL performs a binary search with an index ENTRIES MUST BE IN ORDERNo SET necessary (whole table searched)01 SALES-TAX.05 TAB-ENTRIES OCCURS 100 TIMESASCENDING KEY ZIPCODEINDEXED BY K.10 ZIPCODE PIC 9(5).10 RATE PIC V999.SEARCH ALL TAB-ENTRIESAT END MOVE 0 TO TAXWHEN ZIPCODE(K) = ZIPINCOMPUTE TAX = RATE(K) * AMOUNTEND-SEARCH
91SEARCH ALL CONSTRAINTS The condition following WHEN must test for equalityCompound conditions with ANDs not OrsOnly one WHEN clauseVARYING not allowedOCCURS item and its index must appear on the left of the equal signWHEN TEMP(K) = 80
92SEARCH ALL Constraints Table must indicate ASCENDING or DESCENDING KEY01 TABLE.05 CUST-REC OCCURS 40 TIMESASCENDING KEY CUSTINDEXED BY K.10 CUST PIC 9(4).10 RATE PIC V999.
93Exercise #13Convert Exercise #12 to a binary search.
94Variable Length Tables Storage for variable length tables is statically createdTo create a variable length table, use an alternative version of OCCURSExample: OCCURS 1 TO 100 TIMESTo create a variable length table add a DEPENDING ON clause to the table definitionExample: DEPENDING ON REC-COUNT
95Variable Length Tables After loading the table with entries, set the index to point at the last item. Move the index to the DEPENDING ON field01 CUST-TABLE.05 CUSTOMER OCCURS 1 TO 50 TIMESDEPENDING ON C-COUNTASCENDING KEY IS AGEINDEXED BY I.10 NAME PIC X(20).10 AGE PIS S999.
96Exercise #14 Convert Exercise #12 to a variable length table. Assume you don’t know how many items will be in the table, but the range is 30 to 100 items.
98Intrinsic Functions CURRENT-DATE UPPER-CASE (ARG) LOWER-CASE(ARG) ANNUITY(RATE,NO-OF-PAYMENTS)- returns a decimal fraction that when multiplied by loan amount produces the payment. Rate must be consistent with payment period.PRESENT-VALUE(RATE,AMT1,AMT2,…) – returns the present value of future payments
99Intrinsic Functions SQRT(ARG) REM(ARG1,ARG2) –returns the remainder of arg1 divided by arg2MOD(ARG1,ARG2)- similar to REM but with integer argumentsINTEGER(ARG) – the greatest integer less than or equal to ARGINTEGER-PART(ARG) – the integer part of ARGNUMVAL(ARG) – the numeric value of an argument that contains leading spaces, sign, or decimal point
100Intrinsic Function Syntax FUNCTION function-name [(arg1 …]Arguments can be literals, variables, expressions, other functionsFunctions can operate on tables by using the word ALL for the subscriptCOMPUTE X = FUNCTION SUM(SALARY(ALL))COMPUTE Y = FUNCTION SUM(PRICE(1 ALL))Usually used with COMPUTE or MOVE
101Exercise #15Using Exercise #10 and intrinsic functions, compute the minimum value of each row and the mean of the entire array.
102Reconsidering TablesWith vast amounts of main storage today, you should consider the types of file operations you are using and whether or not an application could benefit by pulling an entire file (or part of a file) into main storage. Working directly with records in memory is very efficient and can speed up an application greatlyMost of the time spent in an application is in I/O.
104Variable Length Records FD CUSTFILERECORD IS VARYING IN SIZEFROM 50 TO 80 CHARACTERSDEPENDING ON RECSIZE.When a record is read from a file defined with the RECORD IS VARYING IN SIZE.. DEPENDING ON identifier phrase, the size of the record read into the buffer is moved into the data-item identifierTo write to a file defined with the RECORD IS VARYING IN SIZE.. DEPENDING ON identifier phrase, the size of the record to be written must first be moved to the identifier data-item, and then the WRITE statement must be executed.
105Exercise #16Use program WRITEVAR as a model. Run the program to create a variable length record file.Write a program READVAR that reads the file and prints out the total sales for each person
110Delimited ByThe characters in ident1 or literal1 are used to build a new stringOnly the characters up to the delimiter are transferred”ABCDEF” DELIMITED BY ”D” transfers ”ABC”“JOE BOB SMITH” DELIMITED BY “ “ (two spaces) transfers ”JOE BOB”
111Delimited ByDELIMITED BY SIZE causes the entire identifier or literal to be transferred
112STRING INTOThe INTO clause indicates the target variable where the concatenation occursOnly one target can be indicatedIf the target is too small to handle the concatenation, the ON OVERFLOW condition is executed
113With PointerThe WITH POINTER clause indicates a variable that contains the position within the target field where the next character will be placedThe pointed is incremented each time a character is transferredAt the end, the pointer points to the location following the last transferred character
114On OverflowThe ON OVERFLOW clause is executed if the target is too small to handle the concatenated resultThe ON OVERFLOW clause is also executed whenever the pointer points to a location outside of the target field
115Example String Operation STRING ID-1 DELIMITED BY “*”ID-2 ID-3 DELIMITED BY SIZEINTO ID-4 WITH POINTER PTREND-STRINGID-1ABC*DEID-3XYZPTR13ID-21234*5ID (Assume PIC X(20)ABC1234*5XYZAssume PTR isInitially 1
117STRING OperationUnlike MOVE, STRING does not replace rightmost character with spacesThe POINTER field is a numeric field that afterwards contains the position of the next byte in the receiving field that would have been processed. (Max = string length + 1)
118Exercise #17 Read the file DATA1. Create three fields in the input record:1) cols 1 – 112) cols 15-183) cols 40-65Remove the first part of field 1 up to the *.Remove all of field 2.Remove all of field 3 up to the first spaceString these three fields together. For example the first record would produce“ PEANUT”Print the results of each record.
119UNSTRINGThe UNSTRNG command is used to pull apart a single string into one or more component strings
121UNSTRINGExtracts a field into multiple strings and stores them into one or more fieldsDELIMITED BY indicates how each subfield endsIf ALL is specified for a delimiter, successive occurrences of the delimiter are treated as oneUNSTRING ADDRESS DELIMITED BY ALL “ “INTO STATE ZIPWITH POINTER PTREND-UNSTRING
122Delimiter InThe DELIMITER IN phrase is used when you need to save the delimiter that was used for a given fieldUNSTRING NAME-FIELDDELIMITED BY ”*” OR ”#”INTO N1 DELIMITER IN D1N2 DELIMITER IN D2END-UNSTRING
123Count InThe COUNT IN phrase is used to capture the number of characters sent to a given fieldUNSTRING NAME-FIELDDELIMITED BY ”*” OR ”#”INTO N1 COUNT IN C1N2 COUNT IN C2END-UNSTRING
124UNSTRINGUNSTRING copies Characters from the source string to the destination strings according to the rules for alphanumeric moves.UNSTRING uses space filling.The DELIMITED BY clause causes data movement from the source string to the current destination string to end when1) a delimiter is encountered in the source string2) the end of the source string is reached.
125UNSTRING If DELIMITED BY is not used, data movement terminates when 1) the destination string is full2) the end of the source string is reachedThe UNSTRING terminates when1) All the characters in the source string have been processed2) All the destination strings have been processed3) An OVERFLOW condition is encountered when the pointer is pointing outside the source string.
126UNSTRING EXAMPLE UNSTRING ADDRESS DELIMITED BY ALL “ “ INTO STATE COUNT IN STCNTZIP COUNT IN ZIPCNTWITH POINTER PTREND-UNSTRING
127UNSTRING ExampleUNSTRING ADDRESS DELIMITED BY ","INTO LINE(1)LINE(2)LINE(3)Line(4)TALLYING IN NOLINESEND-UNSTRING.Tallying leaves the number of receiving fields that actually receive data in the named variable
128Exercise #18 Read the file DATA1. For each record in the file, UNSTRING field 1-11 into two parts (separate at the *). Print each part.
131Formats INSPECT has four formats: 1) TALLYING: used to count characters in a string.2) REPLACING: used to replace a group of characters in a string with another group of characters.3) TALLYING…REPLACING: combines both operations in one statement.4) INSPECT …CONVERTING: converts each of a set of characters to its corresponding character in another set of characters.
132TALLYING INSPECT LINE TALLYING ACOUNT FOR ALL “A” INSPECT LINE TALLYING XCOUNTFOR ALL “X"AFTER INITIAL “S"BEFORE INITIAL “E".
133TALLYING INSPECT LINE TALLYING ACOUNT FOR ALL “A” XCOUNT FOR CHARACTERSBEFORE “,“YCOUNT FOR CHARACTERSAFTER “E".
134REPLACING INSPECT MYSTRING REPLACING ALL “X” BY “Y" AFTER INITIAL “A" BEFORE INITIAL “Z“REPLACING ALL “XXXX" BY “ABCD“AFTER INITIAL “A“BEFORE INITIAL “P"
135TALLYING … REPLACING INSPECT LINE TALLYING ACOUNT FOR ALL “A” REPLACING ALL “X” BY “Y"AFTER INITIAL “A"BEFORE INITIAL “Z“
136CONVERTING INSPECT MYTEXT CONVERTING "abcdefghijklmnopqrstuvwxyz“ TO "ABCDEFGHIJKLMNOPQRSTUVWXYZ“
138Creating a Pointer 05 PTR USAGE IS POINTER. 05 A-PTR POINTER. These definitions create 4 byte fullwords capable of containing addresses of memory locations
139Setting a Pointer SET PTR TO ADDRESS OF X SET PTR1 TO PTR2 The interesting point is that Cobol now allows pointers to reference storage areas that are inside the program.In older versions, Linkage areas could only reference areas outside the program.
140“Dropping a Linkage Area” To position a linkage section item onto a storage area, use SET ADDRESSLinkage Section.01 X PIC X(8).SET ADDRESS OF X TO PTR
141Cobol Pointers This fundamentally changes how Cobol can be written Data structures can now be supported in Cobol (stacks, queues)Segmented records can be supported
142Exercise #19Try running programs LINKED and LINKED1 in BCST.SICCC01.PDSLIB
144VSAM File Types ESDS – Entry Sequenced Data Set Allows sequential processingRRDS – Relative Record Data SetAllows sequential or random access by relative record numberKSDS – Key-Sequenced Data SetAllows sequential, skip sequential, and random processing by key
145VSAM VSAM data sets are known as Clusters For ESDS or RRDS the cluster consists of a data componentFor KSDS the cluster consists of a data component and an index componentVSAM data is stored on DASD in control intervals which are grouped into control areas
146VSAMThe Control Interval (CI) is the unit of data that transfers between the disk and virtual storageCI sizes are multiples of 2K with 4k being commonCI’s can be constructed with free space to accommodate additions to the fileControl Areas (CA) can be constructed with free space to accommodate additions
147VSAMVSAM dynamically manages the file by maintaining information in each CI and CAWhen a CI becomes too “full” the data it contains is split into two CI’sWhen a CA becomes too “full” the data it contains is split into two CA’sVSAM tries to keep records that are logically close together, physically close as well
150Access Method Services (AMS) AMS is a VSAM utility that provides numerous optionsDEFINE CLUSTERPRINTREPROLISTCATDELETEDEFINE ALTERNATEINDEXDEFINE PATHBLDINDEX
151VSAM JCLUnlike QSAM files, VSAM files must be allocated in a separate job step before data can be written to the fileVSAM cluster can be created by deleting and then defining the clusterAfter the cluster is defined, a job can run which writes data to the file
152VSAM JCL Parameters: INDEXED –KSDS NONINDEXED – ESDS NUMBERED – RRDS KEYS ( len off) – primary key infoCISZ (size) – control interval sizeFREESPACE (ci ca) – free space %’s
156Creating a VSAM File 000100 IDENTIFICATION DIVISION. PROGRAM-ID. VSAM1.ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL.SELECT PAYROLL-MASTER-OUT ASSIGN TO PAYMASTOORGANIZATION IS INDEXEDACCESS IS SEQUENTIALRECORD KEY IS ID-OUTFILE STATUS IS PM-STATUS.SELECT PAYROLL-MASTER-IN ASSIGN TO PAYMASTI.
157Creating a VSAM File 004410 01 PM-STATUS. 004430 05 PM-STAT1 PIC X. PROCEDURE DIVISION.OPEN INPUT PAYROLL-MASTER-INOPEN OUTPUT PAYROLL-MASTER-OUTIF PM-STATUS NOT = '00'PERFORM 300-PRINT-STATUSEND-IFPERFORM UNTIL ARE-THERE-MORE-RECORDS = 'NO 'READ PAYROLL-MASTER-INAT ENDMOVE 'NO ' TO ARE-THERE-MORE-RECORDSNOT AT ENDPERFORM 200-READ-MODULEEND-READEND-PERFORMCLOSE PAYROLL-MASTER-INPAYROLL-MASTER-OUTGOBACK
158Creating a VSAM File 005130 200-READ-MODULE. MOVE ID-IN TO ID-OUTMOVE NAME-IN TO NAME-OUTMOVE HOURS-IN TO HOURS-OUTMOVE RATE-IN TO RATE-OUTDISPLAY MASTER-REC-OUTWRITE MASTER-REC-OUTIF PM-STATUS NOT = '00'PERFORM 300-PRINT-STATUSEND-IFPRINT-STATUS.DISPLAY 'FILE STATUS CODE:' PM-STATUSGOBACK
159VSAM Error Strategy VSAM returns a status code after each operation It is imperative that you check each status code after each operation to insure that the program is proceeding normallyThe status code is a two byte field
160OPEN OPEN INPUT file-name … OPEN OUTPUT file-name … OPEN I-O file-name …OPEN EXTEND file-name …For EXTEND, access mode must be sequential
161Reading for Sequential Access READ file-name [NEXT] [RECORD][INTO data-name][AT END imperative stmt][NOT AT END imperative stmt][END-READ]Specify NEXT if access is DYNAMIC and you want sequential processingCan be omitted when access is SEQUENTIALINTO provides move mode I/OOmitting INTO provides locate mode I/O
162Reading for Random Access READ file-name [RECORD][INTO data-name][INVALID KEY imperative stmt][NOT INVALID KEY imperative stmt][END-READ]Be sure to set the key of the record you wish to read beforehand
164REWRITE REWRITE record-name [FROM data-name] [INVALID KEY imperative stmt][NOT INVALID KEY imperative stmt][END-REWRITE]A typical scenario is to read the record, modify it (can’t change the key field), and then rewrite it.For random and dynamic access, you can REWRITE a record without first reading it.
165DELETE DELETE file-name [RECORD] [INVALID KEY imperative stmt] [NOT INVALID KEY imperative stmt][END-DELETE]DELETE can only be used for a file in I-O modeIf file is in sequential mode, the DELETE can only be used after executing a READ statement for that record. (Omit INVALID KEY)If file is in random or dynamic mode, a DELETE can be issued without previously reading the record (specify INVALID KEY)
166START START file-name KEY IS EQUAL TO data-name = GREATER THAN > NOT LESS THANNOT <>=[INVALID KEY imperative stmt][NOT INVALID KEY imperative stmt][END-START]Used for sequential and skip-sequential processingDoes not return a record – positions you in the file
167File Status Codes 00 Operation completed successfully 02 Duplicate Key was found04 Invalid fixed length record05 The file was created when opened - Successful Completion07 CLOSE with REEL or NO REWIND executed for non tape dataset.10 End of File encountered14 Attempted to READ a relative record outside file boundary21 Invalid Key - Sequence error22 Invalid Key - Duplicate Key found23 Invalid key - No record found24 Invalid Key - key outside boundary of file.
168File Status Codes30 Permanent I/O Error34 Permanent I/O Error - Record outside file boundary35 OPEN, but file not found37 OPEN with wrong mode38 Tried to OPEN a LOCKed file39 OPEN failed, conflicting file attributes41 Tried to OPEN a file that is already open42 Tried to CLOSE a file that is not OPEN43 Tried to REWRITE without READing a record first44 Tried to REWRITE a record of a different length46 Tried to READ beyond End-of-file47 Tried to READ from a file that was not opened I-O or INPUT48 Tried to WRITE to a file that was not opened I-O or OUTPUT49 Tried to DELETE or REWRITE to a file that was not opened I-O
169File Status Codes 91 Password or authorization failed 92 Logic Error 93 Resource was not available (may be allocated to CICS or another user)94 Sequential record unavailable or concurrent OPEN error95 File Information invalid or incomplete96 No DD statement for the file97 OPEN successful and file integrity verified98 File is Locked - OPEN failed99 Record Locked - record access failed.
170Exercise #20Create a data file of records which is sorted on a key field (choose a 5 byte key). Creating an 80 byte record in a PDS is easiest. Let some of the keys be in the – range, some in range – 29999, some in range – 39999, and some in range (VSAMDATA)Read the file and output a fixed size record VSAM file.
171Exercise #21Read the VSAM file you created in Exercise 20 and print out the records (your choice of format).
172Exercise #22Create a small file of keys. Some of the keys should match records in your VSAM file and some should not. (VSAMKEYS)Process the VSAM file randomly. Take each key, print it, and print the record if it is on the file, otherwise print a message indicating the record was not found.
173Exercise #23Process the VSAM file dynamically with skip-sequential processing.Issue a Start statement and print the records with keys in the range Issue another START and print the records in the range –
174Exercise #24Create a small file of keys. Some of the keys should match records in your VSAM file and some should not.Process the VSAM file randomly. Take each key, read the VSAM file, and delete each record that is found. If the record is not found print a message indicating this.
175Alternate IndexesAn alternate index provides a way to navigate through a VSAM cluster using an alternate keyCreating an alternate index is a 3 step process:DEFINE ALTERNATE INDEXDEFINE PATHBLDINDEX
180Learn Hex Basics Decimal: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 HexadecimalA B C D E F
181Learn Binary Basics Every digit is a power of 2 1 1 1 0 1 0 0 1 = 233
182Binary to HexConversion rule: Remove blocks of 4 binary digits and replace them with a single hex digitD C BHex dumps are made of hex digits and represent binary values that are stored in memory – a short-hand notation2 HEX DIGITS = 1 BYTE
183EBCDIC Characters CHAR HEX CHAR HEX CHAR HEX CHAR HEX 0 = F0 A = C1 J = D11 = F1 B = C2 K = D2 S = E22 = F2 C = C3 L = D3 T = E33 = F3 D = C4 M = D4 U = E44 = F4 E = C5 N = D5 V = E55 = F5 F = C6 O = D6 W = E66 = F6 G = C7 P = D7 X = E77 = F7 H = C8 Q = D8 Y = E88 = F8 I = C9 R = D9 Z = E9= F9SPACE = 40 COMMA = 6B PERIOD = 4B * = 5CMINUS = 60
184Zoned Decimal Format Byte = 8 bits Leftmost 4 bits = zone part Rightmost 4 bits = numeric partPIC S9999PIC 99PIC 99V99One digit per byte – sign in zone portion of last byte. Preferred signs – C +, D –Signs: A C E F B D -ZONE NUMERIC
185Zoned Decimal Format PIC S999 VALUE 123 F1F2C3 PIC 99V99 VALUE F1F2F3C4PIC S99 VALUE F1D2PIC S999 VALUE F0F0C0
186Zoned Decimal DataZoned decimal data was designed for data entry and is an old data formatNo arithmetic can occur in zoned decimal!If you perform arithmetic with zoned decimal fields, they must first be converted to packed decimal or binaryThis conversion is usually unnecessary
187Data TypesPACKED-DECIMAL (COMP-3) – specify 15 or fewer digits in the PIC clause to avoid the use of library routines.Always code an odd number of digits!01 TOTAL PIC S9(7).Always code a sign unless you have a good reason not to.This is a great choice for most business arithmetic
188Packed Decimal Format Two decimal digits per byte Sign stored in numeric portion of the rightmost byte 12|34|5CDecimal points are implied (not stored)Choose packed decimal over zoned decimal if possible
189Packed Decimal PIC S999 PACKED-DECIMAL VALUE 123 123C PIC S9(3)V99 PACKED-DECIMAL VALUE -12300123DPIC S9(4) PACKED-DECIMAL VALUE -9800098D (5 digits exist here)PIC 9(7) PACKED-DECIMAL VALUE -32COMPILE ERRORPIC 9(7) PACKED-DECIMAL VALUE 32C
191Signed Binary Signed binary data is stored in 2’s complement format High order bit is a sign 1 is negative, 0 is positive= 13 in decimal= -14Conversion rule: Change the 1s to 0s and 0s to 1s, then add 1. This computes the 2s complement
192ConversionsThe machine has specific conversion instructions for changing between types:1) PACK, UNPK are used to convert between Zoned and Packed.2) CVB and CVD between Packed and Binary.Try to minimize the conversions by staying in packed
193PointersUSAGE IS POINTER – A 4 BYTE FULLWORD STORED IN BINARY
194Signed Binary Example: 111111 Changing: 000000 Add 1: =1 is the complement so is -1Example:Changing:Add 1: = = 13= -13
195DisplayThe answer to all debugging problems is to gain more information. DISPLAY can provide it.
196Debugging LinesIt is possible to add debugging lines in your code that can be logically removed by commenting one line:Add a “WITH DEBUGGING MODE” Phrase to your program:ENVIRONMENT DIVISION.SOURCE COMPUTER. IBM-XXX WITH DEBUGGING MODE.
197Debugging Lines Put a D in column 7 on each debugging line: D IF X NOT = YD DISPLAY XD END-IFThe lines will execute if “WITH DEBUGGING MODE” is includedOtherwise, the lines are treated as comments
198Adding Compiler Options Compiler options can be included as the first line of a COBOL program:PROCESS options…orCBL optionsCompiler options can be included from an external file://SYSOPTF DD DSN= …
199A Compiler Option for Debugging Use the SSRANGE compiler option while testing to help detect invalid subscript valuesIs the effective address of an element within the boundary of a table?For variable length data references,Is the actual length positive and within the max define length of the group item?For reference-modified data references, are the offset and the length positive? Is the length within the max length of the data item?
200Dump Reading Display Filter View Print Options Help SDSF OUTPUT DISPLAY SICCC01A JOB DSID LINE COLUMNSCOMMAND INPUT ===> SCROLL ===> CSRData Division MapData Definition Attribute codes (rightmost column) have the following meanings:D = Object of OCCURS DEPENDING G = GLOBAL S =E = EXTERNAL O = Has OCCURS clause U =F = Fixed-length file OG= Group has own length definition V =FB= Fixed-length blocked file R = REDEFINES VB=Source Hierarchy and Base Hex-DisplacLineID Data Name Locator Blk Struc2 PROGRAM-ID BOMBMYTABLE-VALUES BLW=FILLER BLW=MYPTR BLW=FILLER BLW=FILLER BLW=FILLER BLW=FILLER BLW=FILLER BLW=FILLER BLW=X BLW=Y BLW=
201Data Division Map 0Source Hierarchy and Base Hex-Displa LineID Data Name Locator Blk Stru2 PROGRAM-ID BOMBMYTABLE-VALUES BLW=FILLER BLW=MYPTR BLW=FILLER BLW=FILLER BLW=FILLER BLW=FILLER BLW=FILLER BLW=FILLER BLW=X BLW=Y BLW=Z BLW=PTR BLW=ANIMAL BLL=NAME BLL=NEXT-ANIM BLL=
202Dump Information<H1> I B M F A U L T A N A L Y Z E R S Y N O P S I SA system abend 0C4 reason code X'4' occurred in module IGZCPAC at offsetX'3FEB4'.A program-interruption code 0004 (Protection Exception) is associated with thisabend and indicates that:An attempt was made to access a protected storage location using an incorrectstorage access key.The cause of the failure was program BOMB1 in module BOMB1. The COBOL sourcecode that immediately preceded the failure was:SourceLine #------DISPLAY NAME
203Dump Information******************************************************************************************************* P O I N T O F F A I L U R E **********************This is the point where control left program BOMB1 prior to the S0C4 abend.COBOL Source Code:SourceLine #------NEXT-ANIM PIC X.PROCEDURE DIVISION.SET PTR TO ADDRESS OF MYTABLE-VALUESSET ADDRESS OF ANIMAL TO PTRPERFORM 7000 TIMESDISPLAY NAMESET ADDRESS OF ANIMAL TO ADDRESS OF NEXT-ANIMEND-PERFORMGOBACK
204Dump InformationLoad Module Name : BCST.GP5CS4.DOMESTIC.LOADLIB(BOMB1)At Address : 38B00C38Load Module Length : X'13C8'Link-Edit Date and Time . : 2005/05/13 12:36:33Program and Entry Point Name: BOMB1At Address : 38B00C38 (Module BOMB1 offset X'0')Program Length : X'77A'Program Language : COBOL (Compiled using IBM Enterprise COBOL forz/OS and OS/390 V3 R3 M1 on 2005/05/13 at12:36:32)Machine Instruction : 05EF BALR R14,R15At Address : 38B0106E (Program BOMB1 offset X'436')AMODE : 31General Purpose Registers:R0: (Storage invalid)R1: 38B00E49 (Module BOMB1 program BOMB1 + X'211')
205Dump Information WORKING-STORAGE SECTION Off Hex Value EBCDIC Value Source (Starting at<H5> BLW=0000 at address 38D500B801 MYTABLE-VALUES.0 C1C1D9C4 E5C1D9D *AARDVARK * PIC X(1* * MYPTR114 C2C5C1E5 C5D *BEAVER * PIC X(124 C3D6D5C4 D6D *CONDOR * PIC X(134 C4C5C5D *DEER * PIC X(144 C5D3C5D7 C8C1D5E *ELEPHANT * PIC X(154 C6D6E *FOX * PIC X(164 C7C9D9C1 C6C6C *GIRAFFE * PIC X(1D X PIC S9980 F4F5C Y PIC S9988 FFEC Z PIC S9(90 38D500B *.N * 01 PTR POINTER
206Dump Information LINKAGE SECTION BLL=0000 has not been assigned an addressOff Hex Value EBCDIC Value Source (Starting at<H5> BLL=0001 at address 38D57FF801 ANIMAL.* * NAME* * NEXT-ANIMSee "System-Wide Information" - "Storage Areas" - "Hex-Dumped Storage" forunformatted storage areas related to this event.
207Dump Information dress 38D500B8 01 MYTABLE-VALUES. 9D *AARDVARK * PIC X(13) VALUE "AARDVARK* * MYPTR1 POINTER SYNC.*BEAVER * PIC X(16) VALUE "BEAVER*CONDOR * PIC X(16) VALUE "CONDOR*DEER * PIC X(16) VALUE "DEER5E *ELEPHANT * PIC X(16) VALUE "ELEPHANT*FOX * PIC X(16) VALUE "FOX*GIRAFFE * PIC X(16) VALUE "GIRAFFEX PIC S999V99 PACKED-DECIMALY PIC S999 VALUE 456.Z PIC S9(4) BINARY VALUE -20*.N * 01 PTR POINTER.
209XML XML = Extensible Markup Language Used to expose the structure and content of a documentBecoming a universal means of exchanging dataTag language<author><firstname>Charles</firstname><lastname>Dickens</lastname></author>
210XML Tags are user-defined Every start tag has a matching stop tag <atag> …</atag>Sometimes the tags are combined into one start and stop tag<media type = “CD” />Tags can’t overlapNO: <a> <b> </a> </b>
211XML Tags can be nested <a> <b> </b> </a> Documents are tree-structured<a><b></b><c><d></d></c></a>ab cd
212XML Text based documents Case sensitive Must contain one root element Start with an XML declaration and comments<?xml version = “1.0”?><!– comment line - -><a></a>
213XML XML is “Well Formed” if 1) Single root element 2) Start and end tags matching for all elements3) Proper nesting4) Attribute values in quotes
214XML ParsersAn XML parser is a program that can read an XML document and provide programmatic access to the documentTwo types of parsers:1) DOM based – Document Object ModelConstructs a tree that represents thedocument2) SAX based – Simple API for XMLGenerates events when parts of thedocument are encountered.Can also be classified as “push” or “pull” parsers
215COBOL Features for Processing XML Input XML PARSE – begins parsing the document and identifies the processing procedure in your documentProcessing Procedure – receives and processes the events that are generated by the parser
216COBOL Features for Processing XML Input Special RegistersXML-CODE - to determine the status of XML parsingXML-EVENT - to receive the name of the eventXML-TEXT – to receive XML document fragments
217Enterprise COBOLContains an event-based parser that allows you to read XML documents and process them with COBOLXML documents can be retrieved from an MQ message, CICS TD queue, or IMS message processing queueXML documents that are read from a file must be brought into storage as a single item. (Records can be combined using STRING)
218Parsing XML PARSE document PROCESSING PROCEDURE event-handler-name ON EXCEPTION …NOT ON EXCEPTION …END-XMLParsing continues until1) an END-DOCUMENT event occurs2) the parser signals EXCEPTION and the procedure doesn’t reset the XML-CODE register to 03) you terminate processing by moving -1 to XML-CODE
219Parsing XML EventsThe XML-EVENT register contains the event name that the parser passing to the handlerThe XML-CONTENT register contains the content for the event
220Events Some typical events: START-OF-DOCUMENT START-OF-ELEMENT ATTRIBUTE-NAMEEND-OF-ELEMENTCONTENT-CHARACTERSSTART-OF-CDATA-SECTIONEND-OF-DOCUMENT
223Exercise #25 Use the file BCST.SICCC01.PDSLIB(XMLDATA2) The file structure is similar to the one below:<?xml version=”1.0” encoding=”ibm-1140” standalone=”yes”?><batch><trans><name>Joe Smith</name><amt>12.32</amt><amt>5.42</amt></trans><trans<name>Tina Louise</name><amt>8.99</amt>…</batch
224Exercise #25Write an XML Cobol program that reads the file and copies it to memory.Print out a report that lists each customer name and a total for each customer.Print a grand total for the entire fileName AmountJoe SmithTina LouiseGrand Total
225Exercise #26 Read the file BCST.SICCC01.PDSLIB(BOOKLIST) Copy the data into memory storing the data as a Cobol data structureWrite out the entire file as a single XML filePretty print the XML file
226Exercise #26 The XML file should have the following structure <booklist><book><author>Melville</author><title>Moby Dick</title></book>….</booklist>
227Compiler Options Default compiler options are in effect for TSYS Options can be overridden with a process statement that precedes the IDENTIFICATION DIVISIONExample (Start in column 8 or 1)PROCESS LIST, AWO
228Apply Write Only AWO is faster than NOAWO Applies to variable length, blocked filesWith AWO the file buffer is written when there is not enough space for the next recordWithout AWO the file buffer is written when the largest size record won’t fit in the buffer
229DATA(24) and DATA(31)DATA(31) + RENT relieves some below the line storage problems. QSAM file buffers can be placed above the lineWith DATA(24), working storage and FD record areas are below the line
230DYNAM and NODYNAMDYNAM causes programs that are called by their literal names to be called dynamicallyNODYNAM allows for static calls for calls made with literal names of programs
231NUMPROCNUMPROC(PFD) – generates efficient code for numeric comparisons. Doesn’t fix up signsNUMPROC(NOPFD) – causes sign fix up for numeric fieldsNUMPROC(MIG) – causes arithmetic similar to OS/vs Cobol
232OPTIMIZE OPTIMIZE(STD) and OPTIMIZE(FULL) – - eliminate unnecessary brancing- simplifying inefficient branching- simplifying the code for out-of-line PERFORM, moving the code in-line- simplifying calls to nested programs- eliminating duplicate computations- eliminating constant computations- aggregating MOVES- deleting unreachable code- deleting unreferenced data items (FULL only)
233OPTIMIZE NOOPTIMIZE – suppresses optimizations Helpful during development to speed compilationsBetter for testing because code is not removedOPTIMIZE for production
234RENT and NORENTCauses the compiler to generate code that makes the program reentrantReentrant programs can be placed in the Link Pack Area and Extended Link Pack AreaLPA is for programs that can be shared and are heavily used during production runs. Programs here remain in memory.
235RMODE RMODE(AUTO) + RENT = RMODE(ANY) RMODE(AUTO) + NORENT = RMODE(24) RMODE(24) + NORENT => WS below the lineRMODE(ANY) + NORENT => WS is above the line
236SSRANGE and NOSSRANGESSRANGE – causes subscript and index checking. Reference modifications are also checkedUse during program developmentNOSSRANGE – turns off subscript checking. Use for production code
237TEST and NOTESTTEST(ALL,SYM) – produces code that enables the Debug Tool to perform batch and interactive debuggingNOTEST – produces more efficient object modules. Use this option for production code
238TRUNCTRUNC(BIN) – Causes base 2 truncation on some intermediate calculations to insure the answer conforms to a halfword, fullword, or doubleword boundaryTRUNC(STD) – Causes base 10 truncation on some intermediate calculationsTRUNC(OPT) – Assumes the data conforms to the PICTURE and USAGE clauses and manipulates the result based on the size of the field in storage
239ARITHARITH – controls the number of digits in decimal numbers (packed, zoned)ARITH(EXTEND) is slower than ARITH(COMPAT)- COMPAT <= 18 digits- EXTEND max 31 digits
240Performance IssuesCALLs – Nested faster than static, call literal faster than dynamic call literal, call literal faster than dynamic all identifier, dynamic call literal faster that dynamic call identifierNested calls are the fastest – and there are good program design reasons for using them as well
241Performance IssuesIS INITIAL on PROGRAM-ID can be very penalizing in terms of timeQSAM files- BLOCK CONTAINS 0 RECORDS !- Experiment with more buffers by modifying the RESERVE clause of the SELECT statement or specifying more buffers in JCL (BUFNO)- Code APPLY WRITE-ONLY or use AWO compiler option for variable length blocked files
242VSAM Performance Issues Increase the number of data buffers (BUFND) for sequential access or (BUFNI) for random accessSelect an appropriate CI size. Smaller is faster for random processing at the expense of insertsLarger CI size is more efficient for sequential processingAlternate indexes should be built by AMS
243Performance Issues Specify SYNCH for BINARY items. Use signed data items with 8 or fewer digits – S9(8) BINARY SYNCS9(4) BINARY SYNC9 or more digits is slower18 digits is slowestAvoid USAGE IS DISPLAY for numeric fields PIC S99.
244Performance IssuesUse 15 or fewer digits for PACKED-DECIMAL (COMP-3) fieldsAlways code a sign (S) unless you have a programmatic reason not to. S9(8) instead of 9(8).Indexes are faster than subscriptsIf you choose subscripts code S9(8) BINARY SYNC or better yet, choose indexes instead
245Performance IssuesUse PIC S9(8) BINARY fields for loop control variablesPacked-decimal fields are slowerDisplay fields (PIC 999) are slowest!Initialize constants with a value clause and don’t modify them or pass them by reference. (Compile will optimize the constants.)
246Performance Issues Don’t use PERFORM THRU Make appropriate use of in-line PERFORMSTry to use tables so the rightmost subscript varies the most often. (Compiler can optimize some subscript calculations)Use SEARCH ALL for tables with 100 items or more