MRIDfr.

ame Refresher Part-I

73

COBOL (COmmon Business Oriented Language)1

HISTORY

Developed In 1959 based on the recommendation of a group called COnference on bAm Systems Language (CODASYLI. First COBOL compUer was released in 1960.

o First ANSI approved version - 1968

o Modified ANSI approved version - 1974 (OS/VS COBOL)

o Modified ANSI approved version - 1985 (VS COBOL 2)

This book Is written based on IBM COBOL for 05/390 V2R2.

Specialty o

First language developed for commercial application development, which can efficiently handle millions of data.

Procedure Oriented Language: Problem is segmented into several tasks. Each task is Written as a Paragraph in Procedure Division and executed In a logical. sequence as mentioned.

English Like language: Easy to learn. code and maintain.

o

CODING SHEET

1

7

12

72

80

SEQ NO.

COLUMN-A

COLUMN-B

IDENT FIELD

1-6

Sequence Number. Usually 1-3 columns identify page number and 4-6 identify line number.

Column No.

Contains

The character In 7'h column identifies the kind of line. The characters and the meaning are - • (Comment),

- (Contlnuity). 1 (New Page in the listing) and D (Debugging lmes)

8-11

Section, Paragraphs, Oland 77 declaration should start here and this is called column A

12-72

Statements and other declarations should start here and this is called Column B..

73-80

Identification field, Anything coded here are tgnored by the compiler,

People use this field as TAG Field for changes.

Mainframe Refresher Part-I

Character Digits (0-9), Alphabets (A-Z), Space (b),

f-,,-,.----.- Special Characters (+ - • / ( ) :: $ : " > < . ,)
Word .Q~le or more characters - User defined or Reserved
--.- -
- lause One or more words. It ~ecifies fll1 attribute for an entry
-
~~al ment One or more valid words and clauses
Sentence One or more statements terminated bv a period
Pa_ragrae_h One or more sentences.
Section One or more paragraphs. --_- -
Division One or more sections or J2aragraphs
---
Proararn Made up of four divisions
,--_3L.: __ - - --
IDENTIFICATION DIVISION. Only MandalOlX division.
PROGRAM-ID. Only mandatory paragraph. 1-8
characters program name is
mentioned here. Il can be qualified
with keywords RECURSIVE (to call the
program Itself) COMMON (so that this
contained program ean be called by
containing program or any program in
the containing program) and INITIAL
(to keep this program's working
storage ill initial state whenever
called].
~-. -- AUTHOR. Infonmluona I
INSTALLATION. InfonnationaJ

DATE-WRITIEN. Inforrna t ion'a]
DATE-COMPILED. Usually blank and the compiler
populate the compilatton date here in
the pro£!r~!l2.Hsting.
SECURITY. Informat iorial
ENVIRONMENT DIVISION. ·-Thls is mac-hill~dependant division.
When program is moved from one
compuler to other, this is the only
- section that n~i' need change.
_ CO~FIGURATION SECTION.
SOURCE-COMPlJI"ER. The c[;mplIleron which the program
- ~ com[!iled.
OBJECT-COMPUTER. Theco,iipUtt>;:Qi,-whlch the program
is executed.
WITH DE;I3UGGING MODE clause
causes till" debugg;n.g lines
(statements that has 'D' in 7th column)
are get compi! xl and included in the
load module. 74

75

Mainframe Refresher Part-I

SPECIAL-NAMES. This paragraph is used to relate
hardware names to user-speclfled
mnemonic names.
Substitute character for currency
sign.
(CURRENCY SIGN IS ltteral-I]
Comma can be used as decimal point.
(DECIMAL-POINT IS COMMA)
Default collating sequence can be
changed.
New Class can be defined using
CLASS keyword.
(CLASS DIGIT is "O~ THRU "9")
INPUT-OUTPUT SECTION.
FILE-CONTROL. Files used In the program are
identified here.
1-0 CONTROL. Specifies when check points to be
taken and storage areas that are
shared bv different files.
DATA DIVISION. Defines the data that needs to be
accessed by the program.
FILE SECTION. Define the file structure here.
WORKING-SfORAGE. Define the data variables here and
they get initialized only for the first
invocation of the program in the run
unit.
LOCAL-STORAGE. Define variables that get initialized for
every invocation of the program.
LINKAGE-SECTION. Define the external data [not owned by
this prcgraml here.
PROCEDURE DIVISION. The program logic is coded here in
user defined sections and paragraphs. DATA DIVISION

Literals, Constants. Identifier

}> Literal is a constant and it can be numeric or non-numeric.

}> Numeric literal can hold 18 digits and non-numeric literal can hold 160 characters in it. (COBOL74 supports 120 characters only)

}> Literal stored in a named memory location is called as Variable or identifier.

}> Figurative Constant is a COBOL reserved word representing frequently used constants. They are ZERO/ZEROS/ZEROES. QUOTE/QUOTES, SPACE/SPACES,ALL,HIGH-VALUE/HIGH·VALUES, LOW-VALUE/ LOWVALUES.

Example: 01 WS-NAME PIC X(04) VALUE 'MUTHU'.

Ln this declaration 'MlITHU' is non-numertc literal and WS-NAME is an Identifier or a variable.

Ma:hrlrame Refresher Part-I

lIIaInframeRefresher Part-I

77

Declaration of VarIable

Declaration of variable starts with level number and followed by variable name, The attributes of variables follow the variable name as below,

Level# :[Varlable I FILLER] '[picture] (Usage] (Sync] :[Value]

It specifies the hierarchy of data within a record. It can take a value from the set of integers between 01-4'9 or (TOm one of the special levelnumbers 66 77 88

Levels

01

Elementary and group items. Any item described In Level 01, the system is putting on double-word boundary and Inserts slack bytes if necessary

02-49

Group or elementary items within a record. Group level items must not have picture clause.

66

The items that contain the RENAMES Clause.

77

Independent data item. Unlike 0 I, this is not aligned in memory.

88

Condition names,

VaIiable ,Qualification ofVarlable and FILLER

Variable name can have 1-30 characters with at least one alphabet In it. Hyphen is the only allowed special character but it cannot be first or last letter of the name. Name should be unique w:lthiin the record, If two variables with same name are there, then use OF qualifier of high level grouping to refer a variable uniquely.

Example: MOVE balance OF recordl-l TO balance OF recordl-2.

When the program is not Intended to use selected fields in a record structure" define them as FILLER FILLER Items cannot be Initialized or used in any operation of the procedure division,

PICfURE Clause

This describes the attributes of variable.

Numeric

9 (Digit), V (Implied decimal point) .. S (Sign), P(Assumed decimal point when the point lies outside the data item)

Numeric Edited

+ (Plus Sign), - (Minus Sign), CR DB (Credit Debit Sign] . (Period), b [Blank], ':(commal, 0 [Zero), / (Slash)

BLANK WHEN ZERO (Insert blank when data value is 0), Z ,(ZERO suppression), .. I[ASTERISK),. $(Cu.rrency Sign)

Non Numeric

A (alphabet), B (Blank Insertion Character), X(Alpha numeric). G[DBCS)

Exclusrve sets

1. + - CR DB

2. V'.:

3, $ +- Z • (But s Can appear as first place and •

as floatmg. S·" .'. oJ .

DBCS [Double Byte Character Set) is used in the applications that support large character sets. 1,6 bits are used for one character. Ex:

Japanese, language applications,

VALUE Clause

It is used for Initializing data Items inthe working storage section.

Value of item must not exceed picture size, It cannot be specified for the items whose size is variable.

Syntax:

VA.LUE IS literal.

VA.LUES ARE literal-l THRU I THROUGH literal-2 VALUES ARE literal-l, literal-2

Literal should be without quotes for numeric item and wtth quotes for nonnumeric Item.

SIGN Clause

SIGN Clause is used to store the sign separately for the signed declarations. It Is applicable when the picture string contain'S', Default is TRAlLlNG WITH NO SEPARATE CHARACTER So'S' doesn't take any space. It is stored along with last digit.

+]=A, +2=B, +3=C, +4=D, +5=E, +6=F. +7=G, +6=H, +'9=1 -0=1. -1= J, -2= K. -3=L, -4=M, -5=N, -6=0, -7=P, -8=Q. -9=R

Syntax: SIGN IS (LEADfNGj SEPARATE CHARACfER (TRAll.lNG).

LEADING SIGN

LEADlNG SEPARATE

Number

TRAlUNG SIGN (Default)

-125 12N

J25

-125

+125 12E

A25

+125

~c Clause and Siack Bytes

SYNC clause Is specified with CaMP, COMP-l and COMP-2 items.

When these items start at half/full/double word boundaries. the address resolution will be faster, SYNC clause does this but it may introduce slack bytes, (unused bytes) before the binary Item.

01 MY-DATA.

05 DATA-ONE PIC X(6),

05 DATA-TWO PIC 9(6) CaMP SYNC ..

05 DATA-THREE PIC S9 (4) V99 CQMP-3.

(TIt .. e startin. ' g a .• dd.res. s. Off.llu.'-word ShO. u. Id end with._O_,4.,8 or C. and I tha .. t. Ofh.alf- .. word should end with 0,2,4_.6,8,A>C,E" If DATA-ONE starts at 0, it will

occupy '0-5 bytes In memory. DATA·'TWO - a sync item of fun word cannot start at 6. So by SYNC rule, it starts at 8th position. 6th & 7th bytes are unused. So MY-DATA occupies 16 bytes.

Mainframe Refresher Part-I

REDEFINES

The REDEFINES clause allows you to use different data description entries to describe the same memory location, Redefining declaration should immediately follow the redefined Item and should be done at the same level. Multiple redefinitions are possible, Size of redefined and redeflrung need not be the same, It cannot be done at 66 and 88 levels.

01 WS-DATE PIC 9 (06} .
01 WS-REDEF-DATE REDEFINES WS-DATE.
05 WS-YEAR PIC 9(02) .
", 05 WS-MON PIC 9(02) .
05 WS-DAY PIC 9 (02) ,
NAMES It is used for regrouping of elementary data items In a record, It should be declared at 66 level, It need not immediately follows the data item, which Is being renamed, But all RENAMES entries associated with one logical record must immediately follow that record's last data description entry. RENAMES cannot be done for a 01, 77.88 or another 66 entry, It cannot be done for OCCurrences of an array,

01 WS-REPSONSE.

05 WS-CHAR143 PIC X(03).

05 WS-CHAR4 PIC X(04).

66 ADD-REPSONSE RENAMES WS-CHAR143.

QONDITION NAME

\/

A condition name associates a value or set of values to a field and used this field directly in condition checking. The program readability will be improved with condition names. It is identified with speclal Ievel ·SS·. The below example will explain It more clearly.

01 SEX PIC X.

88 MALE VALUE '1' '2'. 88 FEMALE VALUE '2' '3'.

:> IF SEX=l can also be verified as IF MALE In Procedure division.

:> 'SET FEMALE TO TRUE' moves value 2 to SEX If mul.tlpJe values are coded on VALUE clause, the first value will be moved when it is set to true.

[f 2 Is moved to SEX, then both MALE and FEMALE are true.

\;JUSTIFY RIGHT

This clause can be specified with alphanumeric and alphabetic items for right justification. This overrides the standard posttlonjng rules for a receiving Item of the alphabet or alphanumeric Items. It cannot be used with 66 and 88 level items.

78

Mainframe Refresher Part-I

Refreshing Basics

Nibble consists of 4 bits and in packed decimal every digit is stored

in a nibble.

Byte consists of 8 bits and every character is stored In a byte. Half word consists of 16 bits - 2 bytes

Full word consists of 32 bits - 4 bytes

Double word eonststs of 64 bits - 8 bytes

sage Clause

Type

Explanation

DiSPLAY

Default usage clause. Number of bytes required equals to the size of the data Item.

COMP& COMP-4

Binary representation of data item. The memory is occupied in terms of half word. full word and double word depending on size of the item. Anything you mention between S9(01) to S9(04). the memory allocated will be half word and Similarly full-word will be allocated for S9(05) - S9(09) and double-word for S9(10) - S9(8).

Most significant bit is ON If the number is negative.

They are stored In 2's complement form.

COMP-l

Single word floating point Item. PIC Clause should not be specifled.

The sign contained in the first bit of the of the leftmost byte and the exponent contained in the remaining 7 bits of the first byte. The last 3 bytes contain the mantissa.

COMP-2

Double word floating-point item. PIC Clause should not be specified.

7 bytes are used for mantissa and hence used for high precision calculation.

COMP-3

Packed Decimal representation. One digit takes half,byte.

PIC 9(N) comp-3 data item would require (N + 1)/2 bytes. The sign is stored separately in the rightmost halfbyte regardless of whether S is specified in the PICTURE or not C - Signed Positive D - Signed Negative F-Unsigned Positive.

COMP-5

This is also a binary representation ltke COMP and the memory usage is also the same. But this can contain values of magnitude up to the capacity of native binary representation rather than being limited to the value Implied by the number of9s in the PIC clause.

COMP-5 item defined as S9(04) can contain maximum value of 32767 whereas COMP or COMP-4 can have only a

I,maximum of 9999. ..

M·a1nframe RefresherPart.I

( Note that COMP or COMP-4 also can store till 32767 if th
Y program is compiled wi.th TRUNC(BIN) whereas COMP-~
behaves so independent of compiler option. This is useful
when the data is coming from non-COBOL Drograms
INDEX It is used for preserve the index value of an array. It takes
4 bytes.
PIC clause should not be specified. When the clause is
specified for a group item, It applies to all elementary items
cont~ed in it. However, the group Itself is not an index
data Item.
POTNTER ~ byte elementary item that can be used to accomplish
limited base addressing. It can be used only in _ SET
statement, Relation condition, .
USING phrase of a CALL statement, an ENTRY statement
or the procedure divis.lon statement. A value clause for a
pointer data item can contain only NULL or NULLS.
SET identifier-l TO address of idenUfier.2
SET ADDRESS OF identifier-2 TO identifier-l
I?entifier-l Is POINTER data item and Identlr.e-2 is
linkage section item. r OCCURS CLAUSE

locations ~;;~~S~~a:~I~sV~~:~ ~~l~~:::s P~~c~~ c~n~gu~us memory

Detail explanation Is given in Table Handling sectron. u scnpt or Index.

LINKAGE SECTION

LINKAGE SECTION is used to access the data that are external to the program. The external data can be from either JCL or frornth program. The linkage section of the called ro ram wt e calling Linkage section should be coded with a half £or~ '0: willfi~fd explained later.

( ~~d: ~te data is COming from PARM of the JCt. If le~th fjei:~o~~~ :~~~

I gth s wo bytes of the field coded in the linkage section Will be filled with

eln an:1 s:::::~1l be last 2 bytes data truncation in the actual content.

05 LK-LENGTH PIC S9(04) COMPo

05 LK-VARIABLE PIC X(08).

In addition to define this, we need to refer in th .

USING clause to establish the addressabllity and a~c:s~~~~;:~ DMSION

PROCEDURE DIVISION USING LK-DATA.

80

Mainframe .Refresher Part~1

81

PROCEDURE DMSION

This is the last division and business logic is coded here. It has user-defined sections and paragraphs. Section name should be unique within the program and paragraph name should be unique within the section.

Procedure division statements are broadly classified into following categories.

Statement type Meanina
Imperative Direct the program to take a specific action.
Example: MOVE ADD EXIT GO TO
Conditional Decide the truth or false of relational condition and
based on it, execute different paths.
Example: IF, EVALUATE
Compiler Directive Directs the compiler to take specific action during
compilation.
Examole: COPY SKIP EJECT
Explicit Scope Terminate the scope of conditional and imperative
terminator statements.
Example: END-ADD END-IF END-EVALUATE
Implicit Scope The period at the end of any sentence, terminates the
terminator scope of ill previous statements not yet terminated. MOVE Statement

It is used to transfer data between internal storage areas defined in either file section or working storage section. Multiple move statements can be separated using comma. semicolons. blanks or the keyword THEN.

MOVE identifierl/literall/figurative-constant TO identifier2 (identifier3)

Numeric Move Rules

A numeric or numeric-edited item receives data in such a way that the decimal point is aligned first and then filling of the receiving field takes place.

Unfilled posltions are filled with zero. Zero suppression or insertion of editing symbols takes places according to the rules of editing pictures.

If the receiving field width is smallerthan sending field then excess digits, to the left and/or to the right of the decimal point are truncated.

Alphanumeric Move Rules

Alphabetic. alphanumeric or alphanumeric-edited data field receives the data from left to right. Any unfilled field of the receiving filed is filled with spaces.

When thelengtb of receiving field is shorter than that of sending field, then receiving field accepts characters from left to right until it Is filled. The un-accommodated characters on the right of the sending field are truncated.

83

Mainframe Refresher Part-I

82

UaiDfr8.1tle Refresher Part-I

When an alphanumeric field i d

edited field. the item Is moved as if it s. move to a numeric or numeric-

mode. CORRESPONDING b were in an unsigned numeric Integer same names belonging to de;:: e t u sed to, transfer data between items of the group-ttems to which they belong, group-items by specifying the names of

MOVE CORRESPONDING group- I TO group-2 Group Move Rules

When MOVE statement Is used to m inf

the movement of data takes place as if b th endt ormation ,at group level.

specifi. ed as alphanumeric items This . 0 . srdl mg and recervmg fields are

I . 1 1S regar ess of the descriptt f th

e ementary Items constituting the group item. . .. on 0 e

Samoles for Und t d

Picture of A ers an . ing MOVE Statement [MOVE A TO B)
Value of A Picture of B Value of B after Move
PIC 99V99 12.35 PIC 999V99
PIC 99V99 012.35
12.35 PIC 9999V9999
PIC 99V999 12.345 PIC 9V99 0012.3500
PIC9(05)V9{03) 2.34
54321.543 PIC 9(03)V9(03) 321.543
PIC 9(04)V9(02) 23.24 PIC ZZZ99.9 23.2
PIC 99V99 00.34 PIC $$$.99 $.34
PIC X(04) MUSA XBXBXB MUS ARITHMETIC VERBS

All the possible arithmetic operations in

SUBTRACT. MULTIPLY and DIVIDE are given below: COBOL using ADD.

Arithmetic Operation A B C D
ADDATO B A A+B
ADDABCTOD A B C
A+B+C+
ADD ABC GIVING D D
A B C A+B+C
ADDATOBC A A+B I A+C
SUBTRACf A FROM B A B-A
SUBTRACf A B FROM C A B C . (A+B)
SUBTRACT A B FROM C GIVING A B C C - (A + B)
0
MULTIPLY A BY B A A-B
MULTIPLY A BY B GIVING C A B A-B
DIVIDE A INTO B A B/A
DIVIDE A INTO B GIVING C A B B/A
DIVIDE A BY B GIVING C A B A/B
DIVIDE A INTO B GIVING C A B Integer Integer
REMAINDERD
(B/A) remainder
(B/A) GMNG Is used in the following cases:

}> To retain the values of operands partiCipating in the operation,

}> The resultant value of operation exceeds any of the operand size.

ROUNDED Option

With ROUNDED option. the computer will always round the result to the PICTURE clause specification of the receiving field. it is usually coded after the field to be rounded. It is prefixed with REMAINDER keyword ONLY

in DIVIDE operation.

ADD A B GIVING C ROUNDED. DIVIDE,.ROUNDED REMAINDER

vUN SIZE ERROR

If A=20 (PIC 9(02)) and B=90 (PIC 9(02)), ADD ATO B will result 10 in B where the expected value in B is 110. ON SIZE ERROR clause is coded to trap such size errors in arithmetic operation.

If this is coded with arithmetic statement, any operation that ended

with SIZE error will not be carried out but the statement follows ON SlZE

ERROR will be executed.

ADD A TO B ON SIZE ERROR DISPLAY 'ERROR!'.

COMPUTE

COMPUTE statement assigns the value of an arithmetic operation (onth.e right hand side) to a data item (on the left hand side). The order of operation is given below. The rule is Jeft to right within the same order.

Order Operation
1 Brackets
2 NOT and Exponentiatlon(**)
3 AND. Multipl1cation(*] and Division (/)
4 OR. Addttfonl+l and Subtraction (-) Caution: When ROUNDED is coded with COMPUTE, some compiler will do rounding for every arithmetic operation and so the final result would not be precise. So avoid using ROUNDED for any Intermediate computation .

CORRESPONDING is available for ADD and SUBTRACf only.

OTHER STATEMENTS INITIALIZE

VALUE clause is used to initialize the data items in the working storage section whereas INITIALIZE is used to Initialize the data items In the

procedure division.

INITIALIZE sets the alphabetic. alphanumeric and alphanumeric-

edited items to SPACES and numeric and numeric-edited items to ZERO.

..

Mainframe Refresher Part-I

This can be ovenidden by REPLACING option of INITIALIZE. FILLER, OCCURS DEPENDING ON Items are not affected.

INITIALIZE. identifier-1

REPL~ING (ALPHABETIC/ A.LPHANUMERIC/ALPHA-NUMERIC-EDITED NUMERIC/ NUMERIC-EDITED)

. ~ DATA BY [identifier-2 /Literal-2)

V 01 A.

05 Al PIC 9(5). 05 A2 PIC X(4).

INITIALIZE Al REPLACING NUMERIC

by 50. . .. DATA BY 50 will initialize only Al

~

\',/ACCEPT

. . ACCEPT can transfer data from input device or s .

contain in the reserved data items like DATE, TIME, DAY. ystem Information

~C~:~~ ~1~~:Rl (FROM DATE~TIME/DAY/OTHER SYSTEM VARS) . thru SYSIN At the tim e iSr not co~ed, then the data is read from terminal or

. . ... e 0 execution batch g 'n

no In-stream data from JCL and th ' pro ram WI .. ABEND if there Is clause. .. ere is no FROM clause in the ACCEPT

r

System Variable Returns
DATE YYMMDD (6 bytes)
DATE YYYYMMDD
DAY YYYYMMDD (8 bytes)
TIME YYDDD (5 bytes)
DAY-OF-WEEK HHMMSSTT (8 bytes)
N (sirurte dlj!it 1 to 7 represents Mon- Sun) DISPLAY Statement

It is used to display d ta B d c

SYSOUT. a . y efault dlsplay messages are routed to

DISPLAY identifierll literall (UPON .

mnemon~c name)

ENTRY Statement

calling pr:~ime~!i :~e~~n!x~~ta~liShr one alternate entry point and the by referring the respective entry n~m~n I:~ any entry. pOi~t in the program you can call the program onl b '. e entry option IS not there, then control will be fir t lin . Y y program-id and the first line that gets

s e In procedure division.

/ ENTRY 'PGMIA' USING LK-VARI LK-VAR2

VCJSTOP RUN, EXIT PROGRAM & GO BACK

STOP RUN is the last executabl tat

returns control back to OS. EXIT PROG~ I e:ent of the main program. It

of sub-program. It returns ~ontrol back to m:tn e ~ast executable statement coded In main program as well as sub- ro .. p ogram, GOBACK can be gives the control back from where it rec~ve~~ ~~n~~I~ast statement. It just

84

Mainframe Refresher Part-I

85

IF ITHEN IELSE/END-IF

'IF' is the widely used decision making statement in COBOL. The permitted relation conditione are =, <, >, <=. >=, <>

CONTINUE Is a null statement and it just passes the control to next

iInllledlate statement whereas NEXf SENTENCE passes the control to next sentence. Sentence Is one or more statements ended with period. Period can work as implicit scope terminator for all the preceding IFs, To avoid confusion and better readability code the IFs with proper indentation and one

END-IF for every IF.

IF condi~ionl AND condition2 THEN Statement-Block-l

ELSE

IF condition3 THEN CONTINUE

ELSE

IF condition4 THEN Statement-B10ck-2 ELSE

NEXT SENTENCE

END-IF

END-IF

END-IF

Statement-Block-2 will be executed only when condition 1, 2 and 4 are TRUE and condition 3 is FALSE. THEN is not mandatory parameter and it is one of the noise words in COBOL (the 'non-mandatory' words in the syntax).

Implied operand: In compound conditions. it is not always 'necessary to specify both operands for each condition. IF TOTAL=7 orB is acceptable. Here TOTAL=B is Implied operation.

SIGN Test and CLASS Test

SIGN test is used to check the sign of a data item. IF identifier is POSITlVE/NEGATIVE/ZERO

CLASS test Is used to check the content of data item against predefined range of values. It can be done as follows:

IF identifier is NUMERIC/ALPHABETIC I ALPHABETIC-HIGHER/ ALPHABETIC-LOWER

We can define our own classes In the special names paragraph and check whether the variable belongs to that class. For ,example,. we have defined a class DIGIT In our special names paragraph and any variable can be checked whether it contain only the pre-defines values of DIGIT as

IF Identlfierls mGIT

Negated conditions: Any simple. relational, class, sign test can be negated usmg NOT. But it Is not always true that NOT NEGATIVE Is equal to

POSITIVE. (Example ZERO)

Mainframe Refresher Part-I

EVALUATE

With COBOL8S. we use the EVALUATE verb to implement the case structure of other languages. Multiple IF statements can be efficiently and effectively replaced With EVALUATE statement. After the execution of one of the when clauses. the control automatically comes to the statement following END-EVALUATE. Any complex condition can be given in the WHEN clause. Break statement is not needed. as it is so in other languages.

General Syntax

EVALUATE subject-l (ALSO subject2 .. j WHEN object-l (ALSO object2 .. ) WHEN object-3 (ALSO object4 .. ) WHEN OTHER imperative statement

END-EVALUATE

..

» Number of Subjects in EVALUATE clause should be equal to number of Objects in every WHEN clause,

» Subject can be Variable. expression or the keyword TRUE/ FLASE and respectively objects can be values, TRUE/FAlSE or any condition.

» If none of the WHEN condition is satisfied. then WHEN OTHER path wiJl be executed.

EVALUATE SQLCODE ALSO TRUE

WHEN 100 ALSO A=B

WHEN -305 ALSO (A/C=4)

DISPLAY 'ALLOWED SQLCODE .. PROCEEDING .. ' WHEN OTHER

CONTINUE

END-EVALUATE

In the above example. display will be thrown when one of the first two WHEN clauses are true.

EXlT Statement

COBOL reserved word that performs NOTHING. It Is used as a Single statement in a paragraph that indicates the end of paragraph(s) execution. EXlT must be the only statement in a paragraph in COBOL74 whereas it can be used with other statements in COBOL8S.

GO TO Usage

GO TO is not preferable in structured top-down programming. It offers permanent control transfer to another paragraph and the chances of logic errors is much greater with GO TO than PERFORM. The readability of the program will also be badly affected.

But still GO TO can be used within the paragraphs being performed.

I.e. When using the THRU option of PERFORM statement. branches or GO TO statements. are permitted as long as they are within the range of named paragraphs.

86

87

Mainframe Refresh.er part-I

PERFORM 100-STEPl THRU STEP-4

100-STEP-l.

ADD A TO B GIVING C. NOT DONE'

IF D = ZERO DISPLAY 'MULTIPLICATION

GO TO 300-STEP3

END-IF.

200-STEP-2.

MULTIPLY C BY D.

300-STEP-3.

DISPLAY 'VALUE OF C:' C.

RM This kind of Here GO TO used within the range of .PE:~l .

controlled GO TO is fine with structured programrrung

ALTER Statement

The alter statement is used to mo~i~. the targets of GO TO statements written elsewhere in the procedure diVISion.

ALTER PROCEDURE-NAME-l TO [PROCEED TOl, PROCEDURE- NAME-2 IPROCEDURE-NAME-3 TO {PROCEED TO}

PROCEDURE-NAME-4l ...

AME-l PROCEDURE-NAME-3 is the

Each of the PROCEDUR:E-N n1 one sentence. This sentence must name of the paragraph that contalnst 0 .ihout the depending clause .. During consist of a single GO TO stateme~~ NAME-I PROCEDURE-NAME-3 ... the execution each of the PROCED ~ NAME~2 PROCEDURE-NAME-4

will be replaced by PROCEDU -. ,

... respectively.

PERFORM STATEMENTS

. when ou want to execute a set of

PERFORM will be useful. Y Write aU the statements in one

statements in mu.ltiple pl~ces ~f thepk:~~ wherever needed. Once the paragraph and Invoke It using 1 back to next statement following paragraph is executed. the contro comes

the PERFORM.

SIMPLE PERFORM

PERFORM PARA-I.

DISPLAY 'PARA-l executed'

STOP RUN.

PARA-I.

statementl Statement2.

PARA-l and then transfers the It executes all the instructions coded In

control to the next tnstructton tn sequence.

..

Mainframe Refresher Part-I

INLINE PERFORM

When sets of statements are used only in one place then we can group all of them within PERFORM END-PERFORM structure. This is called INLINE PERFORM. This is equal to DO .. END structure of other languages.

PERFORM

ADD A TO B MULTIPLE B By C

DISPLAY 'VALUE OF A+B*C ' C END-PERFORM

PERFORM PARA-I THRU PARA-N

All the paragraphs between PARA-I and PARA-N are executed Once.

PERFORM PARA-l THRUPARA-N NTIMES N can. be literal defined as numeric item in working storage or hard coded constant.

PERFORM PARA-l THRU PARA-N UNTIL Condition(s)

The identifiers used in the UNTIL condition(s) must be altered within the paragraph(s) being pertbnned; OthelWise the paragraphs will be perfonned indefinitely. If the condition in the UNTIL clause is met at first time of execution, then named paragraph[s) Will not be executed at all.

PERFORM PARA-I THRU PARA-N VARYING Id-I'FROM id-2 BY id-3 UNTIL Conditions (sl

FROM identifier2 BY identifier3 UNTIL condition(s)

Initialize identifierlwith identifier2 and test the condition(s). If the condition is false execute the statements in PARA-l thru PARA-N and increment identifierl BY identifier3 and check the condition(s) again. If the condition is again false, repeat this process till the condJtion is satisfied.

PERFORM PARA.-l WITH TEST BEFORE/AFTER UNTIL Condition(s)

. With TEsT BEFORE, Condition is checked first and if it found false, then PARA-l Is executed and this is the default. (Functions like DO- WHILE)

With TEST AFTER, PARA-I is executed once and then the condition is checked. (FUnctions like DO-UNTIL)

Refer Table SeSSion for eighth type of PERFORM.

PERFORM for Multi Dimensional Arrays

/ This perfonp. is Used to scan thru the eleme~ts of muJti dimensional

array. Sample syntax for two dimenSional array look up is:

PERFORM para-l thru para-n VARYING index-l from 1 BY 1

UNTIL index-I> size-Of-outer-occurs AFTER VARYING index-2 from 1 by 1

UNTIL index-2 > size-Of-inner-occurs

88

MaiDfr.ame Refresher Part-I

89

TABLE HANDLING

the repeated occurrences of

An OCCURS clause is used to d~g~~RS clause is not valid for 0 I,

Items of the same format in a struc~ure~~mentary or group Item. COB<?L74 77 88 levels. It can be de~ned a COBOLa5 supports 7 dlmensions. su~ports maximum 3 dlmenstons whe~e~th specific values are usu~~ done Initialization of large table ceduredivtsion. Simple tables can be initialized in using perform loops in proce ure IV!

the following way.

VALUE 'MONTUEWEDTHUFRISATSUN'.

01 WEEK-ARRAY CCURS 7 TIMES PIC X(03),

05 WS-WEEK-DAYS 0

Jh. i th array whose size is decided during runtime just before arruc array s tne

~access of first element of the array.

01 WS-MONTH-DAY-CAL. TIMES DEPENDING ON WS-OCCURENCE. 05 WS-DAYS OCCURS 31

'28' to WS-OCCURRENCE.

IF MONTH = 'FEB' MOVE

. INDEX or subscript and the difference

Array Items can be accessed us~g R I trve subscripts and relative inde~es

between them are listed in ~he ~bo~O~~~ Literals used in relative

orted only m .

are supp. . t be an unsigned Integer.

subscriptmg/Indextng mus

J WS-SAL(SUB + 1) TO WS-SAL(SUB + 2),

I ADD WS-SAL(SUB)

1SU~b-sc-n7'~~~-=~~--------TlIn~d~e~x~=====:~==~~;;;;;;.t~

Internal Item - No need to declare 1 •

Wotkin e item It means dis lacement

It means occurrence Faster and efficient.

Occurrence, in tum translated to

displacement to access elements and so slower than INDEX access.

It can be used in any arithmetic qJ erations or for dis la .

f---'SubsCripts can be modified by any arithmetic statement.

SEARCH I. s sequential information,

When the req~irementis to ~d=~oa~~~s an array and look up in the only possible way IS to load thet Id 0

c th information reques e .

the array ror e k be done in two ways:

This table 100 up can

}> Sequential Search (SEARCH) Search (SEARCH ALL)

}> Binary ALL table should have an index. To use

To use SEARCH/SEARCH rted order. If we use SEARCH for

SEARCH ALL the table should be in a so

Mainframe Refresher Part-I

90

JIa1Df:raJne Refresher Part-I

91

accessing multl-dimension table. then INDEXED BY must be used on all OCCURS levels.

Though AT END Clause is optional, it is highly recommended to code that. Because if it is not coded and element Iookmg for is not found !-hen the control simply comes to the next statement after SEARCH where an mvalid table item can be referred and that may lead to incorrect results /

abnorraal ends. -

SET statement Is used to assign/Increment/decrement Index values. Syntax: SET index-name-l TO/UP BY/DOWN BY integer-l.

Difference Between SEARCH and SEARCH ALL

SEARCH SEARCH ALL
Sequential Search Binary Search
Table should have INDEX Table should have INDEX
Table need not be in SORTED order. Table should be in sorted order of the
searching argument. There should be
ASCENDING /DESCENDlNG Clause.
I Multiple WHEN conditions can be Only one WHEN condition can be
coded. coded.
Any logicalcompartson is possible. Only - is possible. Only AND rs
possible in compound conditions.
To start the search from first Index need not be set to 1. The logic is
element, index should be set to 1. compare the item to be searched with
The logic Is search one after other the item at the mid of the table. If it
from the current index till the search matches fine. else repeat the process
Is successful or end of table. with left or right half depending on
where the item lies. For this logic to
work fine, the array should be sorted
Preferred In the following cases: on the item betna searched.
Preferred In the following cases:
1. Table Size is small .. When the size of the table is large and
2. Table contains duplicates and all the elements in the table will be
required to retrieve all the frequently accessed and table does not
duplicates. contain any duplicates and contain a
3. Table can be loaded in such a way unique key.
that the most frequently accessing
elements can be loaded In the first
few occurrences.
Syntax: Syntax:
SET indexname-l TO 1. SEARCH ALL identifier-l
AT END
SEARCH identifier-l AT END Display 'No Match: r
Display 'No :Match: r WHEN condition-l
WHEN condition-l Statements /NEXT SENTENCE
Statements /NEXT SENTENCE END-SEARCH
WHEN condition-2
Statements /NEXT SENTENCE
END-SEARCH
Identlfler-I should be OOCURS item
and not 01 Item. corr STATEMENT

coPY statements in a COBOL program are very different from other COBOL statements. While other statements are executed at run time, OPY statements are executed at compile time thru SYSLIB _PDS. P. C..QE¥ statement Is slimlar to the "Include" used in languages like C and C++. It anows programs to Include frequently used source code text. Copybooks are

generally used In the following cases.

» Common routines like error routine, date valldation routine are coded In a library and bring Into the program by COPY. Master files are usually used across the programs, Their layout can be placed in one copybook and be placed wherever the files are used. It promotes program standardization since all the programs share the same

layout and the same data names.

» Copybooks reduce coding and debugging time. Instead of changing 'n' places, you can change copybook and just recompile the program for making the new copy effective.

Copybooks can be used in the following paragraphs.

SOURCE-COMPUTER, OBJECT-COMPlITER. SPECIAL-NAMES, FTI..ECONTROL, la-CONTROL, FD SECTION. PARAGRAPHS IN PROCEDURE

DlV1SI0N.

Syntax:

COpy copybook-name ((OF/IN) library name I

[REPLACING string-to-be-replaced BY replacing-string]

By default, the copybook library is SYSLlB and it can be changed using IN or OF of COPY statement.

When COpy statements include source code in a program. the code

can be included without change or the text can be changed as it is copied Into the program. The ability to change the code as It being included greatly adds to the versatility of the COPY verb. This is achieved thru REPLACING option of COpy statement. One example is - If the same copybook is used more than once In the program, then there will be "duplicate data declaration" error during compilation, as all the fields are declared twice. In this case. one copybook can be used with REPLACING verb to replace high-level qualifier of the all the variables with another qualifier,

Example:

COpy CUSTOMER REPLACING 'CUST-' BY'CUSTOMER-'.

Delimiter ': =' should be used for replaclng pseudo texts.fl'o replace a series of words or characters as opposed to an Individual identlfier. literal or word} The replacing option does not alter the prewrltten entries In the library: the Changes are made to the user's source program only .

..

Mainframe Refresher Part-I

STRING HANDLING

A string refers to a sequence [ h

operations include finding a particular 0 hC aract~rs. String manipulation replacing particular character/sub-strin ~. aracter sub-string in a string, and segmenting strings. . g n a stnng, concatenating strings

All these [unctions are ha dl d b th

and UNSTRING In COBOL EXAMt e. y ree verbs INSPECT. STRING supported in COBOL74.· NE IS the obsolete version of INSPECT

/INSPECT- FOR COUNTING

It Is used to tally the occurrenc f .

characters in a data fleld. e 0 a SIngle character or groups of

INSPECT identifier-l TALLYING identifier-2 FOR [[ALLILEADING literal-Il'd t· .

[BEFORE I AFTER INITIAL id~nte~f7fle4r -3! ' CHARACTERS]

~ ~er- Illteral-2]

Main String is identiller-l and c . .

Identifier-3 is a character or rou ~w:t is stored In Identifier-2. Literal-lor string. INSPECT further qUalgif' Pth°f characte~s you are looklng in the main-

initi I ies e search with BEFORE d

, a occurrence of identifler-4 or IiteraJ-2· an AFTER of the

.r: .

WS-NAME - 'MVSQUEST IS A. SUBSIDY Of QTEC' INSPECT WS-NAME TALLYING WS-COUNT FOR ALL'S' BEFORE INITIAL 'QTEC'

END-INSPECT AFTER INITIAL 'MVSQUEST'

Result: WS-COUNT contains _ 3 INSPECT- FOR REPLACING

It is used to replace the occurre f .

characters in a data field. nee 0 a stngle character or group of

INSPECT identifier-I REPLACING

. [[ALLI LEADING literal-II 'd '.

BY identifier-Jlliteral_~ entJ.f:l.er-2j / CHARACTERS]

[BEFORE/AFTER INITI . "

. .ilL ~dentlfler-4Iliteral_2]

INSPECT-FOR COUNTING AND REPLACING

It is a combination of the above two meth d

o S.

INSPECT identifier-l TALLYING <tallying part>

STRING REPLACING <replaCing part>

STRING.command Is used to concatenate two or more strings.

STRLNG ldentlfler-l 1 literal-I' . ,

DELIMITED BY (identifie~_~~~?~lfler-21 literal-2

. INTO identifier-4 1 eral-J/SIZE)

END-STRING.

Jl8lDfralDC Refresher Part-I

93

/01 WS-INPUTS.
05 FIRST-NAME PIC X(IO) VALUE 'MUTHU
05 LAST-NAME PIC X(10) VALUE 'SARA
05 NAME PIC X(20) . To get display 'MUTHU,SARA'

STRING FIRST-NAME DELIMITED BY' , ',' DELIMITED BY SIZE

LAST-NAME DELIMITED BY , ,

INTO NAME END-STRING.

The receiving field must be an elementary data Item with. no editing symbols and JUST RIGHT clause. With. STRING statement, specific characters of a string can be replaced whereas MOVE replaces the full string,

01 AGE-OUT PIC X(12) VALUE '12 YEARS OLD'.

STRING '18' DELIMITED BY SIZE INTO AGE-OUT. ~> 18 YEARS OLD.

Reference Modification - Equivalent of SUBSTR

'Reference modification' is used to retrieve or overwrite a sub-string of a string. ':' is known as reference modification operator.

Syntax: String(Starti ng- Position: Length)

MOVE '18' TO AGE-0tIT(1:2) does the same as what we did with STRING command. When it refers array elements, the syntax Is:

Array-element (occurrence) (Starting-Position:Length)

(llNSTRING

UNSTRING command is used to split one string to many strings.

UNSTRING identifier-l

(DELIMITED BY (ALL/) identifier2/literall [,OR (ALL/) (identifier-3/literal-2), .. ]J

INTO identifier-4

(, DELIMITER IN' identifier-5, COUNT IN identifier-G]

01 WS-DATA PIC X(12) VALUE '10/200/300/1'.

UNSTRING WS-DATA DELIMITED BY 'I'

INTO WS-FLDI DELIMITER IN WS-Dl COUNT IN WS-Cl WS-FLD2 DE.LIMITER IN WS-D2 COUNT IN WS-C2 WS-FLD3 DELIMITER IN WS-D3 COUNT IN WS-C3

END-UNSTRING.

Result:

WS-FLD 1 ::: 10 WS-FLD2 =200 WS- FLD3:::300

WS-Cl '" 2 WS-C2=3 WS-C3=3 WS-Dl = 'r WS-D2='/, WS-D3 '/' ON OVERFLOW can be coded with STRING and UNSTRING. If there is STRING truncation then the imperative statements followed ON OVERFLOW will be executed.

MaJnframe Refresher Part-I

Mainframe Refresher Part-I

NESTED PROGRAMS. GLOBAL. EXTERNAL

One program may contain other programjs). The contained programtsl may themseivescontaln yet other programts). All the contained and containing programs should end with END PROGRAM statement. PGMB is nested a program In the 'example below:

IDENTIFICATION DIVISION.

PROGRAM-ID. PGMA

IDENTIFICATION DIVISION. PROGRAM-ID. PGMB

END PROGRAM PGMB.

END PROGRAM PGMA.

If you want access any working storage variable of PGMA in PGMB th decl~e them with the clause 'IS GLOBAL' in PGMA. If you want to acce~s ~~ workmg st~rage variable of PGMB in PGMA, declare them with the clause 'IS EXTERNAL In PGMB. Nested Programs are supported only in COBOL8S. If there is. a program PGMC lnstde PGMB, it cannot be called from PGMA unless it's program id is qualified With keyword COMMON.

CALL Statement (Sub-Programs)

~en a spectfte functionality need to be performed In more than one program, It IS best tc wnte them separately and call them Into each program. Sub Progr~s can be written in any programming language. They are typically ~tten in a language best Suited to the specific task required and thus provfde greater flexibfhty,

Main Program Changes:

. CALL statement Is used for executing the sub-program from the

main ~rogram. A sample of CALL statement to call PGM2 is given below:

CALL 'PGM2' USING BY REFERENCE WS-VARI.

BY CONTENT WS-VAR2.

" , WS-VAR.l is passed by reference. WS-VAR2 is passed by Content.

BY REFERENCE IS default in COBOL and need not be coded. BY CONTENT LENGTH phrase permits the length of data item to be passed to a called program.

Sub-Program Changes:

WS-V.ARI and WS-VAR2 are working storage items of main program. As we have already mentioned. the linkage section Is used for accessing external elements. As these working storage items are owned by main program. to access them in the sub-prcgram, we need to define the in

the llnkage section. . . em

94

LINKAGE SECTIPN. 01 LNK-ITEMS.

05 LK-VARI PIC 9(04). 05 LK-VAR2 PIC 9(04).

95

In addition to define them in linkage section. the procedure dtvtston should be coded with these data items for address-ability.

PROCEDURE DIVISION USING LK-VARl,LK-VAR2

The name of the Identifiers in the called and calling program need not be the same {WS-VARI & LK-VARIJ.

The last statement or your sub-program should be EXIT PROGRAM.

This returns the control back to main program. GOBACK can also be coded instead of EXIT PROGRAM but not STOP RUN. EXIT PROGRAM should be the only statement In a paragraphln COBOL74 whereas it can be coded along with. other statements in a paragraph in COBOL8S.

~ PROGRAM-ID. <Program-name> IS INITIAL PROGRAM.

If IS INITIAL PROGRAM is coded along with program-id of sub program, then the program Will be In initial stage every time it Is called (COB0L85 feature). r Alternatively CANCEL issued after CALL, will set the sub-program to initial \. state.

n If the sub program is modified then it needs to be recompiled. The need for m ... aln program •. recomptlation is decided by the compiler option us. ed or the main program. If the DYNAM ccmpller Is used. then there is no need o recompile the main program. The modified subroutine will be in effect during the run. NODYNAM is default that expects the main program recompllation,

Pass By Reference

Differ~nce Between Pass-by-Reference and Pass-by-Content

Pass B Content

CALL 'sub I' USING BY REFERENCE WS-VARI

CALL 'sub I' USING BY CONTENT WS-VARI

(BY CONTENT ke ord is needed)

It is default in COBOL. BY REFERENCE is not needed.

BY CONTENT key word is mandatory to pass an element by value.

Address of WS- V AR lis passed

Value ofWS-VARI is passed

The sub-program modifications on the passed elements are visible in the main program.

The sub-program modifications on the passed elements are local to that sub-program and not visible in the main ro ram.

Mainframe Re.fresher Part-!

V Difference Between Static Call and Dynamic Call

STATIC Call DYNAMIC Call
If the subprogram undergoes If the subprogram undergoes
change, sub program and main change, recomptlation of
program need to be recompJled. subpro~misenough.
Sub modules are link edited with Sub modules are pIcked up during
main module using the default run time from the load library,
compiler option No.DYNAM:. Usually identified by call variable.
Usually identified by the call literal.
CALL'PGMl'. DI WS-PGM PIC XfD8).
Note: If the compiler option DYNAM Mo.VE LK,PGM TO WS-PGM
CALLWS-PGM
is used, then sub modules Will be
dynamically bou nd even though the
call is by literal.
The main advantage is the faster The main advantages are:
execution due to embedded sub 1. Load module size Will be less.
modules. 2. When there is a change in sub
program, It Is enough to Just
change/compile the sub
program alone. No need to
recompile main prograrnts). So
It provides better flexibility.
Program that doesn't undergo Program that undergoes frequent
frequent changes and whose size is changes and who e size Is large are
not very large are usually statically USUally dynamically bound with
' bound with main module. main module.
The calls in highly used main -
programs are usually static to
improve the appUcation
performance. ORT and MERGE

. . The programming SORT is called as internal sort whereas the sort in J.CL Is called external sort. If you want to manipulate the data before feedmg to sort, prefer internal. sort. In all other cases. external sort is the good choice. Internal sort, in tum invokes the SORT product of your

( installation. (DFSORT). In the run JCL. allocate at least three sort work files. \!SORT-WKnn => on can be 00-99).

FASTSRT compiler option makes the DFSORT to do all file 1-0. operation than your COBOL program. It would slgnlflcantly Improve the performance. The result of the SORT can be checked In SORT-RETURN register. If the sort Is successful, the value will be 0 else 16.

Syntax: SORT <sort-work-file> ON ASCENDING /DESCENDING KEY sd-key-l Sd-key2

USING file! file2 I INPUT PROCEDURE IS section-l

GIVING file3 I OUTPUT PROCEDURE is section-2

END-SORT

Mainframe Refresher Part-!

97

Ftle l , File2 are to-be-sorted Input files and File3 is sorted-output file and all of them are defined In FD.SORTFrL.E Is disk sort work file that Is defined at

SD. It should not be explicttly opened or closed. .

. INPUT PROCEDURE and USING are mutually exclusive. If USING IS

used. then mel and file2 s~.E0t be opened or :ead explicttly. If INPUT PROCEDURE Is used then filel and file2-neett to be openc:;!..._and read the records one by one until end of the file and pass e required records to sortwork-file using the command RELEASE.

Syntax: RELEASE sort-work-record from Input-file-record.

OlITPUT PROCEDURE and GIV1NG are mutually exclusive. If GMNG is used, then file3 should not be opened or write explicitly. If OUTPUT procedure Is used, then file3 should be opened and the required records from

sort work file should be RETURNed to it. Once AT END is reached for sort- ,...-

work-file. close the output file. /..; ~ tJ)..J G

Syntax: RETURN sort-work-file-name AT END imperative statement

INP.m' PROCEDURE Vs OUTPUT PROCEDURE

V Sometimes it would be more efficient to process data before it is sorted, whereas other times it is more efficient to process after it is sorted. If we intend to eliminate more records. then it would be better preprocess them before feeding to SORT. If we want to eliminate all ~e records having sp~ces In the key fleld then it would be efficient if we eliminate them after sortmg. After the sorting. the records with blank key come first.

MERGE

It Is same as sort but USING is mandatory. There should be minimum two files In USING. The MERGE verb takes two or more identically sequenced files and combines them. according to the key values specified. The combined file Is then sent to an output file or an OUTPUT PROCEDURE.

Syntax:

MERGE <sort-work-file> ON ASCENDING KEY dataname 1 dataname2

USING file 1 fIIe2

GMNG me3. / OUTPUT PROCEDURE is sectlon-l END-MERGE

V Program Sort Registers (and Its Equivalent DFSORT Parameter /MeaningJ SORT-FILE-SIZE (FILSZ), SORT-CORE-SIZE (RESINV), SORTMSG(MSGDDN),SORT-MODE-SIZE (SMS=nnnnn), SORT-RETURN(returnCode) & SORT-CONTROL(control card name - default is IGZSRTCD)

If the COBOL programs calls DFSORT, then the SORT control statements can be given in the JCL DD DFSPARM or $ORrPARM.

INTRINSIC FUNCTIONS

Functions return values on passing

on a broad level categorized as NUmeric(tha~gutments to them. ~nctions and Non-Numeric function (that returns -onl re urn only numeric values) (that returns non-numeric or numerte aI ' Yb ~ond-numedc value) and Mixed

Numeric functi ' v. _ ue ase on arguments)

COMPUTE statement Wh~~a:e~~rns value to the target Variable of the variable of the MOVE tat n-numeric function returns value to target COBOL, one function :an e~~~t. Note that nested function is allowed in another set of arguments. an argument as other function that has

Number Handling LENGTH
MAX MIN
NUMVAL NUMVAL-C
Date and Time ORD-MAX ORD-MIN
CURRENT-DATE WHEN-COMPILED
DATE-OF-INTEGER INTEGER-OF-DA1'E
DAY-OF-INTEGER lNTEGER-OF-DAY
DA1'E- TO- YYi'YMMDD DAY· 1'0- YYYYDDD
DATEVAL UNDATE
Ftnance YEAR-TO- YYYY YEARWINDOW
Mathematics ANNUI1Y PRESENT-VALUE
SIN COS
ASIN ACOS TAN
INTEGER INTEGER-PART ATAN
LOG REM
SUM LOGIO MOD
FACTORIAL SQRT
Statistics MEAN MEDIAN
RANDOM
RANGE MID-RANGE
Non-Numeric VARIANCE STANTARD-DEVIATION
UPPER-CASE WWER-CASE
REVERSE CHAR Notes on Selected Function:

Function Explanation
LENGTH Re~~ the length of PIC clause and not the String
• I
I "NUMVAL en .
Returns the numeric value represented by the
=umeric string specJfied in the argument
AL-C does the same but ignore anycurr~n I
ll~mma/deClmal pOints conversion. They are Prim~
CURRENT- R~~d fornumeric operation onnumeric edited numb;rs
DATE e urns 21 chars alphanumeric value '.
(I1f rMMDDHHMMSSnnnnnnJ 98

Mainframe .Refresher Part-I

99

VLanguage Environment and LE Callable Services

The Language Environment offers a common runtime environment for all the high-level language applications written in COBOL, PL/I, or C. LE makes Inter-language communication in mixed-language applications easier. more efficient, and more consistent. LE/VSE also combines essential runtime services, such as routines for run-time message handling, condition handling, and storage management, The library of callable services also includes math services, date and time services. Some of the most useful LE services/functions are given below:

Service Purpose
CEECBLDY Convert Date into a COBOL Lilian date format
CEEDATE Convert Lllian Date to character format such as
"1992/07/25."
CEEDATM Convert Seconds to timestamp of seconds since 14 October
1582
CEEDAYS Convert Date into a Lilian format. (num of days since 14
October 1582)
CEEDYWK Calculate day of week from Lilian as a number between 1 and
7
CEEGMT Get Current Greenwich Mean Time (GMT) as a Lilian date
CEEGMTO Difference b/w the local system time and Greenwich Mean
Time
CEEISEC Converts year into the number of seconds since 14 October
1582.
CEEWCT Returns the current local time in any of the three formats
1 . Lilian date (the number of days since 14 October 1582)
2. Lilian timestamp (the number of seconds since 00:00:00
14 October 1582)
3. Gregorian character string (in the form
YYYYMMDDHHMISS999)
CEEQCEN Queries the century within which LE assumes 2-dil!lt year
CEESCEN Sets the century where LE assumes 2-dil!it year values lie
CEESCOL Comoares two character strings based on the collatina
, ample LE Service Call from COBOL to get Gregorian date:

01 LILIAN PIC S9(9) BINARY .

01 SECONDS COMP-2.

01 GREGORN PIC X (17) ,

01 Fe.

02 Condition-Token-Value. COPY CEEIGZCT.

CALL 'CEELOCT' USING LILIAN, SECONDS, GREGORN, FC. IF CEEOOO of FC THEN

DISPLAY 'Local Time is • GREGORN

END-IF

Mainframe Refresber Part-I

FILE JIAND.LDlG

A data file is collection of relevant records and a record is collection of relevant fields. The file handling In COBOL program Involves five steps.

Steps In File-Handing

» Allocation: The flles used in the program should be declared in FILE-CONTROL paragraph of environment division. The mapping With JCL DDNAME Is done here. The file is allocated to your program by this statement.

» Definition: The layout of the file and its attributes are defined in the FILE SECTION of DATA DMSION.

» Open: Dataset is connected/readied to your program using OPEN statement, The mode of OPEN decides the operation allowed and the tnltial pointer In the dataset. For example, EXTEND mode allows only write access and the pointer is kept on the end of file to append.

}> Process: Process the file as per requirement. using the 1-0 statements provided by COBOL. (READ, WRITE. REWRITE and

DELETE) .

» Close: After the processing, close the file to disconnect it from the program.

Step 1: Allocation of File

SELECT Statement

(ENVIRONMENT-> INPUT-OUTPUT-> FTLE-CONTROL}

SELECT [OPTIONAL] FILENAME ASSIGN to DDNllME ORGANIZATIN IS SEQUENTIAL/INDEXED/RELATIVE ACCESS IS SEQUNETIAL/RANDOM/DYNAMIC

RECORD KEY IS FILE-KEY1

RELATIVE KEY IS WS-RRN

ALTERNARE RECORD KEY IS FILE-KEY2 WITH DUFLICATES ALTERNARE RECORD KEY IS FILE-KEY3 WITHOUT DUPLICATES FILE STATUS IS WS-FILE-STATl

r. WS-FILE-STAT2]

OPTIONAL Clause

This can be coded only for Input files. If OPTIONAL Is not coded, then the input file is expected to present in JCL. If not. an execution error Will occur.

If OPTIONAL Is 'coded, then .If the me Is not mapped In JCL. it is considered as empty file and the first read results end of me.

The me can also be dynamfcaUyanocated instead of static allocation

in JCL.

Mainframe Refrel!ber Part-I

101

ASSIGN TO

FILENAME is the logical. name used inside. the program and

. . ~ 10 'cal name In the JCL. mapped with physl~al data~et.

DDNAME is the ,gJ ., •• d. with 'UT-S-' to Indicate QSAM file. UT-AS- to

DDNAME can be prenxe .. .', '. ,. S ill

: dl 1D ESDS me and with no prefix to tndtcate KSDS/RRD - e.. ..th

ill ca e . . tin' g the program should have a dataset Wi

JCL step execu . '.',

DDNAME as label

//DDNAME

DD DSN=BPMAIN.EMPLOYEE.DATA,DISP=SHR

ORGANIZATION

It can be SEQUENTIAL (PS or VSAM &.SDS). INDEXED (VSAM KSDS), RE.LATIVE (VSAM RRDS). Default is Sequential.

~CCESSMODE

}> SEQUENTIAL ONLY

I default access mode and it is used to access the. records '.

!~ :equential order. To read 100th record, first 99 records need to be read and skipped.

RANDOM . . i 'th

Records can be randomly accessed in the program us nge

rimary I alternate key of indexed file organization or. relative recor~ ~umber of relative organization. 100th record. can directly be ;e:ar after getting the address of the record from the INDEXpa . files INDEXED fIles.IOOth record can directly be read for RELATIVE without any index.

DYNAMIC . d I .. ndom as It Is mtx:ed access mode where the file can be accesse . n raJ •• " th _

well as sequential mode in the program. Example. Reading e

details of all. the employees between 1000-2000. :I~st t~~n~~gg~ access 1000th employee record, then read sequen a. y 'd t'

I d ST-·" D'1' and READ NEXT commands are use lor

emp oyee recor .. ,"""'.. ,..._

this purpose in e procedure diVISIOn.

RECORD KEY IS

It is primary key of VSAM KSDS file. It should be unique and part of indexed record structure,

ALTERNATE RECORD KEY IS

fll d n d tth AIX Add the clause This phrase Is used for KSDS .. ~s ~uneWi_. ..

WITH DUPLICATES if the AIX is defined WIth dupllcates: .

- - Referrm to VSAM basics. every alternate mdex. record ~as an . t d ' PA'THg and the path should be allocated in the JCL that invokes

assocla e rio. _.. .-

this program.

Mainhame Refresher Part-I b ~

f\ J..-.. vjfjrvt rV'l

1)v 'r Old.

(The DDNAM"E of the path should be DDNAME of the base cluster suftlxed with 1 for the first alternate record clause, suffixed with n for nth ALTERNATE RECORD KEY clause in SELECT clause.

FILE STATUS IS WS-rllE-8TAT1.WS-FILE-8TAT2

WS-FILE-STATl should be defined as PIC )((0.2) in working storage secUon. After every file ope.ration, the file status should be cbecked for allowable values.

WS-Fl1£-STAT2 can be coded for VSAM files to get the VSAM return code (2 bytes), VSAM function-code (1 bytel and VSAM feedback code (3 bytes). This is a 6- byte field in working storage.

RESERVE Clause

REsERVE clause (RESERVE integer AREA J can be coded In the SELECT statement. The number of buffers to be allocated for the file is coded

here.

By default two buffers will be allocated if the clause is not coded.

Since Similar option is available in JCL. this is 110t coded in program.

RESERVE 1 AREA allocates one buffer. for the me In the SELECT statement.

Step2 : Defining the File In FILE SECTION

PO FILENAME

RECORDING MODE IS VIVB/F/FS

RECORD CONTAINS M CHARACTERS (TO N CHARACTERS)

SLOCK CONTAINS X CHARACTERS/RECORDS (TO Y CHARACTERS/RECORDS) LABEL RECORDS ARE OMITTED/STANDARD

DATA RECORD Is FILE-RECORD.

01 FILE-RECORD PIC X (nnn) .

FD-RECORD CONTAINS

It specifies the length of the record In terms of bytes. (It will be RECORD contains m to n CHARACTERS for variable format files)

FD-BLOCK CONTAINS

It specifies the phYSical record size. It can be mentioned as number of logtcal records OR number of characters, that is multiple of logical record length. It is suggested to code BLOCK CONTAINS 0. RECORDS so that system will decide the optimum size for the file based on the device used for storing the me. BLOCK CONTAINS clause Is treated as comments for VSAM" flies.

Advantage of Blocking

l> 1-0 time is reduced as n numbers of records are read into main memory buffer during an 1-0.

l> Inter record gap (rRG) is removed and the gap exist only between blocks. So memory wastage due to IRG is aVOided.

Mainframe Refresber Part-I

103

FD-RECORDING MOD:Dl V.(VARlABLE) FB(FIXED BLOCK) VB[VARIABLE It can be F (F

BWCKEDl ...

Varlableflle Identificati.on. d tains clause it is s. till

di de /recor con. . .

If there Is no recor mg mo d If there is an OCCURS depending

possible to identify variable length {ec~r ~d every 0.1 level is of different size, on clause or there are multiple 01 1 eve ~ M ltiple 0. 1 levels in File section is then the file would be of variable eng . . u

an example for implicit redefinition.

D LABEL RECORDS Clause

F - . . . ·RDS STANDARD Is coded for

As a general rule, LABEL REC~E O:rhED is coded for printer

disk and tape files. ~EL REC?RDS datory clause whereas COBOLBS

files. In COBOL74, this clause IS a man

made this as optional.

FD-DATA RECORD IS Clause

recordls) of theme. More than one It is used to name the data

record can be coded here.

Step3: Open the File with OPEN Statement

Syntax: OPEN OPENMODE FILENAMEI 0 EXTEND OPENMODE can be INPUT OUTPUT -

Open Mode INPUT

OUT~P~U~~T==~~~~~~~~~~~~~~~~~~gj~~~=o=se=.==

I-O~~ ~=t:Illi~~~:Qg_~~~~~:z....:..:....:;:..::.=-:... __ ~ND

Step4: Do the I/O as per Requirement

READ Statement til

READ statement is used to read thedre)co(~E~o~ ~jLE~'KEY1J

ENAME (INTO ws-recor .

Syntax: READ FIL 10 KEY imperative statementl)

[AT END/INVAL ·V"LID KEY imperative ~tatement2)

[NOT AT END/NOT IN ~

END-READ . h file is directly read into working

lf INTO clause is coded. then~e Id another move of me- sectionstorage section record. It Is preferred as I bv simt Ie READ. READ~INTO is not record to working-storage-recor~ fOll~wedr::len~ of the-record being read is preferred for variable sfze reCOL s;; ~~e accessing a record randomly using

not known. KEY IS clause is use w _

primary/alternate record key. d during sequential READ of the

. AT END andNOT AT END are use d during random read of the

meJNVALID KEY and NOT [NVALT ~y~: ~~~ field should h~ve a value file.Before accessing the file ran 0 y,

before READ.

Mainframe Refresher Part-I

WRITE. Statement

Write statement is used to write .

opened in EXTEND mode the r d a new recordIn the file. If the file is

OtITPUT mode, the record wi~ ~:c~~d~~~appended. Ift~.e file is opened in avoids the explicit move of working stoi g e cUdITent poslti~n. FROM clause WRITE. - ra e recor to file section record before

Syntax: IiRITE FILE-RECORD [.FROM ws-record]

[INVALID KEY imperative statementl] END-WRITE

REWRITE Statement

_ . REWRITE is used to update an alread read record in a file, the file should be opened in 1-0 :Ode.

Syntax:

record. To update a

REWRITE FILE-RECORD [FROM ws-record] [INVALID KEY imperative statementl!

END-REWRITE

START Statement

START Is used with d I

establishes th. e. current location rnamth c lacctessfi mode of indexed files. I.t

Sf ......... it 1f ' e c us er or READ NEXT stat

~1 se does not retrieve any record. ement.

Syntax: START FILENAME

KEY is EQUAL TO/NOT LESS TH

. AN/GREATER THAN key-name

[INVALID KEY imperative statementl]

END-START.

DELETE Stateme!lt

DELETE is used to delete the m t t1

To delete a record the me sho Id b os . recen y read record in the file.

, u e opened In roo mode.

Syntax: DELETE FILENAME RECORD

[INVALID KEY imperative statementl] END-DELETE

Step5: Close the File with. CLOSE Statement The used files are closed u I g CLOSE

the files, the completion of the· p a ng 1 statement. rf you don't close program. ro ram cases all themes used in the

Syntax: CLOSE FILENAME

OPEN and CLOSE for TAPE Files Advanced

If more than one file is t d t

file Volume. When one file is st s dO~ In a reel of tape, i.t is called as multi-

as multJ-volume label. One reel~:e kno~ore than one reel of tape, it is called volume is reached. automatlcall the n as one volume. When the end of one special control is needed for mUltiVOlume e:ies~olume opens, So there Is nn

104

Mainframe Refresher Part-I

105

OPEN INPUT file-l [WITH NO REWIND I REVERSED] OPEN OUTPUT file-2 (WITH NO REWIND]

CLOSE file-3 [(REELIUNIT) [WITH NO REWIND I FOR REMOVAL] CLOSE file-3 [WITH NO REWINDILOCK]

UNIT and REEL are synonyms.

After opening a TAPE file, the rue is positioned at its beginning.

When opening the file if the clause REVERSED is coded, then the rue can be read in the REVERSE direction. (Provided hardware supportsthrs feature) When you close the file, the tape is normally rewound. The NO REWIND clause specifies that the TAPE should be left in its current position.

CLOSE statement with REEL option closes the current reel alone.

So the next READ will get the first record of next REEL. This will be useful when you want skip all the records in the first reel after n number of records processing.

Since TAPE is sequential device. if you create multiple files in the same TAPE, then before opening the second file, first file should be closed. At any point of time, you can have onJy one file is active in the program, In addition to this, you have to code MULTIPLE FILE Clause In the 1-0 control paragraph of environment dtvislon ..

MULTIPLE FILE TAPE CONTAINS OUT-FILEl POSITION 1

OUT-FILE3 POSITION 3

The rues OUT-FILEl and OUT-FILE3 used in the program are part of a same TAPE and they exist in first and third position In the tape. Alternatively, this information can be passed from JCL using LABEL parameter.

File Error - Handling

There are chances for failure of any file 1-0 processing. The failure of an 1-0 operation can be accepted or cannot be tolerated. The severity of failure has to be defined in the program design stage.

. Let us assume that we don't have any error handling in our program. For example, if you don't have a specific record in the file, the random read of that record would immediately terminate the program with error 'record not found'.

Error Handling Clauses Provided by COBOL

The sudden termination can be avoided by handling this error, with INVALID KEY clause of READ. Based on the importance of the record and business rule. we can continue our program with next record or terminate the program properly.

AT END is another error handling clause provided by COBOL. But there is no way to handle all such errors in this way.

Assign FiIe-Status and Take the ResponsibiIity

The second method is, assigning file-status to the file in the SELECT clause and checks the file status after each and every 1-0 and ensures that the value of status code is one of the allowable values. If it is not an allowable return code, then abnormally end the program with error statements that would be easier to debug.

Mafnframe Refresher Part-I

But we have to do this checldng aft h ~

This Is MOST PREFERRED ERROR er eac and every T-O operation.

programming. HANDUNG METHOD in structured

DECLARATlVES - USE Statement

COBOL provides an Option to gro all th

operation{s) in a place and that will be up ~ possible errors of specific

respectfve ~ operatiorusj of anylUe. This aV~i~~~~~:~~ invoked durtng the

ThIs is done in DECLARATIVE . . t code.

DECLARATIVE should be the fir ttl section of the procedure division.

- s sec on in the procedure division If coded.

PROCEDURE DIVISION. DECLARATIVES. USE-PROCEDURE SECTION.

USE AFTER EXCEPTION PROCEDURE ON INPUT ERROR-PROCEDURE.

Check the file-status code for validity

END-DECLARATIVES. .

Whenever there is an error j th

INPUT mode. then the control comes ~ e processing of ANY FILE opened in

error should be checked in this ara 0 E~OR-PROCEDURE. The valtdtty of down, based on severity of e~or gra~ anTh~ d allow or restrict the process statements is: ~ co e. e complete syntax of USE

USE AFTER STANDARD ERRORIEXCEPTION PROCEDURE ON

INPUT J OUTPUT J 1-01 EXTENO 1 file-l

If INPUT Is coded. the foHoWing raced will·~

involved in any file that is opentct in I~{h ~e executed for every operation have the Same meanin but h . mo e. OUTPUT, l-O and. EXTEND in. the USE statement. ~en :n eth~oi~e IS .different. If file name (file-l) Is coded will be checked. ERROR and EXCEPtiouNt output operation of that specific file

Th P . . are synonyms.

erocedure written in a OECLARAT

to any non-declarative procedure writt _" thIVE section should not refer versa, en arter e end procedure and vice-

USE FOR DEBUGGING ALL PROCEDURE DEBUG -DECLARATIVES -PARA. DISPLAY "TRACING END DECLARATIVES.

DEBUG-NAME

This declarative section of the ro ram

execution of each paragraph d~fing d i ~ ~ be executed before the start of name" will be displayed before th e n re program. t.e. 'TRACING para-

NAME is e execution of each paragra h DEB

.. the special register that contains th .. . . p. ~ UG-

executed. e name of the paragraph being

106

llalDframe Refresher Part-I

107

!-O-CONTROL

The I-O control paragraph of the INPUT-OUTPUT SECfION specifies when checkpoints are to be taken and which storage areas are to be shared by different files. It also specifies information needed for efficient transmission of data between external media and the COBOL program. TWs paragraph is optional in a COBOL program.

The keyword I-a-CONTROL may appear only once, at the beginning of the paragraph. The word I-O-CONTROL must begin in Area A and must be followed by a separator period.

Each clause within the paragraph may be separated from the next clause by a separator comma or a separator semicolon. The order In which I-O-CONTROL paragraph clauses are wrttten is not Significant. The 1-0- CONTROL paragraph ends with a separator period.

I-O-CONTROL- SAME AREA AND SAME RECORD AREA

RESERVE clause of SELECf statement specifies the number of buffers to be allocated for a file. SAME AREA allows more than one file to use the same buffer area. This will be very useful when the program must work with a limited memory space. But the problem is only one file should be open at a time If SAME AREA is coded.

Syntax: SAME AREAFIOR lUe-1 tue-2 fIle-3.

If SAME RECORD AREA Is coded, then the buffer is not shared but only the record area is shared. So more than one file can be in open state. We should be careful while .filling In the record area of the output flle. This may destroy the record read most recently.

Syntax: SAME RECORD AREA FOR file-l lUe-2 file-3.

SAME SORT AREA allows more than one sort/merge work files to use the same area. The sort work files are automatically allocated when file is opened and de-allocated when me Is closed. As the sort file is automatically opened and closed during a SORT and two sort mes cannot be opened at a time, this clause may not be useful.

Syntax: SAME SORT I SORT-MERGE AREA for file-l file-2.

File-lor file-2 should be a SO file.

1-0 CONTROL- RERUN Clause

RERUN ON rescue FOR EVERY integer RECORDS on ffle-I

This will cause checkpoint to be taken for every integer-l records processing of file-L If the program ABENDEO before the complete processing of the rueL then the program will restart from lntegel"+lST record instead of first record. The rescue file details should be mentioned outside the program and it varies from installation to Installation.

Mainframe Refresher Part-I

F1L.E STATUS CODES

ItIs a two-byte working storage item. The first byte denotes the general category whereas second byte denotes the particular type of en-or message under that category.

a Successful OPENjREAD/WRlTE Operation
0 Successful completion
2 Duplicate key was detected which is allowed as per definition of AIX.
4 Length of record just READ didn't conform to the fixed length
attributes for the rue.
S Referenced Optional file is not present during OPEN. If open mode is 1-
o or EXTEND. then file will be created.
7 Open or Close statement is executed with a phrase that implies a tape
file (ex NOREWlND) whereas tbeflle Is not in TAPE.
1 When AT END condition fails
0 Sequential READ Is attempted after the end of file is reached
4 Sequential READ was attempted for a relative file and RRN is larger
than the maximum that can be stored in the relative key data item.
2 When INDEX Key fails
1 Sequence error exists for sequentially accessed index file.
2 Attempt was made to write a record that would create a duplicate key.
3 Record not found.(for keyed random access)
4 Space not found for WRITE
3 Permanent Open error
5 Opening a: non-optional file that was not present.
7 Open mode is not permitted.
8 Open issued for a file that was closed previously with Jock
9 File attribute mismatch-Open failed.
4 Logic error in opening/closing/deleting
1 OPEN a opened file.
2 CLOSE attempted for not opened file.
3 10 statement before the current REWRITE/DELETE is not successful.
4 REWRlTE attempt with Invalid length
7 READ file which is not opened in INPtrr or 1-0 mode
8 WRITE file which is not opened In 1-0 OUPUT or EXTEND mode
9 DELETE or REWRITE flIe which is not opened in 1-0 mode.
9 Implementation defined
I 1 VSAM password error
2 logic error
I I 3 VSAM resource unavailable
6 No DD statement specified for VSAM file.
7 OPEN statement execution successful: File integrity verified. (indicates
the file was not prol'_erly closed I:Jy_ the last iob that had it opened) 108

MalDframe Refresher part-I

109

COBOL COMPILATION

dul . ts of two stages -

Creation of COBOL load roo e consis in the compilation

. , tlon and Link Edit. The various DDs involved

~~:~~: and the sample compilation JCL are given below.

5'!:'SPItINr [C<=pj.IG' lJ&~

(&ur<z,J

3YSll5 (15u.br=_ L;b<axyJ

'S'{mRINI'

[LUok edit melD!!elj

cOMPn.ATION JCL

IIMUTHUB JOB ,'COMPILATION JCL', _

/1 MSGCLASS=Q,MSGLEVEL=(l,l),CLASS-C

IICOMPILEl EXEC PGM=IGYCRCTL, _

II PARM='XREF,APO,ADV,MAP, LIST) ,REGION-OM

DD DSN=SYS1.COB2LIB,DISP=SHR

//~~~~~IB DO DSN=QUEST.SOURCE(SAMPG1'/0l),DISP=SHR

~~SYSLIB DO DSN=QUEST.COPYLIB,DISP=SHR

/ISYSPRINT DD SYSOUT=*

/ISYSLIN DO DSN=&&LOADSET,

II DCB=(P.ECFM=FB,LRECL=80,BLKSIZE=3200),

II DISP=(NEW,PASS),UNIT=SYSDA,

II SPACE=(CYL, (5,10),RLSE), .

1/* code SYSUTl to SYSUTl for work allocatlon

/ISYSUT1 DD UNIT=&SYSDA, SPACE= (~YL' (1,10))

/ILINKEDT1 EXEC PGM=IEWL,COND=(4,L)

DO DSN=&&LOADSET,DISP=(OLD,OELETE)

/!SYSLIN DD DSN=QUEST.LOADLIB[SAMPGM01),DISP=SHR

IISYSLMOO B DISP=SHR

IISYSLIB DD DSN=QUEST.LOADLI,

1 DD UNIT=SYSDA SPACE=(CYL, (1,10»

!!SYSUT '

I/SYSPRINT DO SYSOUT=*

11*** EXECUTE THE !!EXECUTEl EXEC

I!STEPLIB DO

I/SYSOUT DD

!ISYSPRINT DO

PROGRAM *** PGM=SAMPPGM01,COND=(4,LT),REGION=OM

DSN=QUEST.LOAOLIB,DISP=SHR

SYSOUT=* &

SYSOUT=*

Mainframe Refresher Part-!

Compiler Options

The default options that were set up when YOUT compiler was installed are in effect for your program unless you override them with other options. To check the default compiler options of your Installatton, do a compile and check in thecomptlatton listing.

Ways of overriding the default option

};> Compller options can be passed to COBOL Compiler Program (IGYCRCTL) through the PARM in JCL.

:> PROCESS or CBL statement with compiler options, can be placed before the Identification division.

};> If the organization uses any third party product or its own utility then these options can be coded in the pre-defined line of the utility panel.

Precedence of Compiler Options

};> (Highest precedence). Installation defauits,flxed by the installation. };> Options coded on PROCESS JCBL statement

};> Options coded on JCL PARM parameters

};> (Lowest Precedence). Installation defaults. but not ftxed.

The complete hst of compiler option is in the table:

Aspect Compiler Option
Source Language APOST, CMPR2, CURRENCY, DBCS, LIB, NUMBER,
QUOTE, SEQUENCE, WORD
I Date Processing DATEPROC, INTDATE. YEARWlNDOW
Maps and Listing LANGUAGE, LINECOUNT, LIST, MAP, OFFSET,
SOURCE,SPACE,TERNUNAL,VBREF,XREF
Object Deck COMPILE. DECK, NAME, OBJECT, PGMNAME
generation
Object Code ADV. AWO, DLL, EXPORTALL, FASTSRT. OPTIMIZE,
Control NUMPROC,OUTDD,TRUNC,ZWB
Debugging DUMP. FLAG, FLAGMIG, FLAGSTD, SSRANGE,
1YPECHK
Other ADATA, ANALYZE, .EXIT, IDLGEN Compiler Option Meanlna
AWO (Apply Enable this option to get optimum use of buffer and
WRITE Only) device space. This Is meaningful only fOT variable
recording mode files. It results in fewer calls to data
management services to handle 1/0. A buffer is
truncated only when the next record does not fit in the
unused portion of the buffer. With NOAWO, buffer is
truncated when it does not enough space for a
maximum size record.
DATA(3l) It allocates the buffers in unrestricted storage and avoid
Virtual storage constraint problems. 110

lIalDframe Refresher Part-I

111

NUMPROC(PFD). Invalid sign processing is bypassed for numeric
operations and so slgniflcantly more efficient code will be
generated for numeric comparison. The extra code for
fix-up sign field is generated if the compiler option is
NUMPROC(MIG) or NUMPROC[NOPFD}.
OPTIMIZE Use this option before implementing the code in
production to produce optimized code. As compilation
time will be more when this option is used, this is
usually not preferred for development region
compilation.
NOSSRANGE Use this option to avoid boundary check for every array
operation. SSRANGE includes additional code for this
kind of check.
RMODE(ANYl The )lrogram can be loaded anywhere in memory
RENT This option should be given to generate are-entrant
program that can be placed In shared storage
(LPA/ELPA) for faster execution. It generates additional
code to ensure that the program isre-entrant.
TRUNC[OPT) With this option, the compiler assumes that the data
conforms to the PIC clause and USAGE specifications.
TRUNC(STD) and TRUNC(BIN) generates additional code
to truncate the receiving fields on arithmetic operations.
FASTSRT This option specifies the IBM DFSORT to handle I/O and
so eliminates the overhead of returning to COBOL after
each record is processed. Note that this option will be
effective only for direct sort work files and not all sort
files.
LIST and OFFSET are mutually exclusive. If you use
LIST/OFFSET both, LIST will be Ignored. LIST is used to produce
listing of the assembler language expansion of your
code. OFFSET is used to produce a. condensed
Procedure Division listing.
With OFFSET, the procedure portion of the listing will
contain line numbers, statement references, and the
location of the first instruction generated for each
statement. These options are useful for solving system
I ABENDS. Refer JCL session for more detaJls.
MAP Use MAP to produce a listing of the Items you defined in
the Data Division.
RESIDENT Use the RESIDENT option to request the COBOL Library
Management Feature. (The COBOL Library Management
Feature causes most COBOL library routines to be
located dynamically at run time, Instead of being l1nk-
edited with the COBOL program.}.eICS Programs should
be complied with RESIENT option.
XREF Use XREF to get a sorted cross-reference listing. EBCIJ
and procedure-names w:ilI be listed in alphanumeric 0
includes listing. where all the data-names that are re
your program and the line number where they are definer
for identifying the fields that are defined but not used any
development of new program. ..

Reports - FBA (ADV CompHer Option)

Reports contain the printing control character in the first byte Reports usually have FBA format and. there will be printing control characte; ill the first byte of the file. Most of the reports would have LRECL 133. The population of printing control character can be done In two ways.

Define the me with 133 bytes and populate the first byte with appropriate printing control character as given in the below table.

Define the me with 132 bytes in program and use the COBOL printing verbs like AFTER ADVAINCING and on referring this ADVANCING clause. the COBOL compiler automatically add 1 byte prefix to the existing 132 byte layout with light printing control character. To do this, ADV compiler option should be enabled but this is the default enabled option. Also note that the actual physical length mentioned in the JCL will be 133.. '

Printing control character Equivalent COBOL statement
. (blank) After advancing 1 line
0 After advancinl! .2 lines
- . After advancing 3 lines
+ After advancing 0 lines
1 After new page Identifying Unreferenced Data Names In the COBOL Program

)- Look at the ~at_a name cross reference list that Is printed in your compilatlon listing and double check the declarations that do not have cross reference !Jne number and remove It.

)- Compile the code with OPTIMlZE(FULL) and th.ls will remove unreferenced . d~ta items as well as unnecessary brancbes. This produces optimized load module with cost of addltlonal CPU time during compilation.

COBOL Performance Twrlng

o

Structured Programming:

Use Structured Programming statements so that the program Is readable and the optimizer can then operate on larger region of the program that gives you more ,efficIent code.

Avoid the following:

.:. ALTER

·to Un-Controlled GOTO .:. Backward branches

Cl

Don't use 66 levels. COBOL provides excellent structuring breakage by level numbers. Use that feature rather than 66 levels.

o Don't use 77 independent declarations. Instead group all such items into categories and declare under 01 level.

[J Use 88 level declarations for switches / condition names. This provides excellent readability for the program. In the below code IF US-CUSTOMER makes the code readability better than IF CUSTOMER-CODE = '001'

01 CUSTOMER-CODE PIC X(03).

aa INDIAN-CUSTOMER VALUE '091'. aa US-CUSTOMER VALUE '001'.

IF US-CUSTOME;R

END-IF

o Increment the level numbers by an odd number in order to allow for the Insertion of extra levels during modification. This reduces the need for whole renumbering later. [Code 01,05,10,15 ... )

o Paragraphs OR sections should be used. They should not be mixed except when the paragraphs are used to sub diVide the section. In this case. only sections should be executed.

[J Try to use external sorts/merge than program sort/merge (internal).

With an internal sort. control Is passed back to the program after each record and thus reducing the speed of the sort. You may use FASTSRT compiler option to avoid this provided the sort Is on files directly. And also try to have the sort fields at the start of the record and as contiguous as possible for better performance.

o GOTO should not used. At the worst case. controlled GO TO Is okay (GO TO that transfers the control to the end of the section or paragraph that is being performed)

[J Prefer EVALUATE over nested IF statement.

o

Always code ON OVERFLOW with STRING and UNSTRING otherwise you will not be notified with incomplete operation and the control will pass to the next sequential statement.

End all structures with explicit scope terminator for readability and to avoid any false fall through, (END-ADD, END-SUBTRACT. ENDMULTIPLY. END-DMDE. END-COMPUTE. END-READ. ENDWRITE, END-REWRITE, END-START, END-DELETE, END-CALL. END-STRING. END-UNSTRING)

o

o

Have separate paragraphs for every different I/O for every file used in the program. This is to reduce the load module size as the machine Instructions generated for the execution of PERFORM are less than that for a READ OR WRITE. Also maintenance will be easy when one code is in only one place.

Mainframe Refresher Part-I

o Table access: Define the table with INDEX and use SEARCH or SEARCH ALL to retrieve the data. Prefer SEARCH when the number of data is less or most of the data is retrieved from the few first rows only. Prefer SEARCH ALL when the number of data is more and they are available In sorted order.

[J Use INDEX than Subscript to access tables. INDEX points to direct displacement and so will be much faster than subscript that potnts to occurrence. When we use subscript displacement will be calculated at the run time from the occurrence and size of array.

[J Declare logic switches with one byte alphanumeric, By this declaration, compiler will generate 4 byte compare immediate instruction. The instructions created for n byte alphanumeric or numeric will be more than this.

[J Code BLOCK CONTAINS 0 RECORDS clause for all output files. If this is not coded, then the output file will be unblocked and this will create waste of disk space, unnecessary I/O. increase inn disk usage/ CPU time and run time.

o Whenever possible, always use same format numeric Variables in calculation. If you add a CaMP to COMP-3, then compiler needs to convert one to other format before addition.

[J Prefer the usage of computational items than display items for any mathematical operation. Use CaMP for eight or fewer bytes calculation and COMP-3 for more than 8 bytes calculation. Always prefer CaMP for subscripts/indexes. Code'S' (sign) for all computational declarations. Use odd number of digits in the declaration of COMP-3 for complete usage of allocated memory.

[J In all the compute operations, code the constant portion first and then any other expressions / operations.

[J Look into the listing of your program and check the compiler options used and ensure that all the applicable allowed performance related compiler options are in effect in your program.

114

Database · 2 ( DB21

d for a novice programmer to read and Covera~ DB2 has been a~~:~e aU the basic, advanced concepts. as well as understand. Even though th ' tililitUe scope for expansion m the next . . tuffs are covered, ere 1S s d

~\~~::ssthe product itself being continu<iusly upgrade .

Sign up to vote on this title
UsefulNot useful