Transcript Slide 1
®
IBM Software Group
Enterprise COBOL Education Using Rational Developer for System Z
COBOL General Language Rules
Jon Sayles, IBM Software Group, Rational EcoSystems Team
© 2006 IBM Corporation
IBM Trademarks and Copyrights
© Copyright IBM Corporation 2007,2008, 2009. All rights reserved.
The information contained in these materials is provided for informational purposes
only, and is provided AS IS without warranty of any kind, express or implied. IBM
shall not be responsible for any damages arising out of the use of, or otherwise
related to, these materials. Nothing contained in these materials is intended to, nor
shall have the effect of, creating any warranties or representations from IBM or its
suppliers or licensors, or altering the terms and conditions of the applicable license
agreement governing the use of IBM software. References in these materials to IBM
products, programs, or services do not imply that they will be available in all countries
in which IBM operates.
This information is based on current IBM product plans and strategy, which are
subject to change by IBM without notice. Product release dates and/or capabilities
referenced in these materials may change at any time at IBM’s sole discretion based
on market opportunities or other factors, and are not intended to be a commitment to
future product or feature availability in any way.
IBM, the IBM logo, the on-demand business logo, Rational, the Rational logo, and
other IBM Rational products and services are trademarks or registered trademarks of
the International Business Machines Corporation, in the United States, other
countries or both. Other company, product, or service names may be trademarks or
service marks of others.
2
Course Contributing Authors
Thanks to the following individuals, for assisting with this course:
David Myers/IBM,
Ka Yin Lam/IBM
John Fenyar
Wilbert Kho/IBM
Steven Wilcenski/Sabre Systems Inc.
Mike Wrzinski/Sentry Insurance
3
Course Description
Course Name: COBOL Foundation Training - with RDz
Course Description: Learn the COBOL language, RDz and learn z/OS terms, concepts and development skills in this course.
Pre-requisites: Some experience in a 3rd or 4th Generation Language is expected. SQL is also recommended.
Course Length: 10 days
Topics (Agenda)
Getting Started - installing and configuring RDz - and the course materials, and using Eclipse to edit COBOL
COBOL General Language Rules
Basic COBOL Statements
Advanced record and table handling
Debugging Programs - Note: Deep dive on using RDz for common COBOL programming errors (001, 0C4, 0C7, infinite loops, fall-thru, etc.)
Input/Output and Report Writing Patterns
Sequential File Match/Merge Patterns
COBOL Subprograms and the Linkage Section
Structured Programming Concepts and Coding Patterns
Advanced Character Manipulation, COBOL Intrinsic Functions, Date and Time coding patterns, and Language Environment calls
OS/390 Concepts and JCL
Compile/Link & Run Procs on the mainframe
Indexed file Coding Patterns
Sort/Merge and Master File Update Coding Patterns
Accessing DB2 Data and Stored Procedures
COBOL in the Real World:
– CICS - lecture only
– IMS (DL/I and TM) - ditto
– Batch processing - ditto
– Java calling COBOL
– COBOL and XML Statements
– SOA and COBOL - creating and calling Web Services
– Web 2.0 using Rich UI
4
Unit
COBOL General Language
Rules
Topics:
Coding COBOL
Identifying Your Program
Describing Your Computing Environment
Describing the Data
Processing the Data
Java and .NET Equivalents
5
Topic objectives
After completing this topic, you should be able to:
Describe the areas of COBOL structured coding – and what kind of COBOL
statements go into each
Define the four DIVISIONs of a COBOL program
List the kinds of alphanumeric characters that can be used in coding COBOL
programs
6
COBOL Character Set
COBOL code is written using:
Alphanumeric characters:
A
0
Z
9
The following special characters:
+
-
*
/
=
$
:
.
, ;
“
‘
(
)
<
>
Note – no underscore
Upper and lower case characters are equivalent (case insensitive), except
when they appear in a character string
On the mainframe, the character set – and collating sequence is EBCDIC
On the PC and on AIX systems, the character set and collating sequence is
ASCII
The differences between EBCDIC manifest themselves at run-time in:
Alphanumeric sort routines and operations
IBM built-in functions that process sorted data (Median, etc.)
7
Statement Format (Basic COBOL Coding Rules)
COBOL program development uses a fixed-column or fixed-position coding style:
Statements must be coded within specified column-numbered area boundaries
Sequence
Numbers
A Area
B Area ----------------------------------------------------------------------------------------------------------------------------
Version Control
Numbers
Columns 1 6 contain an optional (rarely used) sequence number for ordering
statements
Column 7 indicates either:
COBOL comment line – by typing an asterisk * in column 7
Multi-line continuation of long literal values - by typing a dash – in column 7
Columns 8 11 are called the “A” or area – with column 8 termed the “A” margin.
Columns 8 11 are reserved for:
Division statements
Procedure names
Certain types of variable declarations
Columns 12 72 are called the “B” area – you code all of your procedural
(business) logic here, as well as the rest of the variable declarations
Columns 73 80 are used by certain Source Code Management Systems for
identifying line changes in versions.
8
See Slide Notes
COBOL Program Units
(The Four Divisions)
Identification
Division
1. IDENTIFICATION
DIVISION, which identifies the
Environment
Division
program with a name and, if optionally
gives other identifying information.
2. ENVIRONMENT DIVISION,
Data
Division
where you describe the aspects of your
program that depend on the computing
environment.
3. DATA DIVISION, where the
characteristics of your data are defined
4. PROCEDURE DIVISION, where
the instructions related to your business
logic are specified.
The PROCEDURE DIVISION of a program is
sub-divided into sections or paragraphs, which
contain executable COBOL sentences and
statements
The Divisions must be coded in the
order described
There are many optional
statements and keywords in the
Divisions
Division and procedure (Paragraph
and Section) names: Begin in the A
margin, must end with a period,
and must be the only statement on
that line
Your program ends when either a
GOBACK or STOP RUN
statement is executed
Procedure
Division
9
See
Notes
Unit
COBOL General Language
Rules
Topics:
Coding COBOL
Identifying Your Program
Describing Your Computing Environment
Describing the Data
Processing the Data
Java and .NET Equivalents
10
Topic objectives
After completing this topic, you should be able to:
Describe the purpose of the IDENTIFICATION DIVISION
List the required elements of it
Code a syntactically correct IDENTIFICATION DIVISION
List a few optional paragraphs and sections of the IDENTIFICATION DIVISION
11
Identifying Your Program – Standard Grammar
IDENTIFICATION DIVISION.
Program-ID. PROGRAM1.
Author. Bill Hudson.
Installation. Computing Labs Inc.
Date-Written. 12/21/2009.
Date-Compiled. 12/30/2009.
Use the IDENTIFICATION DIVISION to name a program and optionally
provide other identifying information.
Required statements:
IDENTIFICATION DIVISION.
PROGRAM-ID. PROGNAME.
You can use the optional AUTHOR, INSTALLATION, DATE-WRITTEN,
and DATE-COMPILED paragraphs for descriptive information about a
program.
The data you enter in the DATE-COMPILED paragraph is replaced with the
latest compilation date.
12
IDENTIFICATION DIVISION – PROGRAM-ID
COBOL Program-ID names must follow these rules:
For mainframe (z/OS) COBOL programs:
Traditionally eight characters
– That restriction has been lifted in current language levels
Name must start with an alphabetic letter
Name can contain only alpha-numerics (letters and 0 – 9)
For PC (“standard”) COBOL programs:
Maximum of thirty characters
Name can contain:
z/Series COBOL
PC
COBO
L
– Alpha-numerics
– The dash
Cannot start or end the Program-ID name with a dash
Note: It is good programming practice to add in-line comments to the top of your
COBOL program. Comments that document:
The business/technical purpose of the program
A program maintenance log
Any unusual or complex coding patterns
13
IDENTIFICATION DIVISION – Optional Statements and Constructs
You can extend the PROGRAM-ID paragraph, with the following optional
keywords that compile programs to allow for extended functionality:
RECURSIVE
– allows a program to be reentrant and called recursively
PROGRAM-ID MYPROG IS RECURSIVE.
INITIAL
– tells the compiler to reset variables to specified initial values upon
program execution
PROGRAM-ID MYPROG IS INITIAL.
CLASS-ID.
Enterprise COBOL provides facilities for developing object-oriented programs
using the COBOL programming language.
OO COBOL programs contain a CLASS-ID paragraph, for defining an OO class,
instead of PROGRAM-ID, which defines a structured program
OO COBOL will be touched on later in this course, as it is considered an
“emerging z/Series technology” in most I/T installations
See slide notes for additional information on OO COBOL
14
Unit
COBOL General Language
Rules
Topics:
Coding COBOL
Identifying Your Program
Describing Your Computing Environment
Describing the Data
Processing the Data
Java and .NET Equivalents
15
Topic objectives
After completing this topic, you should be able to:
Describe the purpose of the ENVIRONMENT DIVISION
List the required elements of it
Code a syntactically correct ENVIRONMENT DIVISION
List a few optional paragraphs and sections of the ENVIRONMENT DIVISION
16
Environment Division – Standard Grammar
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SOURCE-COMPUTER. IBM-3081.
OBJECT-COMPUTER. IBM-3081.
INPUT-OUTPUT SECTION.
SELECT PRINTFILE ASSIGN TO UPDPRINT
ORGANIZATION IS SEQUENTIAL.
Use the ENVIRONMENT DIVISION to identify input and output files for the program,
and to describe aspects of the program that depend on the computing platform.
ENVIRONMENT DIVISION and its sections can be optional.
That is, you will code them when you need to specify elements of your program that
connect to the operational environment your program runs in (example. Reading and
writing to external files)
The ENVIRONMENT DIVISION has two sections:
CONFIGURATION SECTION – Optional section, used to specify the development and run:
Source-Computer – the compiling computer.
Object-Computer – the run-time computer
INPUT-OUTPUT SECTION – Used to define external files used by the program (files are
considered part of your program’s “environment”)
The SELECT/ASSIGN statement is covered on the next slide
Note that: ENVIRONMENT DIVISION, CONFIGURATION SECTION and
INPUT-OUTPUT SECTION are coded in the “A” area of your source code
17
Select/Assign – Input/Output Files and Datasets/Devices
The FILE-CONTROL part of the INPUT-OUTPUT SECTION identifies the external
files your program reads and writes using COBOL “logical” name identifiers
These logical file names in your program, are mapped to a physical input/output
storage device attached to a mainframe (typically disk storage)
By using Select/Assign in your program, you achieve Physical/Logical data
independence - so you won’t have to change your code:
If you move the physical file to a different device
If you point to an altogether different file entirely
All your program cares about is the internal (logical) file name in Select/Assign
The system is responsible to find and attach the correct external dataset
Your program source…
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT INPUT ASSIGN TO INPUT1 (your program’s internal COBOL filename)
…
The mainframe “job”
that runs your program
…
//GO.INPUT1 DD DSN=MY.INPUT,DISP=SHR
Your
Program
External z/OS Dataset (file)
MY.INPUT
18
3990
Disk Pack
Mainframe
ENVIRONMENT DIVISION – Assigning Input/Output Files to Your PC
For the programs in this course, you will use the ENVIRONMENT DIVISION’s
SELECT/ASSIGN clauses to point to ASCII files on your machine.
So your “environment” is the PC, not the mainframe
You will code your Select/Assign clauses for PC files like the following:
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT CUST-FILE
ASSIGN TO "D:\CUST.DAT"
ORGANIZATION IS LINE SEQUENTIAL
ACCESS MODE IS SEQUENTIAL
FILE STATUS IS CFCODE.
SELECT PRINT-FILE
ASSIGN TO "D:\CUSTOUT.DAT"
ORGANIZATION IS LINE SEQUENTIAL
ACCESS MODE IS SEQUENTIAL
FILE STATUS IS PRTCODE.
Internal file name
PC file spec: Drive:\folder\filename.extension
Tells the compiler how to treat the file's I/O
…
Names a variable you can check for I/O errors
Internal file name
PC file spec: Drive:\folder\filename.extension
Tells the compiler how to treat the file's I/O
…
Names a variable you can check for I/O errors
See Slide Notes, for additional File Read/Write performance tips
19
Unit
COBOL General Language
Rules
Topics:
Coding COBOL
Identifying Your Program
Describing Your Computing Environment
Describing Your Program’s Data
Processing the Data
Java and .NET Equivalents
20
Topic objectives
After completing this topic, you should be able to:
Describe the purpose of the DATA DIVISION
List the required elements of it
Code a syntactically correct DATA DIVISION
List a few optional paragraphs and sections of the DATA DIVISION
21
Identifying and Describing Your Program’s Data – Standard Grammar
DATA DIVISION.
FILE SECTION.
…
WORKING-STORAGE SECTION.
…
LINKAGE SECTION.
One of COBOL’s fortes is file handling and data manipulation – which COBOL makes:
Simple – easy to code
Efficient – as pertains to run-time processing efficiency)
Sophisticated – allowing for complex data types and structures
Define the characteristics of your data, and group your data definitions into one of the
sections in the DATA DIVISION.
You can use these sections of the DATA DIVISION to define the following types of
data:
Data used in input-output operations (FILE SECTION)
Data defined for internal processing purposes, calculation fields, flags, counters, etc.
(WORKING-STORAGE SECTION)
Data passed as parameters from another program (LINKAGE SECTION)
22
FILE SECTION – Data used in File Input/Output Operations
DATA DIVISION.
FILE SECTION.
FD internalFileName
RECORD CONTAINS n CHARACTERS
DATA RECORD IS recordVariable.
01
recordVariable.
05 Field1 PIC X(40).
05 Field2 PIC X(40).
Every Select/Assign file in the INPUT-OUTPUT SECTION of the ENVIRONMENT
DIVISION must have a matching FD (File Definition) entry in the FILE SECTION
You follow an FD by the declaration of the data record the file is read into/written from
The RECORD CONTAINS clause is optional – but if explicitly coded, it causes the compiler
to verify the DATA RECORD’s overall length with the “n CHARACTERS” specified
The DATA RECORD clause is also optional, and specifies the COBOL variable that will be
read into, or written from. .
FILE SECTION, FD and the 01 level-number for the record variable are coded in
the “A” area
All other clauses and level-numbers > 01 must begin in the “B” area
Note that we'll cover COBOL level-numbers in a few slides
23
FILE SECTION – Optional Clauses
DATA DIVISION.
FILE SECTION.
FD internalFileName
…
BLOCK CONTAINS n RECORDS
LABEL RECORDS ARE STANDARD.
BLOCK CONTAINS – defines a “blocking factor” for the file.
Blocking factors are I/O efficiency features of COBOL and z/OS
We will cover them later in the course
For mainframe COBOL programs:
Recommendation - code: BLOCK CONTAINS 0 RECORDS
– This allows the compiler to obtain the Blocking Factor directly from the program’s JCL
For PC COBOL programs:
Recommendation – leave this clause out
LABEL RECORDS ARE STANDARD – determines whether there is a label on the
z/OS dataset (external file).
-LABEL RECORDS ARE STANDARD is the default if you omit the clause
-Leave this clause off for PC files, print files and non-labeled datasets
See Notes
24
WORKING-STORAGE SECTION – Declaring Program Work Variables
DATA DIVISION.
FILE SECTION.
…
WORKING-STORAGE SECTION.
77 RECORD-KTR
77 END-OF-FILE-SW
01 StructureVariable.
05 Elementary-num-field
05 Elementary-char-field
PIC 9(4).
PIC X(1) VALUE 'N'.
PIC 9(4).
PIC X(40).
The WORKING-STORAGE SECTION is where you code variables used
throughout your program
All of the variables in the WORKING-STORAGE SECTION are global in
scope (can be referenced throughout your program)
Use WORKING-STORAGE variables for:
Temporary fields used in calculations
Variable names for constant values
Record structures used in data manipulation processing
Switches and flags (i.e. end-of-file)
Print file records and structures
25
WORKING-STORAGE SECTION – Coding COBOL Variables
WORKING-STORAGE SECTION.
77 RECORD-KTR
77 KTR-2
01 STRUCTURE-VARIABLE.
05 ELEM-FIELD
05 END-OF
PIC 9(4) COMP VALUE ZERO.
PIC 9999 COMP VALUE ZERO.
PIC 9(7)V99 COMP-3 VALUE ZERO.
PIC X(40).
COBOL variable names:
Can use alphanumerics and the dash (but don’t start or end a variable name with a dash)
Must be shorter than 30 characters, no embedded blanks , and contain at least one letter
Code individual (single) COBOL variables as follows:
Type a 77 in the “A” area
Type the variable name in the “B” area
Follow the variable name with a “picture clause” – typically abbreviated as: PIC – that describes
the type, size and scale of your variable
End with the variable declaration with a period
Code (related) variables grouped into a structure as follows:
Type a 01 in the “A” area
Type the structure name in the “B” area
Type the remaining variables starting with a number > 01 in the “B” area and follow the above rules
for coding 77 variables
See Slide Notes – for an explanation of COMP and COMP-3
26
WORKING-STORAGE SECTION – PICTURE Clause Definitions
Every COBOL data variable must have a picture clause – typically abbreviated as: PIC
A variable’s picture clause determines:
The type and format of the data stored in the field
Size of the data
Numeric precision (scale, or # of digits to the right and left of the decimal place)
You can code a number inside a parenthesis, which means that the preceding character is repeated “n”
times (see below)
Different PIC clauses are used for input and intermediate calculation results or holding areas
and for output.
Note: We’ll cover input and output picture clauses in-depth, in a subsequent unit of this
course.
The Input or WORKING-STORAGE PIC clauses consist of:
X
Any character (Alpha, numeric, or special)
9
Only numeric data - digits (0 9)
V
Part of numeric definition. Assumed decimal point
01
S
Part of numeric definition. Sign – allows for negative numbers
What's with FILLER?
See Slide Notes
27
WS-EMP-RECORD.
05 FILLER
05 ER-LAST-NAME
05 ER-FIRST-NAME
05 ER-SOC-SEC-NUM
05 ER-PAY-RATE
05 ER-HOURS-WORKED
05 FILLER
PIC
PIC
PIC
PIC
PIC
PIC
PIC
XXX.
X(20).
X(20).
9(9).
S999V99.
999.
X(28).
COBOL Records – Level Numbers and Hierarchically Structured Group Variables
01 ADDRESS-REC.
05 STREET
05 ADDRESS-2.
10 CITY
10 STATE-CODE
10 POSTAL-CODE1
Level
10 FILLER
Numbers
10 POSTAL-CODE2
COBOL Group Structure variable
PIC X(40).
PIC
PIC
PIC
PIC
PIC
X(17).
XX.
9(5).
X VALUE "-".
9(4).
Elementary field
Another group variable
Elementary character field
…
Elementary numeric field
Value clause – initializes variable
You may want to sub-divide data into groups of fields that show relationships, or that
organize variables in a hierarchical structure known as a COBOL “record”.
Records are COBOL variables that begin with a “level-number” in the range of
01 (which denotes the record as a whole) 49.
COBOL records consist of:
Group fields:
Which do NOT have a picture clause
Typically contain elementary fields (lower level fields that sub-divide a group variable)
And have a lower level number (representing higher “parentage” level” in the structure) than their
children (elementary) fields
Elementary fields:
Which must have a picture clause
And have a higher level number (representing lower or dependent level in the structure) than their
group field “parent” variables
You can manipulate both group and elementary fields in COBOL
28
LINKAGE SECTION – Declaring Variables Passed as Parameters by Other Programs
DATA DIVISION.
FILE SECTION.
WORKING-STORAGE SECTION.
LINKAGE SECTION.
01 StructureVariableName.
05 BinaryIntVariable
05 FixedStringVariable
PIC 9(4) COMP.
PIC X(40).
The LINKAGE SECTION is where you define variables that are used to
receive parameters passed by other programs in your application
All of the variables in the LINKAGE SECTION are global in scope
LINKAGE SECTION variables adhere to the same COBOL variable coding rules
as data in the FILE SECTION and WORKING-STORAGE SECTION:
COBOL variable naming rules
Picture clause definitions
Group/Structure record declaration rules
LINKAGE SECTION variables obtain their values through data passed as
parameters in “calling” COBOL programs
This will be described in greater detail later in the course
29
Wow… This Seems Like a Lot to Remember!
Memorizing all these
rules seems like a
steep ladder to
climb…
Have no fear… the compiler and Workbench
tools will remind you!
30
Unit
COBOL General Language
Rules
Topics:
Coding COBOL
Identifying Your Program
Describing Your Computing Environment
Describing the Data
Processing the Data
Java and .NET Equivalents
31
Topic objectives
After completing this topic, you should be able to:
Describe the purpose of the PROCEDURE DIVISION
List the required elements of it
Code a syntactically correct PROCEDURE DIVISION statement
List a few optional paragraphs and sections of the PROCEDURE DIVISION
32
Processing Your Data – the PROCEDURE DIVISION
IDENTIFICATION DIVISION.
…
ENVIRONMENT DIVISION.
…
DATA DIVISION.
…
PROCEDURE DIVISION.
In the PROCEDURE DIVISION of a program, you code the executable
statements (business logic) that process data.
The division header for a program can be:
Accepting parameter values into VAR1, VAR2
PROCEDURE DIVISION.
PROCEDURE DIVISION USING VAR1, VAR2…
PROCEDURE DIVISION RETURNING VAR1, VAR2…
Returning parameter values to a program that called this program
-- Note that VAR1, VAR2, etc. are variables defined in a program’s
LINKAGE SECTION
33
How Logic is Divided in the PROCEDURE DIVISION
Imperative
Section
Statements
Logical subdivision of your processing logic.
A section has a procedure name – declared in the “A” area,
S
and is optionally followed by one or more paragraphs.
E
A section can be the subject of a PERFORM statement.
C
T
A section can have zero-to-many paragraphs
I
O
N
Paragraph
Subdivision of a section, procedure, or program.
A paragraph has a procedure name – declared in the “A”
area, followed by a period and zero or more sentences.
A paragraph can be the subject of a PERFORM or THRU
statement.
Conditional
Statement
Sentence
Series of one or more COBOL statements – coded in the
“B” area, that ends with a period.
P
A
R
A
R
A
P
H
Statement
Performs a defined step of COBOL processing, such as
adding two numbers.
A statement is a valid combination of words, and begins with
a COBOL verb.
Statements are
Scope Terminator
The PROCEDURE DIVISION of a COBOL
program is divided into sections and
paragraphs, which contain sentences,
statements, and phrases.
Imperative (indicating unconditional action)
Conditional
Compiler-directing
S
E
N
T
N
C
E
Statements are terminated by a period
Some statements can be terminated by an explicit Scope
Terminator (see screen capture)
Section and Paragraph procedure names
follow the same COBOL naming rules as
variables
Using explicit scope terminators instead of periods to
show the logical end of a statement is a “Best Practice”
34
PROCEDURE DIVISION – Imperative Statements
An imperative statement - such as
ADD
MOVE
INSPECT
COMPUTE
DISPLAY
ACCEPT
GOBACK
READ
WRITE
CLOSE
Examples of Imperative Statements
More examples can be found in:
http://publibfp.boulder.ibm.com/epubs/pdf/igy3lr40.pdf
…indicates an unconditional action
to be taken.
End an imperative statement with a
period
Or if allowed (READ, WRITE, COMPUTE),
end with a scope-terminator
35
PROCEDURE DIVISION – Conditional Statements
A conditional statement is either a
simple conditional statement
IF
EVALUATE
SEARCH
or a conditional statement made up of
an imperative statement that includes a
conditional phrase or option
PERFORM … UNTIL
READ … AT END
You can end a conditional statement
with an implicit or explicit scope
terminator.
36
PROCEDURE DIVISION – Imperative Statements – ACCEPT – 1 of 2
WORKING-STORAGE SECTION.
77
INPUT-DATA
PIC X(40).
…
PROCEDURE DIVISION.
…
ACCEPT INPUT-DATA.
Accept waits for user data entry from your keyboard (and waits for you to
press Enter.
The alpha-numeric value you enter is assigned to the variable following
ACCEPT.
It is not necessary to make the accepted input variable of type PIC X – but
is probably a best practice, to avoid user-entry and data-type errors
On the Mainframe, ACCEPT retrieves its value from a reserved JCL “DD
card” named: SYSIN.
We will discuss this in more depth later in the course
37
PROCEDURE DIVISION – Imperative Statements – ACCEPT – 2 of 2
Date/Time Structure Variables
ACCEPT statements, that return the current date
and time in different formats
ACCEPT is often used to retrieve certain useful operating system
"special-register" values:
Current Date – formatted with a number of different date masks:
Date
DAY-OF-WEEK (a value 1 7, representing Monday Sunday)
Day – the ordinal day of the year (1 365)
Time – formatted from the operating system's time: hhmmssss
38
PROCEDURE DIVISION – Imperative Statements – DISPLAY
WORKING-STORAGE SECTION.
…
PROCEDURE DIVISION.
…
DISPLAY "Something on the console".
Something
on the
console.
Display presents a literal or the contents of a PIC X(nn) field in the
console:
On the mainframe DISPLAY writes to a reserved JCL DD statement named:
//SYSOUT
On your PC a DOS window is opened, and the data is displayed inside it
Also – a new line is opened and your cursor moves to the new line (which works, in
case you want to ACCEPT data into the program)
You can DISPLAY:
A literal
A PIC X field
A PIC 9 field
A record
Multiple fields and/or literals, separated by commas
Code DISPLAY in the "B" area of your program
39
See Slide Notes
PROCEDURE DIVISION – Imperative Statements – MOVE
FILE SECTION
…
01
OUT-REC
PIC X(80).
…
WORKING-STORAGE SECTION.
77
INPUT-DATA
PIC X(40).
…
PROCEDURE DIVISION.
…
ACCEPT INPUT-DATA.
MOVE INPUT-DATA TO OUT-REC.
Syntax:
MOVE
<to-variable> TO <from-variable>.
MOVE copies the value in the to-variable to the from-variable (receiving
field), over-writing the from-variable’s storage contents.
Alpha-numeric values are copied from left-to-right, byte-for-byte
If the receiving field is longer than the sending field blanks (spaces) pad the receiving field
to the end of its PIC X length
If the receiving field is shorter than the sending field truncation occurs
We will study MOVE variations, and COBOL internal storage contents in subsequent
chapters
40
PROCEDURE DIVISION – Sequential File Input/Output Routines
FILE SECTION
FD
EXTFILE …
01
OUT-REC
PIC X(80).
…
WORKING-STORAGE SECTION.
…
PROCEDURE DIVISION.
…
OPEN <input/output> EXTFILE.
…
L
O
WRITE OUT-REC.
O
P
…
CLOSE EXTFILE.
Steps/Order:
1. OPEN <input/output> <FILENAME>.
2. WRITE <OUTPUT-RECORD>.
3. CLOSE <FILENAME>.
COBOL file I/O consists three steps (done roughly in this order):
1. OPEN the file you wish to read from or write to – for INPUT or OUTPUT (see example next slide)
2. Begin an iterative processing loop. Somewhere in the loop:
READ the input file - until “end-of-file” …and/or…
WRITE the record in the COBOL FILE SECTION FD – for all records that should be written out
3. CLOSE the file
In subsequent chapters we will cover COBOL loop statements
41
See Slide Notes,
for additional
learning content
PROCEDURE DIVISION – Imperative Statements – OPEN
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
SELECT INTFILENAME ASSIGN TO …
DATA DIVISION.
FILE SECTION
FD
INTFILENAME…
01
OUT-REC.
…
PROCEDURE DIVISION.
OPEN OUTPUT INTFILENAME.
COBOL (internal) File Name
WRITE OUT-REC.
CLOSE INTFILENAME.
Syntax:
OPEN OUTPUT
INPUT
External
Device
External File
EXTEND <InternalFileName>.
OPEN connects your program to the external device assigned in your
ENVIRONMENT DIVISION.
Your program must issue an OPEN statement, before you can READ to or WRITE from the file
OPEN INPUT – for files you READ from
OPEN OUTPUT – for files you WRITE to from scratch (over-writing the contents of any existing records in the file)
OPEN EXTEND – for files you WRITE to and append new records starting at the end of the file
CLOSE all OPEN files before ending your program
You can OPEN multiple files in one statement (see Slide Notes)
42
See Slide Notes, for
additional learning content
PROCEDURE DIVISION – Imperative Statements – WRITE
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
SELECT INTFILENAME ASSIGN TO …
DATA DIVISION.
FILE SECTION
FD
INTFILENAME…
01
OUT-REC.
…
PROCEDURE DIVISION.
OPEN OUTPUT INTFILENAME.
WRITE OUT-REC.
CLOSE INTFILENAME.
Syntax:
External
Device
External File
WRITE <OUTPUT-RECORD>.
WRITE adds one record to the end of an OPEN OUTPUT file.
You write:
The record in the FD for the file in the FILE SECTION
The record in the FD for the file in the FILE SECTION FROM a record in the WORKING-STORAGE
SECTION
See Slide Notes,
43
for additional
learning content
PROCEDURE DIVISION – Imperative Statements – CLOSE
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
SELECT INTFILENAME ASSIGN TO …
DATA DIVISION.
FILE SECTION
FD
INTFILENAME…
01
OUT-REC.
…
PROCEDURE DIVISION.
OPEN OUTPUT INTFILENAME.
WRITE OUT-REC.
CLOSE INTFILENAME.
Syntax:
F
I
L
E
External
Device
External File
C
L
O
S
E
CLOSE <InternalFileName>.
Issue a CLOSE statement for every file you are using before your program
ends. CLOSE:
Closes an external file
And makes it unavailable for processing
Unless/until a subsequent OPEN statement occurs
You can close multiple files in a single statement
44
See Slide Notes,
for additional
learning content
®
IBM Software Group
Enterprise COBOL Education Using Rational Developer for System Z
Module 3 – Basic COBOL Statements
Jon Sayles, IBM Software Group, Rational EcoSystems Team
© 2006 IBM Corporation
Course Description
Course Name: COBOL Foundation Training - with RDz
Course Description: Learn the COBOL language, RDz and learn z/OS terms, concepts and development skills in
this course.
Pre-requisites: Some experience in a 3rd or 4th Generation Language is expected. SQL is also recommended.
Course Length: 10 days
Topics (Agenda)
Getting Started - installing and configuring RDz - and the course materials, and using Eclipse to edit COBOL
COBOL General Language Rules
Basic COBOL Statements
Advanced record and table handling
Debugging Programs - Note: Deep dive on using RDz for common COBOL programming errors (001, 0C4, 0C7, infinite loops, fall-thru, etc.)
Input/Output and Report Writing Patterns
COBOL Subprograms and the Linkage Section
Structured Programming Concepts, professional COBOL development practices and Coding Patterns
Advanced Character Manipulation, COBOL Intrinsic Functions, Date and Time coding patterns, and Language Environment calls
OS/390 Concepts and JCL - Compile/Link & Run Procs on the mainframe
Indexed file Coding Patterns
Sort/Merge, Sequential File Match/Merge and Master File Update Coding Patterns
Accessing DB2 Data and DB2 Stored Procedures
COBOL in the Real World:
– CICS - lecture only
– IMS (DL/I and TM) - ditto
– Batch processing - ditto
– Java calling COBOL
– COBOL and XML Statements
– SOA and COBOL - creating and calling Web Services
– Web 2.0 using Rich UI
46
Unit
COBOL General Language
Rules
Topics:
Assignment Statements and Internal Data
Representation
Math Operations
Conditional Logic
Transfer of control
COBOL Looping Constructs
Sequential File Processing Patterns
Java and .NET Equivalents
47
Topic objectives
After completing this topic, you should be able to:
Describe the COBOL MOVE and assignment operation
List the three types of COBOL assignment statements – and what causes the
COBOL compiler to choose one type over the other
Define the rules for:
Alphanumeric moves
Numeric moves
Group or structure moves
List a few optional MOVE clauses, and describe what they do, including:
MOVE CORRESPONDING
Code MOVE statements that are syntactically correct
Describe the underlying COBOL storage representation for:
Alphanumeric data
Numeric data
List the common COBOL Figurative Constants
Describe what the COBOL INITIALIZE statement does
48
COBOL Picture Clauses and Internal Data Representation
COBOL Data types are PIC clause dependent, and come in several broad categories:
Character Data:
Fixed Length: PIC X(nn) – or PIC A(nn) … Note, A "Alphabetic data"
Stored as EBCDIC bytes – examples: A Hex: C1, B Hex: C2, 9 Hex: F9, etc
http://theamericanprogrammer.com/code7302/ebcdic.txt
Numeric Data:
Display numeric (aka Zoned Decimal): PIC 9(5), PIC S9(5)V99
Stored as EBCDIC bytes, with "assumed" decimal place – one byte per digit
– Hex values: F0 F9
With V in declaration – COBOL takes care of decimal alignment in math/MOVE operations
With S (sign) in declaration, the last byte of internal storage holds the sign (C or D):
–
–
C - is positive number:
– PIC S9(5)V99 - value:
D - is negative number
– PIC S9(5)V99 - value:
321.19
F0 F0 F3 F2 F1 F1 C9
321.19
F0 F0 F3 F2 F1 F1 D9
EBCDIC Internal
Data Representation
Binary (COMP) numeric – used to improve run-time COBOL arithmetic instruction performance:
Small binary: PIC S9(4) COMP – stored in two bytes, pure binary (base 16) data
Medium binary: PIC S9(9) COMP – stored in four bytes
Large binary: PIC S9(18) COMP – stored in eight bytes
With or without Signs, and assumed decimal places:
Ex.
–
–
PIC S9(4) COMP Value
123.
PIC S9(4) COMP Value -123.
Stored as: 0123
Stored as twos complement of 123: FF85
Packed decimal (COMP-3) numeric – frequently used to reduce the size of a file:
Two digits per/byte. Sign bit – in last "nibble" (bottom 1/2 of last byte). "Slack bytes" (other high-order/leading
zeroes) may need to be added to the internal storage to account for evenly divisible PIC clause + sign nibble
Ex.
–
–
PIC S9(5)V99 COMP-3 Value
PIC S9(5)V99 COMP-3 Value
123.99.
-123.99.
Important – See Slide Notes
Stored as:
Stored as:
49
00 12 39 9C
00 12 39 9D
COBOL Picture Clause Editing and External (Output) Field Values
There are a number of other PIC clauses used for output result data on reports and greenscreen I/O. They are simple to understand, and very convenient. Note that the numeric PIC
clauses force decimal-point alignment. The alphanumeric PIC clauses all align the data left.
Z
Suppress leading zeroes – insert floating blanks
PIC ZZ,ZZZ,Z99.99
B
Alphanumeric "mask" – Positionally insert a blank into alphanumeric data
PIC XBXBXB
0
Numeric "mask" - Positionally insert a zero into a numeric field.
PIC 990990
/
Data mask - Insert a slash into alphanumeric data – typically used for dates
PIC XX/XX/XX
,
Insert a comma into numeric data
PIC Z,ZZZ,Z99.99
.
Insert a decimal point, into numeric data
Z,ZZZ,Z99.99
+
Insert a plus sign – IF the value in the variable is > 0
PIC Z,ZZZ,Z99.99+
Insert a negative sign – IF the value in the variable is < 0
PIC Z,ZZZ,Z99.99CR Insert a "CR" literal – IF the value in the variable is < 0
PIC Z,ZZZ,Z99.99CR
DB Insert a "DB" literal – IF the value in the variable is < 0
PIC Z,ZZZ,Z99.99DB
*
Insert asterisks instead of leading zeros for numeric values
PIC ********9999
$
Dollar-sign suppressions - Insert a floating, left-justified $ sign for numeric values
PIC $$,$$$,$99.99
50
ILE Reference Manual – Picture Clause Editing Examples – 1 of 2
The ILE reference manual has an excellent sample guide to Picture Clause editing
http://publib.boulder.ibm.com/infocenter/iadthelp/v7r0/index.jsp?topic=/com.ibm.etools.iseries.langref.doc/c0925395267.htm
51
ILE Reference Manual – Picture Clause Editing Examples – 2 of 2
The ILE reference manual has an excellent sample guide to Picture Clause editing
http://publib.boulder.ibm.com/infocenter/iadthelp/v7r0/index.jsp?topic=/com.ibm.etools.iseries.langref.doc/c0925395267.htm
52
COBOL Storage Representation – Reference Chart
Picture Clause
Meaning
PIC X(10)
Fixed alpha-numeric data
'ABC'
PIC 9(5)
Display numeric (Zoned Decimal) numbers
-321
00321 - Note - without S (sign)
value get "absolute value"
FFFFF
00321
PIC S9(5)
Zoned decimal - with sign
-321
00321 - Value is negative in math
operations
FFFFD
00321
PIC S9(5)V99
Zoned decimal with implied decimal place
321.5
00321V50
PIC S9(4) COMP
Small binary number - 2 byte - note, negative
binary #s stored as two's complement
321
0321
PIC S9(5) ==> S9(9) COMP
Binary number - 4 bytes
321
00000321
PIC S9(9) ==> S9(18) COMP
Large Binary number
321
000000000000000321
PIC 9(4) COMP-3
Packed decimal number
321
0321
PIC S9(5)V99 COMP-3
Packed decimal number
321.99
00321.99
0319
029C
PIC S9(5)V99 COMP-3
Packed decimal number
-321.99
00321.99 – Value is negative in
math operations
0319
029D
External PIC clauses
Value
Internal Storage
(EBCDIC bytes)
Value
PIC Z(3)
Zero-suppressed
PIC ZZ,ZZZ,ZZZ.99-
Zero-suppressed, with commas and minus sign
-321.99
PIC $$,$$$,$99.99
Dollar-sign suppressed
-321.99
PIC XBXBXB
Blank insertion
ABC
PIC 990990
Zero insertion
-321.99
PIC XX/XX/XX
Slash insertion
012099
PIC Z,ZZZ,Z99.99CR
Zero-suppressed, with commas and Credit sign
-321.99
PIC ****9999
Asterisk suppressed
PIC Z,ZZZ,Z99.99DB
Zero-suppressed, with commas and Debit sign
Internal Value
Output/Display Value
-2.99
-333321.99
321.99
53
CCC4444444
12300000000
ABCbbbbbbb (seven trailing
blanks)
2
FFFFFFC
0032150
04
11
0004
0011
00000004
00000011
031
02F
Notes
No decimal places, no sign
321.99-
Sign on right (can be on left). Zeroes suppressed
$321.99
One resulting $, if need sign, must use dash (-)
AbBbCb
Positional blank (b) inserted
030210
01/10/99
High-order inserted, numbers inserted @ PIC 9
Date mask
321.99CR
**321
321.99
If number was positive, CR would not appear
Like Z and $ - asterisk suppresses leading zeros
If number was negative, DB would appear
88-Level Variables in the Data Division
88-level variables in COBOL programs are "conditionals, built in to the variable
declarations"
They:
Have no PIC clause
Have one or more VALUES – specified as literals (see a few valid expressions below)
Are used effectively to make COBOL IF conditional expressions readable/maintain-able
01 MONTH-IND PIC XXX.
88 SHORTEST-MONTH
VALUE 'FEB'.
88 THIRTY-DAY-MONTH
VALUES ARE 'JUN', 'SEP', 'APR', 'NOV'.
88 THIRTY-ONE-DAY MONTH
VALUES ARE 'JAN' 'MAR' 'MAY' 'JUL' 'AUG' 'OCT' 'DEC'.
…
IF THIRTY-DAY-MONTH
…
01 STUDENT-GRADE-RANGE PIC S9(3).
88 A-OK
VALUE 90 THRU 100.
88 NOT-BAD
VALUE 80 THRU 89.
88 PRETTY-GOOD VALUE 70 THRU 79.
88 RUH-ROH
VALUE 60 THRU 79.
88 FAIL
VALUE 0 THRU 59.
…
IF NOT-BAD
MOVE 'DOIN ALRIGHT' TO MSG-TEXT
DISPLAY GRADE-MSG
54
Pluses:
• Make code more "English" read-able
• Allow you to centralize conditions in one place - in
the DATA DIVISION
Minuses:
• Force you to refer to the DATA DIVISION for the
actual values tested in the code in the PROCEDURE
DIVISION
Review – Imperative Statements – MOVE
FILE SECTION
…
01
OUT-REC
PIC X(80).
…
WORKING-STORAGE SECTION.
77
INPUT-DATA
PIC X(40).
…
PROCEDURE DIVISION.
…
ACCEPT INPUT-DATA.
MOVE INPUT-DATA TO OUT-REC.
Syntax:
MOVE
<to-variable> TO <from-variable>.
MOVE copies the value in the to-variable to the from-variable (receiving
field), over-writing the from-variable’s storage contents.
There are two types of MOVE operations:
Alphanumeric MOVE
Numeric MOVE
The receiving field's datatype (PIC clause) dictates the type of MOVE operation
It is important to understand how the contents of variable storage are affected by
MOVE. So, let's drill-down now, on PIC clauses and COBOL internal data
storage representation
55
Alphanumeric MOVE Statements
Alphanumeric MOVE statements:
Occur when the receiving field is considered Alphanumeric by the compiler
PIC X
PIC A
The Alphanumeric formatted output PIC clauses:
– PIC with B, etc.
Proceed from left-to-right – and copy byte-for-byte
When the sending and receiving fields are not the same size:
Space (blank) fill to the right, if the receiving field is longer than the sending field
Truncate if the receiving field is shorter than the sending field (typically you will get a W-level diagnostic
when you compile a program with a MOVE statement that truncates data)
Except – can JUSTIFY the receiving field data RIGHT
FLD1
FLD2
…
MOVE
PIC X(4) VALUE 'ABCD'.
PIC X(10) JUSTIFY RIGHT.
FLD1 TO FLD2.
– Results in FLD2 value of: bbbbbbABCD
If JUSTIFY RIGHT, and the receiving field is shorter than the sending field, truncation occurs in the right-most
characters
If JUSTIFY RIGHT, and the receiving field is longer than the sending field, blanks are added to the left-most
positions
Note: if, FLD1 PIC X(10) VALUE 'ABCD' result of MOVE is: ABCDbbbbbb.
– Why?
Copy:
Internal storage values byte for byte
For the # of bytes in the receiving field
Group data (structures) are considered Alphanumeric – in MOVE operations
56
Numeric MOVE Statements
Numeric MOVE statements:
Occur when the receiving field's PIC clause is numeric
9 … anywhere in the PIC clause
Input field declaration:
– V, S
Output (formatted numeric PIC clause in declaration)
– Z, $, 0, DB, CR, +, -, period (.), comma (,)
MOVE copies the algebraic value of the sending field to the
receiving field as follows:
Automatically aligns at the decimal place
Or assumed decimal place if no V in PIC clause
Pad to the left with leading, and to the right with trailing zeroes, if the receiving field has
more decimal digits to the left or the right of the (assumed) decimal positions
If sign (S) or numeric edited sign MOVE will value the receiving positively or negatively
depending on the sending field's value. If no sign, the receiving field gets absolute value
Will numerically truncate – if receiving field has fewer decimal digits to the left of the
decimal place, or less digits (decimal precision) to the right of the decimal place
What about mixed datatype MOVE statements? (next slide…)
57
MOVE Statements When the Datatypes Are Not The Same
Obviously you can move PIC X fields to other PIC X – and PIC 9 fields to other PIC 9
fields, but sometimes, due to business requirements you will have to code MOVE
statements of unlike (mixed) datatypes.
Here are the general rules:
Anything can be moved to an alphanumeric PIC X field
Only other PIC 9 (input) fields can be moved to PIC 9 fields
And only PIC 9 fields can be moved to numeric edited fields
PIC 9 numeric edited fields can be moved to PIC 9 fields
Group moves are considered exactly the same as an alphanumeric PIC X field move by the
compiler
And all the rules you just learned about truncation, padding and decimal alignment also apply
This table may help clarify the rules for mixed data type MOVE
Sending
Fields
Receiving Fields
PIC X
PIC 9
Numeric
Edited
PIC X
Y
N
N
PIC 9
Y
Y
Y
Y
N
Treated as an alphanumeric MOVE
(digits may be lost, trailing blanks
may be added, etc.)
Numeric Edited
Y
58
Allowable
MOVE Statements
Please
consult this
verbose (!)
table to see
the complete
list of COBOL
allowable
MOVE
statements –
based on
sending and
receiving field
PIC types.
Don't worry if
there are
terms you're
not up to
speed on just
yet – we'll get
you there.
Patience
59
Alphanumeric MOVE Statements - Examples
Sending Field
Receiving Field
Sending Field Value
Result in Receiving
Field
PIC X(5)
PIC X(5)
ABCDE
ABCDE
PIC X(5)
PIC X(3)
ABCDE
ABC
PIC X(5)
PIC X(8)
ABCDE
ABCDEbbb
PIC 9(5)
PIC X(8)
12345
12345bbb
PIC X(5)
PIC 9(5)
Not allowed by the compiler
N/A
PIC S9(5)V99 COMP-3
PIC X(8)
Not allowed by the compiler – as is noninteger numeric (see table of moves)
13574444
246C0000
PIC S9(4) COMP
PIC X(4)
1234
1344
2400
PIC X(4)
PIC X(10) JUSTIFY RIGHT.
ABCD
bbbbbbABCD
(hex)
Numeric Value
PIC 9(5)V99
PIC 9(3)V9
12345.67
345.67
PIC S9(7)V99
PIC 9(4) COMP
123456789.99
6789
PIC S9(5)V99
PIC S9(7)V999 COMP-3
-12345.67
0012345.670 (minus carried in sign bit)
PIC S9(9) COMP
PIC 9(5)V99
1234567912
67912.00
PIC S9(5)V99 COMP-3
PIC 9
-12345.67
5
CUSTOMER-NAME
PIC X(18)
SMITHbbbbbAALEXAND
CUSTOMER-RECORD
PIC X(40)
1201SMITHbbbbbAALEXANDERbbbbbbbbbbbbbbbbbbbbbb
Group Moves
01 CUSTOMER-RECORD.
05 ID-NUMBER
05 CUST-TYPE
05 CUSTOMER-NAME.
10 FIRST-NAME
10 MIDINIT
10 LAST-NAME
PIC 9(2)
PIC 9(2)
VALUE 12.
VALUE 01.
PIC X(10) VALUE 'SMITH'.
PIC X(01) VALUE 'A'.
PIC X(10) VALUE 'ALEXANDER'.
60
MOVE With OF Modifier
FILE SECTION.
…
01 CUSTOMER-RECORD-IN.
05 ID-NUMBER
PIC 9(2).
05 CUST-TYPE
PIC 9(2).
05 CUSTOMER-NAME.
10 FIRST-NAME
PIC X(10).
10 MIDINIT
PIC X(01).
10 LAST-NAME
PIC X(10).
01 CUSTOMER-RECORD-OUT.
05 ID-NUMBER
PIC 9(2).
05 CUST-TYPE
PIC 9(2).
05 CUSTOMER-NAME.
10 FIRST-NAME
PIC X(10).
10 MIDINIT
PIC X(01).
10 LAST-NAME
PIC X(10).
…
PROCEDURE DIVISION.
MOVE FIRST-NAME OF CUSTOMER-RECORD-IN TO FIRST-NAME OF CUSTOMER-RECORD-OUT.
Syntax:
The OF modifier allows you to:
MOVE <from-variable> of <from-Group> to
<to-variable>.
Fully-qualify elementary field names – making large programs with 1,000's variables easier to maintain
Compile programs with duplicate elementary field names
61
MOVE CORRESPONDING
FILE SECTION.
…
01 CUSTOMER-RECORD-IN.
05 ID-NUMBER
PIC 9(2).
05 CUST-TYPE
PIC 9(2).
05 CUSTOMER-NAME.
10 FIRST-NAME
PIC X(10).
10 MIDINIT
PIC X(01).
10 LAST-NAME
PIC X(10).
01 CUSTOMER-RECORD-OUT.
05 ID-NUMBER
PIC 9(2).
Field's data not moved
05 CUSTTYP
PIC 9(2).
05 CUSTOMER-NAME.
Field's data not moved
10 FIRSTNAME
PIC X(10).
10 MIDINIT
PIC X(01).
10 LAST-NAME
PIC X(10).
…
PROCEDURE DIVISION.
MOVE CORRESPONDING CUSTOMER-RECORD-IN TO CUSTOMER-RECORD-OUT.
Syntax:
The CORRESPONDING modifier allows you to MOVE group records:
MOVE CORRESPONDING <from-group-variable> to
<to-group-variable>.
When COBOL variable names match between the from and to groups, data is copied
And only when COBOL variable names match
62
See Notes
COBOL INITIALIZE Statement
INITIALIZE values selected types of data fields. The default is:
Numeric data to zeros
alphanumeric data (PIC X or Group Data Items) to spaces.
You can also INITIALIZE fields, replacing classes of datatypes with specific values
This is used less frequently, and is shown in the slide
notes
Initializing a structure (INITIALIZE)
You can reset the values of all subordinate data items in a group item by applying the
INITIALIZE statement to that group item.
63
COBOL Figurative Constants
FILE SECTION.
…
01 CUSTOMER-RECORD-IN.
…
77 COBOL-CHAR-FIELD
77 COBOL-NUM-FIELD
77 COBOL-QT
PROCEDURE DIVISION.
MOVE LOW-VALUES
MOVE HIGH-VALUES
MOVE SPACES
MOVE ZEROS
MOVE ALL '_'
PIC X(4).
PIC X(4).
PIC X(1) VALUE QUOTE.
to
to
to
to
TO
CUSTOMER-RECORD-IN.
COBOL-CHAR-FIELD.
COBOL-CHAR-FIELD.
COBOL-NUM-FIELD.
COBOL-CHAR-FIELD.
Syntax:
There are a number of COBOL figurative constants available to fill the storage of
alphanumeric fields (or in the case of ZEROS), either:
MOVE <figurative constant> to
<Cobol variable>.
With MOVE statements
In VALUE clauses of field declarations
The figurative constants are reserved words, and there are a number of alternative spellings
(see the COBOL language reference, or RDz Help system)
They are sometimes used by convention to signal some processing event:
READ <fileName>
AT END MOVE HIGH-VALUES TO <inputRecord>.
64
Unit
COBOL General Language
Rules
Topics:
Assignment Statements and Internal Data
Representation
Math Operations
Conditional Logic
Transfer of control
COBOL Looping Constructs
Sequential File Processing Patterns
Java and .NET Equivalents
65
COBOL Mathematical Operators
As you'd expect from a a business oriented language, COBOL's math
capabilities are simple, flexible, deep and robust.
Simple operations:
ADD
SUBTRACT
MULTIPLY
DIVIDE
…with a number of variations of operand/operator expressions and automatic decimal
alignment across all numeric types
Algebraic statements:
COMPUTE – uses arithmetic operators (next slide) to perform math operations
COBOL Intrinsic "Built-in" math Functions
Here are a few of the math-oriented COBOL intrinsic functions:
ACOS
ANNUITY
ASIN
ATAN
CHAR
COS
FACTORIAL
LOG
LOG10
MAX
MEAN
MEDIAN
MIDRANGE
MIN
MOD
PRESENT-VALUE
RANDOM
66
RANDOM
RANGE
REM
REVERSE
SIN
SQRT
STANDARD-DEVIATION
SUM
TAN
VARIANCE
Fixed-Point Arithmetic Statements*** – ADD
WORKING-STORAGE SECTION.
01 WORK-FIELDS.
05 ITEM-1 PIC S9(3)V99 VALUE 85.52.
05 ITEM-2 PIC S9(3)V99 VALUE 2.34.
05 SUM
PIC S9(5)V99 VALUE 0.
PROCEDURE DIVISION.
…
ADD ITEM-1, ITEM-2 TO SUM ROUNDED
ON SIZE ERROR MOVE 0 TO SUM
END-ADD
ADD ITEM-1 ITEM-2 GIVING SUM ROUNDED
ON SIZE ERROR MOVE 0 TO SUM
DISPLAY '** ON SIZE ERROR **'
END-ADD
Format 1
Rounded
Rounds to the decimal digits in
the PIC clause (See Slide Notes)
ON SIZE ERROR
Allows you to handle arithmetic
overflow conditions with
imperative statements.
Additional note: You can
substitute a numeric literal for the
variables in the ADD and TO (but
not GIVING) clauses in the
statement
Adds the addend to the sum
Format 2
The values of all operands preceding the word GIVING are added together, and the
sum is stored as the new value.
None of the values in the operands preceding GIVING are changed
Note: There is a Format 3 statement: ADD CORRESPONDING
67
***See Notes
Arithmetic Statements – ROUNDED and ON SIZE ERROR
WORKING-STORAGE SECTION.
01 WORK-FIELDS.
05 ITEM-1 PIC S9(5)V99 VALUE 85.56.
05 RESULT PIC S9(6)
VALUE 100.
PROCEDURE DIVISION.
…
ADD ITEM-1 TO RESULT.
Value: 185
MOVE 100 TO RESULT.
ADD ITEM-1 TO RESULT ROUNDED.
Value: 186
The ROUNDED phrase allows you to specify rounding up to the
nearest low-order decimal digit of precision. This means that
ROUNDED adds 1 to the absolute value of the low-order digit of
the result variable IF the absolute value of the next least
significant digit of the intermediate variable value is >= to 5.
MOVE 140156.33 TO ITEM-1.
MOVE 900000 TO RESULT.
ADD ITEM-1 TO RESULT ROUNDED.
Value: 040156
MOVE 900000 TO RESULT.
ADD ITEM-1 TO RESULT
ON SIZE ERROR MOVE 0 TO SUM
DISPLAY '** ON SIZE ERROR **'.
68
Value: 000000
Arithmetic Statements – SUBTRACT
WORKING-STORAGE SECTION.
01 WORK-FIELDS.
05 ITEM-1
PIC S9(3)V99 VALUE 85.52.
05 ITEM-2
PIC S9(3)V99 VALUE 2.34.
05 DIFFERENCE
PIC S9(5)V99 VALUE 0.
PROCEDURE DIVISION.
…
SUBTRACT ITEM-1, ITEM-2 FROM DIFFERENCE ROUNDED
ON SIZE ERROR MOVE 0 TO DIFFERENCE
END-SUBTRACT
SUBTRACT ITEM-1 FROM ITEM-2 GIVING DIFFERENCE ROUNDED
ON SIZE ERROR MOVE 0 TO DIFFERENCE
DISPLAY '** ON SIZE ERROR **'
END-SUBTRACT
Rounded
ON SIZE ERROR
Rounds to the decimal
digits in the PIC clause
Allows you to handle
arithmetic overflow
conditions with imperative
statements.
Additional note: You
can substitute a numeric
literal for the variables in
the SUBTRACT and FROM
(but not GIVING)
clauses in the statement
Format 1
Subtracts all minuends from the sum
Format 2
The values of all operands preceding the word GIVING are added together, and the
sum is subtracted from the difference (in the above)
None of the values in the operands preceding GIVING are changed
Note: There is a Format 3: SUBTRACT CORRESPONDING
69
Arithmetic Statements – MULTIPLY
WORKING-STORAGE SECTION.
01 INPUT-FIELDS.
05 ITEM-1
PIC S9(3)V99 VALUE 85.52.
05 ITEM-2
PIC S9(3)V99 VALUE 2.34.
05 ITEM-3
PIC S9(3)V99 VALUE 6.01.
05 RESULT
PIC S9(5)V99.
PROCEDURE DIVISION.
MULTIPLY ITEM-1 BY ITEM-3 ROUNDED
ON SIZE ERROR MOVE 0 TO DIFFERENCE
END-MULTIPLY
MULTIPLY ITEM-1 BY ITEM-2 GIVING RESULT ROUNDED
ON SIZE ERROR MOVE 0 TO DIFFERENCE
DISPLAY '** ON SIZE ERROR **'
END-MULTIPLY
Format 1
The values of the operand preceding the word BY is multiplied by the operand after
the word BY
Format 2
The value of the operand after the word GIVING is replaced by the multiplication of
ITEM-1 BY ITEM-2
None of the values in the operands preceding GIVING are changed
70
Arithmetic Statements – DIVIDE – Common Usage and Formats
WORKING-STORAGE SECTION.
01 INPUT-FIELDS.
05 ITEM-1
PIC S9(3)V99 VALUE 85.52.
05 ITEM-2
PIC S9(3)V99 VALUE 2.34.
05 ITEM-3
PIC S9(3)V99 VALUE 6.01.
05 RESULT
PIC S9(5)V99.
PROCEDURE DIVISION.
DIVIDE ITEM-1 INTO ITEM-3 ROUNDED
ON SIZE ERROR MOVE 0 TO DIFFERENCE
END-DIVIDE
DIVIDE ITEM-1 INTO ITEM-2 GIVING RESULT ROUNDED
ON SIZE ERROR MOVE 0 TO DIFFERENCE
DISPLAY '** ON SIZE ERROR **'
END-DIVIDE
DIVIDE ITEM-1 BY ITEM-3 ROUNDED
REMAINDER ITEM-3
END-DIVIDE
DIVIDE ITEM-1 INTO ITEM-2 GIVING RESULT ROUNDED
REMAINDER ITEM-3
END-DIVIDE
Five separate Formats for DIVIDE (see Slide Notes)
71
Rounded
ON SIZE ERROR
Rounds to the decimal
digits in the PIC clause
Allows you to handle
arithmetic overflow
conditions with imperative
statements.
Additional note: You
can substitute a numeric
literal for the variables in
the DIVIDE, BY and
INTO, (but not GIVING)
clauses in the statement
Arithmetic Statements – COMPUTE
WORKING-STORAGE SECTION.
…
01 INPUT-FIELDS.
05 ITEM-1
PIC S9(3)V99 VALUE 85.52.
05 ITEM-2
PIC S9(3)V99 VALUE 2.34.
05 ITEM-3
PIC S9(3)V99 VALUE 6.01.
05 RESULT
PIC S9(5)V99.
PROCEDURE DIVISION.
…
COMPUTE RESULT ROUNDED =
(ITEM-1 * ITEM-2 / ITEM-3).
Note:
Blanks (the white space) between elements
of your equation are significant with COMPUTE.
For example:
Compute celsius rounded =
(5/9) * (fahrenheit - 32).
Compute celsius rounded =
( 5 / 9 ) * (fahrenheit - 32).
--- will not work
--- will work
The COMPUTE statement assigns the value of an arithmetic (think algebraic)
expression to one or more data items.
It allows you to combine arithmetic operations without the restrictions on
receiving data items that the rules for the ADD, SUBTRACT, MULTIPLY, and
DIVIDE statements impose.
When you need to combine arithmetic operations, using the COMPUTE
statement may be more efficient than writing a series of separate arithmetic
statements.
You may use any of the arithmetic operators shown on the next slide inside a
compute statement
Additionally, you can combine COMPUTE with COBOL intrinsic functions
72
COMPUTE Arithmetic Operators
Use the above arithmetic operators to in your COMPUTE statements
The operations proceed as follows:
Unary Operators
Multiplication/Division/Exponentiation
Addition/Subtraction
… from left to right within the COMPUTE – and following the order of parenthesis
Thus, it's always a good idea to force an explicit arithmetic order of
precedence using parenthesis in COMPUTE statements
These two statements are not algebraically equivalent:
COMPUTE RESULT ROUNDED =
(ITEM-1 * ITEM-2 + ITEM-3).
COMPUTE RESULT ROUNDED =
(ITEM-1 * (ITEM-2 + ITEM-3)).
73
Intermediate Results of Fixed Point Math
From the IBM Enterprise COBOL Programmer's Guide - Document Number: SC23-8529-00
The compiler handles arithmetic statements as a succession of operations performed according to operator
precedence, and sets up intermediate fields to contain the results of those operations.
The compiler uses algorithms to determine the number of integer and decimal places to reserve.
Intermediate results are possible in the following cases:
In an ADD or SUBTRACT statement that contains more than one operand immediately after the verb
In a COMPUTE statement that specifies a series of arithmetic operations or multiple result fields
In an arithmetic expression contained in a conditional statement or in a reference-modification specification
In an ADD, SUBTRACT, MULTIPLY, or DIVIDE statement that uses the GIVING option and multiple result fields
In a statement that uses an intrinsic function as an operand
The precision of intermediate results also depends on whether you compile using the default option
ARITH(COMPAT) or using ARITH(EXTEND)
Net:
Because of the effect of the intermediate results on your arithmetic calculations can produce incorrect
results (mostly truncation errors)
And because the above list is a lot to remember (and is actually only the entry point into the topic)!
You can – and should follow these simple rules-of-thumb:
Be particularly careful to define your numeric datatypes to the precision necessary for your requirements
When using literals in your calculations always add the necessary decimal digits of precision to them, in order to
force the compiler to create intermediate results to your level of requirements
Example: Instead of: COMPUTE FIELD-1 ROUNDED = 100 * (32.78 / 1000).
Include decimal places in your literals:
COMPUTE FIELD-1 ROUNDED = 100.000 * (32.78 / 1000.000).
74
Lab Assignment
From the course workshop documents, do the following labs –
create and debug COBOL program that calculates simple
interest based on the following variables
amount
principal
interest
nbrYears
PIC
PIC
PIC
PIC
9(7)V99.
9(7)V99.
9(2)V99.
9(4) COMP.
//Business logic – in pseudo-code.
//Initialize values
amount = 0;
principal = 10000.01;
interest = .05;
nbrYears = 10;
//Invoke simple interest calculation function
calculateSimpleInterest();
end
function calculateSimpleInterest()
amount = principal * (1 + (nbrYears * interest));
end
end
75
Unit
COBOL General Language
Rules
Topics:
Assignment Statements and Internal Data
Representation
Math Operations
Conditional Logic
Transfer of control
COBOL Looping Constructs
Sequential File Processing Patterns
Java and .NET Equivalents
76
COBOL Conditional Expressions
Two statement options:
IF/ELSE
EVALUATE statement
Both useful – and have many language patterns and options (you'll see )
In general:
Use IF for coding:
Simple expressions
Conditional statements with tests against multiple fields
Complex statements – with tests against multiple fields
Use EVALUATE for:
Implementing "decision table" logic
Coding statements with multiple tests against a single field
Let's take a close look at both statements
See Slide Notes
77
Conditional Statements – IF Statement Overview
IF statement has two operational modes:
IF
condition
Alphanumeric compare:
On variables of type:
ELSE
Statement
Block
– PIC X
– PIC A
– Group data items
THEN
Statement
Block
– Alphanumeric literal
EBCDIC (or ASCII) value "byte-for-byte"
comparison
END-IF
– Comparison proceeds from Left-to-Right
– Alphanumeric range ( < or > ) is based on
platform's collating sequence
Shorter fields are padded with spaces
(HEX '40') to length of longer variable
– Regardless of which side of the IF statement is shorter/longer
Numeric comparison:
On variables of type PIC 9 or a numeric literal
Algebraic compare
Decimal positions automatically aligned
Note that overall, the IF statement comparison values must be "data type compatible"
78
the
IF Statement Examples
Simple IF - No ELSE
IF/ELSE
Note – matching END-IF for each
IF/ELSE
"Nested" IF/ELSE
Nested IF/ELSE refactored as IF with
AND connectors
Note – only one END-IF
IF POLICY-OVERDUE-DAYS > 90
ADD +100 TO AMT-DUE
END-IF
_____________________________________________________________________
IF EMPLOYEE-SALARY-TYPE = "H"
PERFORM 400-PROCESS-HOURLY-PAY
ELSE
IF
EMPLOYEE-SALARY-TYPE = "S"
PERFORM 400-PROCESS-SALARIED-PAY
ELSE
MOVE "***" TO EMPLOYEE-SALARY-TYP
ADD +1 TO ERRORS-FOUND-KTR
END-IF
END-IF
_____________________________________________________________________
IF HOURS-WORKED > 40
IF HOURLY-EMPLOYEE = "Y"
IF NO-ERRORS-FOUND
PERFORM 900-CALCULATE-HOURLY-OT
END-IF
END-IF
END-IF
_____________________________________________________________________
IF HOURS-WORKED > 40 AND
HOURLY-EMPLOYEE = "Y" AND
NO-ERRORS-FOUND
PERFORM 900-CALCULATE-HOURLY-OT
END-IF
79
COBOL Conditional Statements – IF Statement Overview
Condition may be simple or complex (> 1 simple condition)
There are five simple conditions, which have a truth value of
either true or false:
1.
Class condition:
2.
Condition-name condition:
3.
4.
88-LEVEL Data Items
Relation condition (value-based comparisons)
Sign condition
5.
ALPHABETIC, NUMERIC, ALPHABETIC-UPPER
POSITIVE, NEGATIVE, ZERO
Switch-status condition – used with SPECIAL NAMES (rare)
Use Content-Assist (Ctrl/Spacebar) to view options
A complex condition is formed by combining simple
conditions, combined conditions, and/or complex conditions
with logical operators, or negating these conditions with logical
negation:
AND
OR
NOT
If complex condition, comparisons proceed from Left-to-Right:
But you can (and most of the time should) specify your own
comparison operation precedence by surrounding separate
conditions with parenthesis to make the logic apparent
To humans who read/maintain your code, as well as to the compiler
80
See Notes
IF/ELSE – Examples – and See Slide Notes
FILE SECTION
…
01
OUT-REC
PIC X(80).
…
WORKING-STORAGE SECTION.
77
ITEM-1
PIC X(12).
77
ITEM-2
PIC X(15).
77
ITEM-3
PIC 9(05).
88 VALID-ITEM
VALUES ARE 11111, 22222.
…
PROCEDURE DIVISION.
Simple
IF ITEM-1 > "10"
Relation
Condition
MOVE "X" TO ITEMB
ELSE
PERFORM PROC-A
END-IF
IF ITEM-1 NUMERIC
MOVE ITEM-1 TO ITEM-3
END-IF
Class
Condition
IF VALID-ITEM
Condition-Name
Condition
MOVE ITEM-2 TO ITEM-1
ELSE
MOVE FUNCTION UPPER-CASE(ITEM-2)
TO ITEM-1
END-IF
Complex
Nested IF
Relation
Condition
IF ( ITEM-3 IS POSITIVE ) AND
( ITEM-1 NOT > ITEM-2 )
THEN IF ITEM-3 = 22222
THEN DISPLAY "22222-RECORD"
ELSE DISPLAY "11111-RECORD"
END-IF
ELSE DISPLAY "BAD RECORD"
END-IF
Complex
IF ITEM-1 > "10"
Nested IF
Relation
IF ITEM-1 = ITEM-2
Condition
ADD 1 TO ITEM-3
MOVE ALL "X" TO OUT-REC
END-IF
MOVE "X" TO ITEM-2
END-IF
IF NOT (ITEM-3 < 10 OR ITEM-3 > 500)
AND ITEM-1 <= "Z"
Complex
Nested IF
THEN DISPLAY "Done"
Condition
END-IF
Combing
OR/AND
81
Implied IF Condition Statements
When referring to the same field on
both sides of a compound condition,
you do not have to repeat the variable
name
Example:
IF EMPLOYEE-ID > 20
AND EMPLOYEE-ID < 3000
Can be coded as:
IF EMPLOYEE-ID > 2000 AND < 3000
IF ITEM-2 = "AABBCC" OR "AACCDD"
OR "AADDEE"
MOVE ITEM-2 TO ITEM-1
ELSE
MOVE FUNCTION UPPER-CASE(ITEM-2)
TO ITEM-1
END-IF
IF NOT (ITEM-3 < 10 OR > 500)
ITEM-1 <= "Z"
THEN DISPLAY "Done"
END-IF
There is no hard and fast rule (or even
rule-of-thumb) on this coding idiom.
Pluses:
Creates more compact easily code
Can be more easily readable
AND
Examples of implied IF statement conditions
Minuses
Written semantics are not as exact and
explicit
– Many modern languages do not permit this
Might be misunderstood if merely
browsing or scanning code
IF ITEM-1 NUMERIC AND > 10000
MOVE ITEM-1 TO ITEM-3
END-IF
82
Bypassing Conditional Logic (NEXT SENTENCE and CONTINUE)
There are two standard ways for you to skip
over logic in a complex IF statement that you
must avoid as per business requirements
Code (after the if condition) either:
IF ITEM-2 ALPHABETIC-UPPER
NEXT SENTENCE
ELSE
MOVE FUNCTION UPPER-CASE(ITEM-2)TO ITEM-1
ADD +10 TO AMOUNT-SUB-TOTAL
END-IF
ADD +1 TO REC-KTR
ADD REC-TOTAL TO WS-TOTAL-CLAIMS-PYMNTS
WRITE OUTPUT-RECORD FROM WS-OUT-REC.
NEXT SENTENCE – which branches to
the next sequential statement after an
ending period
…or…
CONTINUE – which branches to the next
sequential statement after an ending period
– OR the IF statement's scope terminator.
GOBACK.
An important distinction – to be sure
Because NEXT SENTENCE is looking for
the next physical period in the source – and
scope-terminators/indentation mean
nothing whatsoever to it, you will probably
want to use: CONTINUE – if you're coding
style is to use scope-delimiters (a best
practice).
Note also that, when you're coding new
programs this is not as problematic as
when you are maintaining existing COBOL
applications
IF ITEM-2 ALPHABETIC-UPPER
CONTINUE
ELSE
MOVE FUNCTION UPPER-CASE(ITEM-2)TO ITEM-1
ADD +10 TO AMOUNT-SUB-TOTAL
END-IF
ADD +1 TO REC-KTR
ADD REC-TOTAL TO WS-TOTAL-CLAIMS-PYMNTS
WRITE OUTPUT-RECORD FROM WS-OUT-REC.
GOBACK.
What if I want to bypass more than
the current logic statement block?
See Slide Notes
83
Conditional Statements – EVALUATE Statement
The EVALUATE statement is COBOL's version of
the (in other programming languages) "case" or
"switch) statement.
EVALUATE provides a shorthand notation for a
series of nested IF statements.
When your program has to test a single variable
for more than two values, EVALUATE is probably a
better choice than nest IF
See next slide
EVALUATE parses a variable value
WHEN is used as the condition expression
You can a single WHEN condition
You can use multiple WHEN statements when
several conditions lead to the same processing
action
You can use a WHEN <value> THRU <value> phrase
to easily code several conditions in a range of
values
You can specify "TRUE" or "FALSE" as the testing
criteria – and can combine with "ALSO"
84
EVALUATE
Statement
WHEN
condition
TRUE
Statement
Block
WHEN
condition
…
TRUE
Statement
Block
WHEN
OTHER
TRUE
Statement
Block
END-EVALUATE
EVALUATE versus Nested IF Statement Comparison
Example 1
IF CARPOOL-SIZE = 1 THEN
MOVE "SINGLE" TO PRINT-CARPOOL-STATUS
ELSE
IF CARPOOL-SIZE = 2 THEN
MOVE "COUPLE" TO PRINT-CARPOOL-STATUS
ELSE
IF CARPOOL-SIZE >= 3 and
CARPOOL-SIZE <= 6 THEN
MOVE "SMALL GRP" TO PRINT-CARPOOL-STATUS
ELSE
MOVE "BIG GRP" TO PRINT-CARPOOL-STATUS
END-IF
END-IF
END-IF
EVALUATE CARPOOL-SIZE
WHEN 1
MOVE "SINGLE" TO PRINT-CARPOOL-STATUS
WHEN 2
MOVE "COUPLE" TO PRINT-CARPOOL-STATUS
WHEN 3 THRU 6
MOVE "SMALL GRP" TO PRINT-CARPOOL STATUS
WHEN OTHER
MOVE "BIG GRP" TO PRINT-CARPOOL STATUS
END-EVALUATE
Example 2
IF MARITAL-CODE = "M" THEN
ADD 2 TO PEOPLE-COUNT
ELSE
IF MARITAL-CODE = "S"
OR MARITAL-CODE = "D"
OR MARITAL-CODE = "W"
THEN ADD 1 TO PEOPLE-COUNT
END-IF
END-IF
EVALUATE MARITAL-CODE
WHEN "M" ADD 2 TO PEOPLE-COUNT
WHEN "S"
WHEN "D"
WHEN "W" ADD 1 TO PEOPLE-COUNT
END-EVALUATE
85
Conditional Statements – EVALUATE – Complex Examples
FILE SECTION
…
01
OUT-REC
PIC X(80).
…
Working-Storage Section.
01 Age
PIC 999.
01 Sex
PIC X.
01 Description PIC X(15).
01 A
PIC 999.
01 B
PIC 9999.
01 C
PIC 9999.
01 D
PIC 9999.
01 E
PIC 99999.
01 F
PIC 999999.
Evaluate True Also True
When Age < 13 Also Sex = "M"
Move "Young Boy" To Description
When Age < 13 Also Sex = "F"
Move "Young Girl" To Description
When Age > 12 And Age < 20 Also Sex = "M"
Move "Teenage Boy" To Description
When Age > 12 And Age < 20 Also Sex = "F"
Move "Teenage Girl" To Description
When Age > 19 Also Sex = "M"
Move "Adult Man" To Description
When Age > 19 Also Sex = "F"
Move "Adult Woman" To Description
When Other
Move "Invalid Data" To Description
End-Evaluate
Evaluate True Also True
When A + B < 10 Also C = 10
Move "Case 1" To Description
When A + B > 50 Also C = ( D + E ) / F
Move "Case 2" To Description
When Other
Move "Case Other" To Description
End-Evaluate
"True ALSO True" means that both conditions in the WHEN clause must be true
to take the WHEN path
86
Unit
COBOL General Language
Rules
Topics:
Assignment Statements and Internal Data
Representation
Math Operations
Conditional Logic
Transfer of control
COBOL Looping Constructs
Sequential File Processing Patterns
Java and .NET Equivalents
87
Topic objectives
By the end of this unit you should Understand how the PERFORM can be used to transfer control to block of
code contained in a paragraph or section..
Know how to use the PERFORM..THRU and the GO TO and understand
the restrictions placed on using them.
Understand the difference between in-line and out-of-line Performs
88
COBOL Transfer of Control Options
Three keywords used to transfer control in traditional COBOL
PERFORM
Branches to the first statement in a block of code
– Inline
– Or, organized in a labeled paragraph or section somewhere else in the PROCEDURE DIVISION
At the end of the performed code, control is automatically returned to the next
sequential instruction following PERFORM
PERFORM is a statement with a number of useful options and extensions
GO TO
Unconditional branch to a labeled paragraph or section
All statements are executed at that point in time – forward in the program
CALL
Invoke another COBOL program
Pass parameters with a USING statement
We will discuss CALL in a future section of this course
Of the above three options:
PERFORM and CALL are best practices for "structured programming"
GO TO is not a best practice, but we will present it, as you will see many
examples of GO TO in production COBOL, and need to understand it
89
PERFORM – External Paragraph or Section
Structured coding method of branching to – and
returning from COBOL paragraphs or sections
With PERFORM, the compiler automatically returns
control to the "next sequential instruction" after the
block of statements in the paragraph or section ends
This makes the program's flow of control easy to read,
easy to understand and easy to maintain
Less worry about "fall thru" logic
PERFORM
May be nested:
This is known as a "PERFORM chain" – or a series of
PERFORM
and return branches controlled by the
Operating System at run-time.
May NOT be recursive:
In this example, within 200-OPEN-FILES you may
not PERFORM 100-HOUSEKEEPING
Does not depend on physical placement or ordering in
the source files:
Although it can help from a read-ability standpoint
to PERFORM paragraphs lower (down) in the
program listing.
Allows you do "divide and conquer" the design and
development of large complex applications.
Do not scope external paragraph PERFORM
with END-PERFORM
90
PROCEDURE DIVISION.
PERFORM 100-HOUSEKEEPING.
PERFORM 300-MAINLINE-RTN.
PERFORM 500-CLEANUP.
GOBACK.
100-HOUSEKEEPING.
PERFORM 150-INITIALIZE-FIELDS.
PERFORM 200-OPEN-FILES.
PERFORM 800-READ-RTN.
150-INITIALIZE-FIELDS.
…
200-OPEN-FILES.
…
300-MAINLINE-RTN.
PERFORM 400-PROCESS-RECORD.
PERFORM 700-WRITE-RTN.
PERFORM 800-READ-RTN.
400-PROCESS-RECORD.
…
500-CLEANUP.
PERFORM 900-CLOSE-FILES.
…
700-WRITE-RTN.
…
PERFORM THRU
One variation on PERFORM is
PERFORM … THRU
PERFORM … THRU allows you to explicitly
mark & bound the end of the PERFORM chain
with a labeled paragraph
All of the procedural statements between:
PERFORM <paragraphName>
and THRU <paragraphName>
…are executed
The best practice is for the exit paragraph to
have one COBOL reserved word in it: EXIT
This returns control to the next sequential
instruction in the perform chain
Technically, you could PERFORM a COBOL
paragraph THRU any other paragraph.
However, this often leads to complex and
unstructured code
Difficult to understand and maintain
So the convention is to PERFORM THRU a
single paragraph EXIT (as shown)
91
PROCEDURE DIVISION.
PERFORM 100-HOUSEKEEPING
THRU 100-EXIT.
PERFORM 300-MAINLINE-RTN
THRU 300-EXIT.
PERFORM 500-CLEANUP
THRU 500-EXIT.
GOBACK.
100-HOUSEKEEPING.
PERFORM 150-INITIALIZE-FIELDS
THRU 150-EXIT.
PERFORM 200-OPEN-FILES
THRU 200-EXIT.
PERFORM 800-READ-RTN
THRU 800-EXIT.
100-EXIT.
EXIT.
150-INITIALIZE-FIELDS.
…
150-EXIT.
EXIT.
200-OPEN-FILES.
…
200-EXIT.
EXIT.
…
See Slide Notes
Inline PERFORM
Another variation on PERFORM is what's
known as an "inline perform"
An inline PERFORM allows you to encase
COBOL statements and business logic within
a structured statement block – which you can
group or loop through (looping is the next
topic, but Inline PERFORM is often used to
control loops.
PERFORM
<statement>
<statement>
…
PROCEDURE DIVISION.
PERFORM UNTIL END-OF-FILE
IF NOT END-OF-FILE
PERFORM 800-READ-INPUT-FILE
IF NOT END-OF-FILE
MOVE INPUT-REC TO OUTPUT-REC
PERFORM 900-WRITE-RECORD
ELSE
MOVE HIGH-VALUES
TO INPUT-REC
PERFORM 1000-CLOSE-FILES
DISPLAY 'NORMAL EOJ
END-IF
END-IF
END-PERFORM.
…
PERFORM VARYING IDX
FROM 1 BY 1 UNTIL IDX > 100
MOVE REC-IN
TO REC-TABLE(IDX)
END-PERFORM.
END-PERFORM.
An in-line PERFORM must be delimited by
the END-PERFORM phrase.
92
…
Scope Terminators and Paragraph Names
100-HOUSEKEEPING.
…
IF ITEM-2 = "AABBCC" OR "AACCDD"
OR "AADDEE"
MOVE ITEM-2 TO ITEM-1
ELSE
MOVE ITEM-3 TO ITEM-1
END-IF
100-EXIT.
This will not compile!
EXIT.
You have seen that many of the
COBOL statements can have Scope
Terminators:
END-IF
END-READ
END-COMPUTE
…
This is actually a coding best practice
However, the last statement before the
paragraph (or "exit paragraph") must end
in a period.
93
Type a period after END-IF
100-HOUSEKEEPING.
…
IF ITEM-2 = "AABBCC" OR "AACCDD"
OR "AADDEE"
MOVE ITEM-2 TO ITEM-1
ELSE
MOVE ITEM-3 TO ITEM-1
END-IF.
100-EXIT.
EXIT.
GO TO – Unconditional Transfer of Control
GO TO branches to the paragraph or section
label after the statement.
With no automatic, compiler-managed return to
the next sequential instruction
Ergo all subsequent statements "fall through"
This can create what is termed "spaghetti
code" – which is typically
Difficult to read
Very difficult to maintain and modify
The use of GO TO is universally denounced
in the academic computing world
And we agree – except for under one very key
and common design pattern (combining GO TO
with PERFORM … THRU)
Our "Best Practices" advice:
Do not use GO TO in COBOL coding, for
transferring control
EXCEPT under one condition – when you are
using GO TO - for branching to the exit paragraph
in a PERFORM … THRU
This honors the Perform Chain and execution
will not "fall through"
94
PROCEDURE DIVISION.
PERFORM 100-HOUSEKEEPING
THRU 100-EXIT.
PERFORM 300-MAINLINE-RTN
THRU 300-EXIT.
GOBACK.
100-HOUSEKEEPING.
PERFORM 200-OPEN-FILES
THRU 200-EXIT.
PERFORM 800-READ-RTN
THRU 800-EXIT.
IF END-OF-FILE
DISPLAY "END-OF-JOB"
PERFORM 900-CLOSE FILES
THRU 900-EXIT
GO TO 100-EXIT
ELSE
ADD +1 TO REC-KTR
MOVE ZEROS TO AMOUNT-TOT
END-IF
Perform 300-INIT-FIELDS.
100-EXIT.
EXIT.
…
Transfer of Control Best Practices
We will cover structured COBOL programming and logic patterns and design
in one of the upcoming units, but for now, consider the following:
Structure your program as a chain of PERFORM THRU paragraphs
Within the paragraphs code anything you need to satisfy your business logic
requirements, including:
CALLs to external programs – CALL is covered in an upcoming unit
Nested PERFORM
Inline PERFORM
Sequence and conditional logic
GO TO – BUT ONLY GO TO a PERFORM THRU paragraph EXIT
Try not to use COBOL SECTIONs
Within COBOL SECTIONs – COBOL paragraphs are considered at the level of
statements – blocks of code where fall through will occur
The only time you will need a COBOL SECTION is when you're programming is invoking
the COBOL SORT verb (which is tied to INPUT and OUTPUT SORT SECTIONs)
95
Unit
COBOL General Language
Rules
Topics:
Assignment Statements and Internal Data
Representation
Math Operations
Conditional Logic
Transfer of control
COBOL Looping Constructs
Sequential File Processing Patterns
Java and .NET Equivalents
96
Topic objectives
By the end of this unit you should Be able to use the PERFORM..TIMES.
Understand how the PERFORM..UNTIL works and be able to use it to
implement while or do/repeat loops.
Be able to use PERFORM..VARYING to implement counting iteration
such as that implemented in other languages by the for construct.
97
COBOL Looping Options
There are three COBOL programming ways to loop:
GO TO <paragraphName> combined with an IF condition that ends the loop:
Unstructured – creates complex, un-maintainable code
NOT a best practice – hence will not be covered
PERFORM <paragraphName> n TIMES
Structured and simple to understand
But only applicable in cases where the number of loop iterations is known at design time
PERFORM <paragraphName> UNTIL a condition is met
Structured ("Good")
Can be used when the number of loop iterations is variable or known
Net: Use PERFORM <paragraphName> UNTIL for your COBOL looping
requirements.
When do you need to loop in your COBOL programs?
Reading/Writing a file until no more records
Looping through rows returned from a database
Loading a COBOL internal table
Processing a COBOL table sequentially
Calculations
Algorithms
…in general – you will write few programs that don't loop
98
PERFORM <paragraphName> n
TIMES
Can PERFORM a paragraph a specified
number of times, in a loop controlled by a:
Numeric literal
Numeric integer variable
Examples:
Performs all of the COBOL statements between
300-MAINLINE-RTN and 300-EXIT
12 TIMES
Performs all of the COBOL statements between
310-SUBTOTALS and 310-EXIT the number
of times represented by the integer value in
NBR-REPS
Use PERFORM … n TIMES – when you know
during development how many loop iterations
should be performed at run-time.
99
WORKKING-STORAGE SECTION.
77
NBR-REPS S9(4) COMP.
PROCEDURE DIVISION.
…
PERFORM 300-MAINLINE-RTN
THRU 300-EXIT
12 TIMES.
GOBACK.
300-MAINLINE-RTN.
…
MOVE IN-REC-KTR TO NBR-REPS.
PERFORM 310-SUBTOTALS
THRU 310-EXIT
NBR-REPS TIMES.
…
300-EXIT.
EXIT.
PERFORM UNTIL <condition>
PROCEDURE DIVISION.
PERFORM 100-HOUSEKEEPING
THRU 100-EXIT.
Structured method of looping when you only
know at run-time how many times the loop
should be iterated over
PERFORM 300-MAINLINE-RTN
THRU 300-EXIT
UNTIL NO-MORE-RECORDS.
UNTIL
GOBACK.
Tests a condition for TRUE/FALSE
If NOT TRUE (repeat – if the condition is
FALSE) PERFORM the specified Paragraph
If TRUE
– End the loop
– Return program control to the next sequential
instruction following the PERFORM UNTIL
statement
Additional notes:
If the UNTIL condition never becomes true?
Infinite loop
– If the program is batch, the TIME= parameter on the
JCL will most likely cancel it
– If the program is an online transaction, the operator
will cancel it
– Either way, this is not a good thing
There are actually two additional options for
PERFORM UNTIL (next slide)
100
100-HOUSEKEEPING.
OPEN INPUT IN-FILE.
PERFORM 800-READ-RTN
THRU 800-EXIT.
100-EXIT.
EXIT.
300-MAINLINE-RTN.
…
PERFORM 800-READ-RTN.
300-EXIT.
EXIT.
800-READ-RTN.
READ IN-FILE INTO WS-RECORD
AT END MOVE 'Y'
TO SW-NO-MORE-RECORDS.
800-EXIT.
EXIT.
PERFORM UNTIL – With TEST
BEFORE or AFTER
PERFORM …UNTIL may be modified by
one of two clauses, coded before UNTIL and
after the paragraph name:
1. WITH TEST BEFORE
PROCEDURE DIVISION.
PERFORM 100-HOUSEKEEPING
THRU 100-EXIT.
PERFORM 300-MAINLINE-RTN
THRU 300-EXIT
WITH TEST BEFORE
UNTIL NO-MORE-RECORDS.
The UNTIL condition is tested before
each PERFORM execution.
The Paragraphs will be executed 0 or
more times
Is the default – if this clause is left
unspecified
2. WITH TEST AFTER
The UNTIL condition is tested after each
PERFORM execution.
The Paragraphs will be executed 1 or
more times
101
GOBACK.
100-HOUSEKEEPING.
OPEN INPUT IN-FILE.
PERFORM 800-READ-RTN
THRU 800-EXIT.
100-EXIT.
EXIT.
300-MAINLINE-RTN.
…
PERFORM 800-READ-RTN.
300-EXIT.
EXIT.
800-READ-RTN.
READ IN-FILE INTO WS-RECORD
…
800-EXIT.
EXIT.
Unit
COBOL General Language
Rules
Topics:
Assignment Statements and Internal Data
Representation
Math Operations
Conditional Logic
Transfer of control
COBOL Looping Constructs
Sequential File Processing Patterns
Java and .NET Equivalents
102
Topic objectives
This topic covers basic (simple) sequential file processing – patterns:
Open files
Read an initial record from the input file
Process all records until end-of-input-file
Edit and validate data
Compute totals, subtotals and accumulators
Write output records
Read the next input file record
Close files and end the job
In subsequent topics of this course, we will dive much more deeply into
file handling, as a majority of COBOL batch processing depends on
concepts and coding patterns that are variations of the above
We will also touch on the basic batch program design patterns you will
want to use going forward in this course and later in your production
COBOL work
By the end of this chapter you will be able to:
OPEN, READ, WRITE and CLOSE files
Loop through and input file, processing all of the records until completed
103
Sequential File Processing
Sequential File Processing consists of a well-documented set of processing –
or a pattern that you will see in many program requirements
You read one or more input files until:
Your business logic requirements are fulfilled
End-of-File
While reading files you typically:
Edit or evaluate data
Add numeric values to total and sub-total fields – perform business calculations
Assign (MOVE) values
WRITE output record(s) – either to an output file, report or both
You must be cognizant of:
Bad or invalid data (and know what to do about it when it shows up in your fields)
Empty input files
READ/WRITE I/O errors that may occur
After reaching end-of-file you will typically:
WRITE a final output record, with summary computed values
CLOSE all files
DISPLAY a successful end-of-job message
Input File
Note - more
than likely
NOT a tape
Device
COBOL Program
Business Logic
104
Record Buffer
Record Buffer
Output Report
Output File
Sequential File Processing Pattern – Simple Batch Design Pattern
This first batch application pattern "Process One Input File" – consists of
the following pattern
Perform an initialization routine
Initialize values in Working-Storage
OPEN the files – for either input or output
PERFORM a "priming" input-record read – an initial read statement that
simplifies:
Empty input-file-processing problems
Reading past end-of-file logic problems
Perform a process-the-file routine, until end-of-input-file
Validate the data – using the conditional logic statements learned in this unit
Move the data – using the assignment statements learned in this unit
Do computations, calculations, etc. – using the COBOL math statements
Write the record
Read the next input record
Perform an end-of-job routine
Complete final computations
WRITE final output record with final computations
CLOSE all files and display an end-of-job message on the Console
105
File I/O Review – OPEN
…
ENVIRONMENT DIVISION.
External
Device
INPUT-OUTPUT SECTION.
External File
SELECT INTFILENAME ASSIGN TO …
…
DATA DIVISION.
FILE SECTION
Record Buffer
FD
INTFILENAME…
01
OUT-REC.
…
Recall the following:
PROCEDURE DIVISION.
SELECT/ASSIGN connects your
…
internal (logical) filename with
OPEN
INPUT FILE1, FILE2
OUTPUT FILE3, FILE4.
external (physical) file-spec
FILE SECTION is required for each
SELECT/ASSIGN file
OPEN references the logical
(internal) filename
Can OPEN multiple files with one
statement (as shown)
…
Note carefully the syntax for OPEN
See Slide Notes, for
additional learning content
106
File I/O Review – READ INTO
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
SELECT INTFILENAME ASSIGN TO …
DATA DIVISION.
FILE SECTION
FD INTFILENAME …
Record Buffer
01 IN-REC.
WORKING-STORAGE SECTION
01 IN-REC-WS.
01 END-OF-FILE-FLAG PIC X.
PROCEDURE DIVISION.
OPEN INPUT INTFILENAME.
READ INTFILENAME INTO IN-REC
AT END MOVE ‘Y’ to END-OF-FILE-FLAG.
…
External
Device
External File
F
I
L
E
R
E
A
D
See Slide Notes,
Recall the following:
File must be OPEN before you try to READ from it
READ retrieves each record from an external file:
- Into the record specified in your FILE SECTION
for additional
learning content
* Note that the DATA DIVISION's FILE SECTION is sometimes referred to as an I/O "buffer"
- Into WORKING-STORAGE - if you've coded READ INTO
AT END condition occurs after the last record is READ from the file
- If you attempt to read past end-of-file your program will ABEND
107
File I/O Review – WRITE FROM
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
SELECT OUTFILENAME ASSIGN TO …
DATA DIVISION.
FILE SECTION
FD
OUTFILENAME…
Record Buffer
01
OUT-REC.
WORKING-STORAGE SECTION
01 OUT-REC-WS.
PROCEDURE DIVISION.
OPEN OUTPUT OUTFILENAME.
External
Device
External File
W
R
I
T
E
O
P
E
R
A
T
I
O
N
WRITE OUT-REC
FROM OUT-REC-WS.
…
See Slide Notes,
Recall the following:
File must be OPEN before you try to WRITE a record to it
- An ABEND condition occurs, if try to write to an un-opened file
WRITE creates a new record at the end of a sequential/external file:
- From the record specified in your FILE SECTION
- From WORKING-STORAGE - if you've coded WRITE FROM
Close opened output files before your program ends
108
for additional
learning content
File I/O Review – CLOSE
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
SELECT INTFILENAME ASSIGN TO …
…
DATA DIVISION.
FILE SECTION
Record Buffer
FD
INTFILENAME…
01
OUT-REC.
…
PROCEDURE DIVISION.
Recall
…
F
I
L
E
External
Device
External File
C
L
O
S
E
the following:
CLOSE
FILE1, FILE2,
FILE3, FILE4.
CLOSE every opened file
…
Can CLOSE multiple files with one
statement (as shown)
Can re-OPEN a file after closing
- Input file
- Output file
Note carefully the syntax for
CLOSE
See Slide Notes, for additional learning content
109
Sequential File Processing Pattern –
Pseudo-Code
In a subsequent unit of this course we will
cover the concept of design and programming
patterns with COBOL
For now, here is your first simple, sequential
file-handling pattern, in pseudo-code.
Study the control-flow to understand the
paragraph PERFORM process, and purpose
of each statement block
Tie this back to the code you the previous
slide in this unit.
What is not part of this processing pattern are
the actual details of the:
Data Validation
Calculations and computations
… which can be extremely complex and will most
likely take up the majority percentage of your
coding cycles.
There are other algorithms that can do the
same sequential process, but we feel this is a
simple, easy-to-read/maintain/debugsupport/and extend approach
110
PROCEDURE DIVISION.
Do Init-Routine
Do Process-Files
until No-More-Data
Do End-of-Job-Routine
GOBACK.
Init-Routine.
Open files
READ Input-File
Process-Files.
Validate input data
Perform calculations and
sub-totals
Move data to output Record
Write Output-Record
READ Input-File
End-of-Job-Routine.
Final computations
Move Data to output Record
Write output record
Close Files
Putting it All Together - A Complete Example of a Sequential File
Processing Program
Read through (study) the code in this sample
small sequential file processing program.
Trace the concepts, COBOL syntax and
statement semantics learned in this, and
the previous Unit to the actual code in this
program.
Feel free to refer-back to your slides, the
course supplemental text or your notes – if
necessary
Select External File
Assign to COBOL
(internal) file name
FILE SECTION FDs
Matching the SELECT/ASSIGN
Clauses for each external file
Note – this example continues over the next three slides
111
A Complete Example of a Sequential File Processing Program
– WORKING-STORAGE SECTION
File Status fields
Automatically updated
By COBOL and the O.S.
A final-totals output record
Input and Output records
You will often see these
coded in WORKINGSTORAGE because they
are easier to find in a
System log file (called a
DUMP file) if your
program files (ABENDS)
when executing on the
mainframe
Holding fields for intermediate
result calculations and values
112
A Complete Example of a Sequential File Processing Program – PROCEDURE DIVISION
E
D
I
T
S
Processing
• Calculations
• Computations
Our Sequential File Pattern – in COBOL
M
O
V
E
Read the code line-by-line (as if you were debugging it –
In other words, if there's a PERFORM – jump down to the
Performed paragraph. When finished jump back, etc.)
Note the use of:
• PERFORM THRU
• AT END/GO TO "EXIT"
• PERFORM UNTIL
• For each record in the input file, do 100-MAINLINE
Write the current record
Read the next record in the file
113
A Complete Example of a Sequential File Processing Program
– No More Records in the File
When there are no more
records left to process
Do final calculations
Move the fields to final output record
WRITE
CLOSE all files
Display a message on the console
114
®
IBM Software Group
Enterprise COBOL Education Using Rational Developer for System Z
COBOL Report Writing Patterns
Jon Sayles, IBM Software Group, Rational EcoSystems Team
© 2006 IBM Corporation
Purpose of This Document
Course Name: COBOL Foundation Training - with RDz
Course Description: Learn the COBOL language, RDz and learn z/OS terms, concepts and development skills in
this course.
Pre-requisites: Some experience in a 3rd or 4th Generation Language is expected. SQL is also recommended.
Course Length: 10 days
Topics (Agenda)
Getting Started - installing and configuring RDz - and the course materials, and using Eclipse to edit COBOL
COBOL General Language Rules
Basic COBOL Statements
Advanced record and table handling
Debugging Programs - Note: Deep dive on using RDz for common COBOL programming errors (001, 0C4, 0C7, infinite loops, fall-thru, etc.)
Input/Output and Report Writing Patterns
COBOL Subprograms and the Linkage Section
Structured Programming Concepts, professional COBOL development practices and Coding Patterns
Advanced Character Manipulation, COBOL Intrinsic Functions, Date and Time coding patterns, and Language Environment calls
OS/390 Concepts and JCL - Compile/Link & Run Procs on the mainframe
Indexed file Coding Patterns
Sort/Merge, Sequential File Match/Merge and Master File Update Coding Patterns
Accessing DB2 Data and DB2 Stored Procedures
COBOL in the Real World:
– CICS - lecture only
– IMS (DL/I and TM) - ditto
– Batch processing - ditto
– Java calling COBOL
– COBOL and XML Statements
– SOA and COBOL - creating and calling Web Services
– Web 2.0 using Rich UI
116
Course Details
Audience
This course is designed for application developers who have programmed in
some language before, and who wish to learn COBOL.
Prerequisites
This course assumes that the student has the basic knowledge of IS
technologies, data processing, software and have programmed for at least
two or more years in a language such as: Java, VB, RPG, PL/1, Pascal, or
some 4th Generation Language or tool.
Knowledge of SQL (Structured Query Language) for database access is
assumed as well.
Basic PC and mouse-driven development skills is also assumed.
Finally, it is assumed that you have been following along in this course, and
have successfully completed the learning modules in sequence.
Or have the equivalent COBOL background obtained through some other form of
COBOL study or on-the-job work.
117
Unit
COBOL Report Writing Patterns
Topics:
Report Writing Concepts
COBOL Print and Report Layouts
COBOL Control Break Reports
Appendices
118
COBOL Reporting – a Little History
Since its inception (the late 1950's) COBOL has been the dominant language of
business application development
For the first 30-40 years (yes, a COBOL application's shelf-life measure in decades what
some application languages aspire towards, measured in years) businesses founded on
COBOL used the language for:
Data capture and storage – using:
Sequential files
Indexed files
Hierarchical databases
Networked (CODASYL) and other pointer-based
databases (such as Model 204)
Relational databases
Object databases
Reporting applications – both broad and deep, used in every aspect of the business world
Online applications
Batch (non-reporting) applications – data consolidation, computationally intensive
applications, etc
Internet application
Now in its 6th decade, COBOL applications still do all of the above – but certainly
not in the same ratio and proportion they did in the 70's, 80's and 90's
In fact, one type of COBOL business application that is only marginally as important as it was
in the past is the reporting application – specifically traditional print reports or "green bar"
reports (See Slides)
119
Why Learn About COBOL Reporting Applications
Traditional reporting applications consumed a large portion of early COBOL
practitioner time and attention
The COBOL language even has a REPORT SECTION – in the DATA DIVISION that
provides special keyword vocabulary for creating reports
Business reports in fact were so critical to commercial shops that throughout the
1970's 1990's dozens of high-quality reporting products emerged on the market
to simplify and streamline report development
Some by IBM
Many, many, many others – by 3rd Party IBM Business Partners *** See Slide Notes
The reason for these non-COBOL/3rd Party products was that essentially, Reporting
Applications written in any general-purpose 3rd generation computing language:
Are time-consuming and labor-intensive to create
Can be built from special-purpose tools and using proprietary report-programming languages:
Quickly
Cost-effectively
Often are time-dependent, in that unlike data, which has intrinsic and lasting value to organizations,
reports are essential "the original" U.I. of business applications
And U.I.s have changed drastically since 1960 – haven't they
While the production source-code assets represented by the 3rd Party products have not
necessarily maintained their position, you will still most likely find the knowledge of how create
COBOL reports useful for the following reasons:
You may end up writing a "quick-and-dirty" report against production data (these are sometimes called
"one-offs"
You will most likely have to maintain and/or support COBOL reporting applications still running in
production.
120
COBOL Reporting Applications – Big Picture
The figure below shows a typical COBOL reporting application, which contains the
following elements:
A sorted sequential data source – one of the following:
On the mainframe a QSAM file – on the PC a "flat file" or sequential file
One the mainframe a VSAM or off the mainframe an indexed file – read sequentially
A database (IMS-DL/I, CA-IDMS, DB2, or other) read sequentially
A program that processes records from the data source:
Read file – usually sequentially, until end-of-file
Validate/Compute each record, move fields
Write report – that there are a few new COBOL WRITE clauses specific to reporting applications
A report – or report file, that is laid out according to precise U.I. record descriptions
And quite possibly a file of error records, produced by the COBOL program's validation routine
COBOL Program
Business Logic
121
Record Buffer
Sorted
Sequential
File
Record Buffer
We continue by looking at each part of the above
Error Report
Sequential Input Files – For COBOL Reporting Applications
If you've been following along in this course
you've already done a bit of work with Sequential
Files.
Which are simple data structures that store records
serially
Such that the records are read one after another
These records can be sorted or un-sorted.
Sequential File – Sorted
Sequential File - Unsorted
RECORD1………………………….
RECORD5………………………….
RECORD2………………………….
RECORD2………………………….
RECORD3………………………….
RECORD6………………………….
RECORD4………………………….
RECORD4………………………….
RECORD5………………………….
RECORD5………………………….
RECORD6………………………….
RECORD1………………………….
…
…
We will cover sorting in an upcoming unit
COBOL Reports will just about always require the data to be sorted, and we will
discuss various means of doing that in subsequent course sections:
COBOL internal sort
Operating System (JCL) sort
3rd Party Sort packages
The data in the sorted sequential file records will be read into 01 record structures
Typically READ <fileName> INTO <ws-RecordName>.
The input record layouts correspond to the input data – which you've seen a number
of times now
01 records
Group fields (levels 05 and higher)
– Elementary fields, 88 levels, etc.
122
A Simple Report
Have a look at this report
1.
2.
3.
Let's break down the output
or report-specific elements
4.
1.
Page Heading
This line should be at the top of each page
Question … how will we know when to do a "Page Break"?
2.
Answer: A page break should occur when the total # of lines written exceeds the max-lines-per-page print
specification
Column Headings
These lines (sometimes the faux-underlines are there…sometimes they're not) should be just under the
Page Heading
3.
Detail Rows
We will format one row of output/detail report values for each input record
4.
Report Footer
This line is displayed at the end of the entire report.
It would typically include additional report totals, counters and accumulators – although we have not
coded for this in our example
123
Working Storage for the Simple Report
From the code shown here
Match each of the 01s to the
output shown (below)
One 01 is not shown in the
report
You will add this in, when you do
your work
Answer the following questions:
Why the VALUE SPACES next
to the FILLER fields?
Are the report columns lined up?
What do you think the input for
this report looks like?
124
Input Data and Record Layout for the Simple Report*** See Slide Notes
From the graphic below, note the input fields in the input file (Sorted
Sequential File).
Map each field to its respective variable in CustomerRec
Answer the following questions:
How many fields are there (total) – not counting the 10-level break out of the date field?
Are any of the fields packed decimal or binary data?
Is the data as shown, sorted?
What "key" (what input field variable) is it sorted on
Ascending or Descending sort?
Error Report
Sorted
Sequential
File
*** Slide Notes
COBOL Program
Business Logic
125
Procedure Division for the Simple Report
So – as this example is primarily:
Read Move to output file Write
we can assume the logic is relatively
straightforward
And? It is.
Read the code shown here, and follow the
flow of control. Note the following:
File OPEN/CLOSE statements
Initial report heading and file read
statements
Logic to perform the main business logic
and report production paragraph until no
more data. Within that paragraph:
Check for page break condition
Move statements from the input to the
output variables
Write detail line:
– AFTER ADVANCING LINE
forces
the printer to skip # lines between
Read next input record
Final Print Headings
126
Workshop – Sequential File Processing
– 1 of 7
1.
As you have done several times so far, Create a
new, Workstation Local, COBOL project
Name it: chapter4
Be sure to select COBOL Sample Property Group
2.
In the chapter4 Project, create a new cobol folder
(as shown)
3. Copy the COBOL source code from the Notes
section of the slide
4. Create a new file in the chapter4 project, in the
cobol folder, named: rpt1.cbl
5. Paste the code in the editor
6. Do a Local Syntax check of the program
7. Right-click and Nominate rpt1 as the Entry Point
8. Rebuild the chapter4 project
9. Expand the BuildOutput folder, right-click and
select Debug As > Debug Configurations
10. Setup a new Debug Configuration as shown
11. Debug the program
Step to understand the code flow
Resume (run) to end of program
12. Look at the output file produced
(probably: c:\customerOut.dat)
127
Workshop – Sequential File Processing – 2 of 7 – Maintenance Specs
Let's throw in some new specs for a "maintenance" workshop. To complete the work
required, you will need to:
Edit the input records read. Only allow records with:
Valid numeric CustomerIDs
The year-in (YYYY) between 1990 and the current year
– You will have to ACCEPT the CURRENT DATE into an 8-byte date format (see code example in
upcoming slide for an example of this)
All records in error should be written to a new error output file – unformatted
Add counters for:
# of error records found
# of Good error records written
Total # of input records read – the sum of this should equal the # of error records + the number of
good records*** See Notes
Change Page Break to occur after 10 records
Fix the bug in the Active/Inactive output value – currently it's only writing I or A,
and should write out Inactive or Active
See the next slide for an example new report
Use the values in the slide notes for new input test records
Sometimes known as test cases
Please read through all of the Workshop Slides before beginning to code. Note
the use of PERFORM … THRU EXIT – which simplifies modifying logic
128
Workshop – 3 of 7
– Output Report
Note the following:
Page #s at the bottom of each page
Statistics
129
Workshop – 4 of 7 – Environment and Data Division
Note the following:
New file Select/Assign and FD for the Error
records
Redefinition of CustomerID – in order to do a
numeric Class test on it
130
Workshop – 5 of 7 – Data Division and
Procedure Division
Note the following:
New value for PageBrkReq
New counters for records read/written, good,
bad, indifferent, etc.
Current-Date variable and Aceppt statement
New file open/close/read/write
Added EXIT statements to the 100paragraph, to simplify maintaining the code
131
Workshop – 6 of 7
Note the following:
Code for adding to the various record
counters
New routine for handling the error
records – inline within the current logic
New input edit sample
Note the use of the following logic
pattern:
Find an error
Deal with the error
Skip to the end of the function
132
Workshop – Sequential File Processing – 7 of 7
Suggested course of action:
Code the ENVIRONMENT, and DATA Division elements
Syntax check and Build the Project
Code the remaining PROCEDURE DIVISION logic
Use Content Assist to help you code references to the fields and records
– This is why you'll do the data variable coding first
Syntax check
Build the Project
Debug your program
Run your program – and verify your work by reviewing the output files
If time permits, add the following new requirements:
Additional Working Storage and output variables that count the # of Active and
Inactive accounts
Add the current date to the top right-hand corner of the page, in ISO format
Move the page # to the top-left of each page
133
Unit
COBOL Report Writing Patterns
Topics:
Report Writing Concepts
COBOL Print and Report Layouts
COBOL Control Break Reports
Appendices
134
COBOL Report Writing Statements – WRITE AFTER ADVANCING Options
The SPECIAL-NAMES paragraph:
Relates IBM-specified environment-names to userdefined mnemonic-names.
Relates alphabetic-names to character sets or
collating sequences.
Relates class names to sets of characters.
Specifies a substitute character for the currency
sign.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SOURCE-COMPUTER. IBM-370-168.
OBJECT-COMPUTER. IBM-370-168.
SPECIAL-NAMES.
C01 IS TO-TOP-OF-PAGE.
…
01
01
In this example C01 is a "special name" that is used
with the WRITE I/O verb, to skip to the top of the
next page when the output file is attached to a
printer that accepts files formatted for printing (i.e.
with special characters for advancing to the next
physical page, etc.).
01
HEADER-1.
05 FILLER
05 FILLER
05 FILLER
05 DATE-OUT
05 FILLER
HEADER-2.
05 FILLER
05 FILLER
05 FILLER
HEADER-3.
05 FILLER
05 FILLER
05 FILLER
05 FILLER
PIC
PIC
PIC
PIC
PIC
X(12) Value
X(21) VALUE
X(03) Value
99/99/99.
X(02) Value
PIC X(08)
PIC X(19)
PIC X(17)
Spaces.
'ANNUAL INCOME STATEMENT'.
Spaces.
Spaces.
VALUE 'EMPLOYEE'.
Value Spaces.
VALUE 'ANNUAL TAKE HOME'.
PIC X(02) VALUE SPACES.
PIC X(08) VALUE 'EMP-ID'.
PIC X(24) VALUE SPACES.
PIC X(03) VALUE 'SALARY'.
…
700-WRITE-REPORT-HEADING-LINES.
WRITE EMPL-REPORT-REC FROM HEADER-1
AFTER ADVANCING n LINES
Is a clause of the WRITE statement, that directs
the printer to advance the next physical line in the
report paper
Can specify AFTER or BEFORE
LINES is optional
Note the use of BEFORE ADVANCING 0 LINES –
executed multiple times.
This is used to make a header or bold on a report
135
AFTER ADVANCING TO-TOP-OF-PAGE.
WRITE EMPL-REPORT-REC FROM HEADER-2
AFTER ADVANCING 2 LINES.
WRITE EMPL-REPORT-REC FROM HEADER-3
AFTER ADVANCING 1.
…
WRITE EMPL-REPORT-REC FROM TOTAL-LINE
BEFORE ADVANCING 0 LINES.
WRITE EMPL-REPORT-REC FROM TOTAL-LINE
BEFORE ADVANCING 0 LINES.
WRITE EMPL-REPORT-REC FROM TOTAL-LINE
BEFORE ADVANCING 0 LINES.
Workshop – Open Ended
One more maintenance assignment. We now have to account for four
quarters worth of taxes (this program is run at end-of-year).
Replace the existing c:\customerIn.dat data, with the records in the Slide Notes
Recode the input file's layout to match the new test case values
Create an output report that matches the next slide's screen capture
Add in one more statistic kept:
Average annual taxes paid (see next slide for snapshot of result)
You will have to be cognizant of:
Numeric output formatted fields
Lining up the columns of the report and the final average value
136
Workshop – Open Ended
137
Workshop Coding Solution
There is a coding solution to this
simple report programming
problem in the slide notes.
Considerations:
This is only one interpretation of
how to do this workshop
It is offered here as
– Caveat Emptor
If you choose to use this, we
recommend you rename the
program
So that if you want to finish your
own version of this workshop you
won't have to rename files, etc.
Optional
Add the State values into the
output print (Rpt-Detail-Hdg-1 and
Rpt-Detail-Hdg-2) lines
138
Unit
COBOL Report Writing Patterns
Topics:
Report Writing Concepts
COBOL Print and Report Layouts
COBOL Control Break Reports
Appendices
139
What Are Control Breaks?
A "Control Break" in COBL program vernacular, refers to a change in a
control field value – typically in a sequential file, such that, upon successive
reads when the value changes? A processing change happens in the
program – and you would perform a routine that prints a control-break line
containing: Summary values, sub-totals and/or statistics:
Lines counted – for all of the records since the last control break
Accumulators - numeric values such as: Number of items sold, Total expenses, etc.
Statistics – average, min, max salaries, etc.
The pre-requirement for Control Break functionality is for the sequential file
to be sorted on the values in the control break field
Or there would be random control breaks in the output processing
Control Break reports are common in COBOL applications. They expose
summary values and statistics, and help turn raw data into the information
necessary to run a business.
Show me the total sales for our retail stores broken out by:
State
Store Departments
Months of the year
Individual stores
140
Single-Level Control Break Report – Example Break on U.S. State Values
Note that the
"control
break"
occurs:
Each time
the State
changes
And at the
end of the
report (an
implied final
control
break)
141
What Are Control Breaks?
The pseudo-code for a
single-level Control
Break report is as
follows
Note that this logic could
be divided up into COBOL
paragraphs sections or
simply inline routines –
depending on the
complexity and scope of
each element
Do Initial Process
Do Process All Records until end-of-file
Do End-of-Program Process
Initial Process
Write headers
Process first record
Move control break field to a hold-area (for comparison)
Process All Records
Edit – or Do Edit Routine
If good record
– If Current control-break-value <> hold-control-break-value
– Do Control Break Process
– Process Detail Record
– Read next input record
Process Detail Record
Add to hold fields and accumulators
Move fields to output fields
Write Detail Record
Control Break Process
Move hold control break values to output fields
Write Control Break Record
Zero out control break hold areas
Move Current control-break-value to hold-control-break-value
End-of-Program Process
Do final control break
Do final output report processing
142
COBOL Program to do Control Break – DATA DIVISION Areas – 1 of 3
2.
Here's a completed example of a
Control Break program. Note the
following:
1.
2.
3.
4.
Input record with two new fields for
control break values (we will use only
StateCode for this first part of the unit)
The Control Break report line
Hold areas for the Control Break
interim-values
The Control Break "hold keys" – that
will be used to as comparison values
with each new record read, to
determine if there has been a "control
break" in the file
…more fields…
3.
…more fields…
1.
4.
143
COBOL Program to do Control Break –
Procedure Division – 2 of 3
5.
6.
5.
Driver Logic (from our pseudo-code)
Process All Records – which includes
PERFORM statements to paragraphs on the next
slide
7.
6.
Control Break Process – note the detailed logic
in the comments
7.
Note that this is actually the same program we
have been working with all along in this unit,
just better structured
144
8.
COBOL Program to do Control Break –
Final Paragraphs – 3 of 3
Process Detail Records – note the additional
code to add to the Control Break hold areas
9. Initial Process paragraph – to setup the
report, do the priming file read, and initialize
the control break values
10. End-of-Program Process – which does the
final control break, and writes out the
standard end-of-job report summary lines
8.
10.
9.
145
Note also that we've made the Read Routine
into a separately performed paragraph. This
is a "best practice"
Workshop – Control Break Reports – 1 of 4
1.
2.
From the slide notes, copy all of the new data records – that contain the State code, and paste
them into c:\customerIn.dat – replacing the existing records
View the state values in the file – note that they are sorted from low to high (from California to
Hawaii).
146
Workshop – Control Break Reports – 2 of 4
1.
From the slide notes, copy the program source (all of the COBOL statements)
2.
3.
4.
5.
6.
7.
8.
Create a new file in the chapter4 project, in the cobol folder, named: rpt2.cbl
Paste the code in the editor
Do a Local Syntax check of the program – ensure no errors
Right-click over rpt2, and Nominate as Entry Point
Rebuild the chapter4 project
Expand the BuildOutput folder, right-click and select
Debug As > Debug Configurations
Setup a new Debug Configuration as shown
9.
Debug the program
Step to understand the code flow
Resume (run) to end of program
10. Look at the output file produced
(probably: c:\customerOut.dat)
Unless you've changed the file
Return to z/OS Project Perspective
147
Workshop – Control Break Reports – 3 of 4 – Development Specs
Let's throw in some new specs for a brand new control break program that
produces a listing of employee salaries by state. Using the data in the Slide Notes,
create: c:\employee.dat. (see screen capture)
Note – these are well-paid employees. Probably hedge fund managers.
It will line up the with the EMPLOYEE-RECORD layout shown below
Using the Control Break pattern from rpt3.cbl – create a program in the chapter4
cobol folder that produces the Control Break report shown on the next slide
There are no edit errors in this file, so you can just concentrate on coding the
Control Break logic pattern
Break on
EMPLOYEE-STATE
value change
c:\employee.dat
148
Workshop – Control Break Reports – 4 of 4 – Development Specs
The employee salary
Control Break Report
Optional workshop
functionality includes:
A report header
With the current date
And page#
And edit routine for:
Valid numeric salary
A more realistic salary
range for employees
(who are not hedge fund
managers)
149
What About Multi-Level Control Break Reports?
As common as single-level control break functionality in COBOL business
applications are multi-level control break reports, that have:
Major key
Middle key
– Minor key
Or more levels of control break, and that process data in files that is sorted on the same key sequence.
Consider this example of a (fictitious) grocery store report
Major Key
Middle Key
Minor Key
Note keys of: State, City, Store#
And coincidentally, note that additional data control breaks would be possible (probable?) along the lines
of Store Department and SKU
At the risk of repeating ourselves, control break processing turns data into information
150
Data For a Two-Level Control Break Report
If you're going to break on
two control fields, you need
to columns of data, both
sorted, in a
Parent Child, or
Master Detail sequence:
Sort on Parent key
values
Within the Parent key,
sort on Child key values
Note the following – in our
current customerIn.dat file:
Master/Parent Key data:
State code
Detail/Child Key data:
Territory code
Find both sets of values in
this screen capture
Question: So if we have our data arranged by this two-level control break sequence, what elements in our
program do you think we'll have to change?
Answer:
Output report lines
A Parent/Master control break test and processing paragraph
A Child/Detail control break test and processing paragraph
The various hold areas, counters and accumulators coded for both Parent and Child control breaks
This will be clearer if we have a look at the output produced (next slide)
151
A Two-Level Control Break Report
Note the following:
Detail/Child control
break line
Master/Parent control
break line
Let's have a look at the
actual COBOL code
used to produce this.
152
COBOL Code For a Two-Level Control Break – 1 of 2
We're going to reuse the rpt2.cbl
program for this example.
We will enhance it to add:
A Control Break output line for
Territory Control Breaks
Hold fields for Territory values
…more fields…
Note that we will have to rename
the generically-named State
fields
…more fields… and begin Procedure Division
In the PROCEDURE DIVISION
we see the key logic
modification
Test for a Major/Parent key
control break … then …
Test for a Minor/Child key control
break
– In that order
153
COBOL Code For a Two-Level Control Break – 2 of 2
We will need a new Minor/Child control
break processing paragraph – that will
eerily resemble the Major/Parent control
break process.
With a few exceptions:
The Parent control break will perform the
child control break
Note that this could happen for any #
of intermediate levels as well –
following the data sort key
relationships from highest to lowest
sort-key
What's important is that the Perform
of lower-level control breaks happen
BEFORE the upper-level control
breaks.
The Child control break will print out
the Territory line – and re-initialize
the counters and accumulators
154
Workshop – A Two-Level Control Break Program
Return to your single-level Control
Break program.
You will use the new data records
for c:\employee.dat
They are in the Slide Notes
Enhance the program to produce
the report shown on the next slide
155
Workshop – A Two-Level Control Break Program
Note the Sub-Totals
and total values.
156
Unit
COBOL Report Writing Patterns
Topics:
Report Writing Concepts
COBOL Print and Report Layouts
Simple COBOL Reports
Control Break Reports
Appendices
157