PROCEDURE DIVISION
PROCEDURE DIVISION Syntax
=======================================================================
PROCEDURE DIVISION
~~~~~~~~~ ~~~~~~~~
[ { USING Subprogram-Argument... | CHAINING Main-Program-Argument... ]
~~~~~ ~~~~~~~~
[ RETURNING identifier-1 ] .
~~~~~~~~~
[ DECLARATIVES.
~~~~~~~~~~~~
[ Event-Handler-Routine... . ]
END DECLARATIVES. ]
~~~ ~~~~~~~~~~~~
[ [ Section-name1 SECTION. ]
~~~~~~~
[ [ paragraph-name-1. ]
[ procedural-sentence-1 ]... .
]...
]...
[ Nested-Subprogram... ]
[ END PROGRAM | FUNCTION name-1. ]
~~~ ~~~~~~~ ~~~~~~~~
=======================================================================
The PROCEDURE DIVISION of any GnuCOBOL program marks the point where all executable code is written.
PROCEDURE DIVISION USING
PROCEDURE DIVISION Subprogram-Argument Syntax
=======================================================================
[ BY { REFERENCE [ OPTIONAL ] } ] identifier-1
{ ~~~~~~~~~ ~~~~~~~~ }
{ VALUE [ [ UNSIGNED ] SIZE IS { AUTO } ] }
~~~~~ ~~~~~~~~ ~~~~ { ~~~~ }
{ DEFAULT }
{ ~~~~~~~ }
{ integer-1 }
=======================================================================
The USING clause defines the arguments that will be passed to a GnuCOBOL program which is serving as a subprogram.
The reserved words
BYandISare optional and may be omitted. The presence or absence of these words have no effect upon the program.The
USINGclause should only be used on the procedure division header of subprograms (subroutines or user-defined functions).The calling program will pass zero or more data items, known as arguments, to this subprogram — there must be exactly as many <identifier-1> data items specified on the
USINGclause as the maximum number of arguments the subprogram will ever be passed.If a subprogram does not expect any arguments, it should not have a
USINGclause specified on its procedure division header.The order in which arguments are defined on the
USINGclause must correspond to the order in which those arguments will be passed to the subprogram by the calling program.The identifiers specified on the
USINGclause must be defined in the linkage section of the subprogram. No storage is actually allocated for those identifiers in the subprogram as the actual storage for them will exist in the calling program.A GnuCOBOL subprogram expects that all arguments to it will be one of two things:
The memory address of the actual data item (allocated in the calling program) that is being passed to the subprogram.
A numeric, full-word, binary value (i.e.
USAGE BINARY-LONG(see USAGE)) which is the actual argument being passed to the subprogram.
In the case of the former, the
USINGclause on the procedure division header should describe the argument via theBY REFERENCEclause — in the latter case, aBY VALUEspecification should be coded. This allows the code generated by the compiler to properly reference the subprogram arguments at run-time.BY REFERENCEis the assumed default for the firstUSINGargument should noBYclause be specified for it. Subsequent arguments will assume theBYspecification of the argument prior to them should they lack aBYclause of their own.Changes made by a subprogram to the value of an argument specified on the
USINGclause will “be visible” to the calling program only ifBY REFERENCEwas explicitly specified or implicitly assumed for the argument on the subprogram’s procedure division header and the argument was passed to the subprogramBY REFERENCEby the calling program. See Subprogram Arguments, for additional information on the mechanics of how arguments are passed to subprograms.The optional
SIZEclause allows you to specify the number of bytes aBY VALUEargument will occupy, withSIZE DEFAULTspecifying 4 bytes (this is the default if noSIZEclause is used),SIZE AUTOspecifying the size of the argument in the calling program andSIZE integer-1specifying a specific byte count.The optional
UNSIGNEDkeyword, legal only ifSIZE AUTOorSIZE integer-1are coded, will add theunsignedattribute to the argument’s specification in the C-language function header code generated for the subprogram. While not of any benefit when the calling program is a GnuCOBOL program, this can improve compatibility with a C-language calling program.The
OPTIONALkeyword, legal only onBY REFERENCEarguments, allows calling programs to codeOMITTEDfor that corresponding argument when they call this subprogram. See CALL. for additional information on this feature.
PROCEDURE DIVISION CHAINING
PROCEDURE DIVISION Main-Program-Argument Syntax
=======================================================================
[ BY REFERENCE ] [ OPTIONAL ] identifier-1
~~~~~~~~~ ~~~~~~~~
=======================================================================
The CHAINING term provides one mechanism a programmer may use to retrieve command-line arguments passed to a program at execution time.
PROCEDURE DIVISION CHAININGmay only be coded in a main program (that is, the first program executed when a compiled GnuCOBOL compilation unit is executed). It cannot be used in any form of subprogram.The
CHAININGclause defines arguments that will be passed to a main program from the operating system. The argument identifiers specified on theCHAININGclause will be populated by character strings comprised of the parameters specified to the program on the command line that executed it, as follows:When a GnuCOBOL program is executed from a command-line, the complete command line text will be broken into a series of tokens, where each token is identified as being a word separated from the others in the command text by at least one space. For example, if the command line was
/usr/local/myprog THIS IS A TEST, there will be five tokens identified by the operating system — ‘/usr/local/myprog’, ‘THIS’, ‘IS’, ‘A’ and ‘TEST’.Multiple space-delimited tokens may be treated as a single token by enclosing them in quotes. For example, there are only three tokens generated from the command line
C:\Pgms\myprog.exe ‘THIS IS A’ TEST— ‘C:\Pgms\myprog.exe’, ‘THIS IS A’ and ‘TEST’. When quote characters are used to create multi-word tokens, the quote characters themselves are stripped from the token’s value.Once tokens have been identified, the first one (the command) will be discarded; the rest will be stored into the
CHAININGarguments when the program begins execution, with the 2nd token going to the 1st argument, the 3rd token going to the 2nd argument and so forth.If there are more tokens than there are arguments, the excess tokens will be discarded.
If there are fewer tokens than there are arguments, the excess arguments will be initialized as if the
INITIALIZE identifier-1(see INITIALIZE) statement were executed.All identifiers specified on the
CHAININGclause should be defined asPIC X, PIC A, group items (which are treated implicitly asPIC X) or asPIC 9 USAGE DISPLAY. The use ofUSAGE BINARY(or the like) data items asCHAININGarguments is not recommended as all command-line tokens will be retained in their original character form as they are moved into the argument data items.If an argument identifier is smaller in storage size than the token value to be stored in it, the right-most excess characters of the token value will be truncated as the value is moved in. Any
JUSTIFIED RIGHTclause on such an argument identifier will be ignored.If an argument is larger in storage size than the token value to be stored in it, the token value will be moved into the argument identifier in a left-justified manner. unmodified-modified byte positions in the identifier will be space filled, unless the argument identifier is defined as
PIC 9 USAGE DISPLAY, in which case unmodified bytes will be filled with ‘0’ characters from the systems native character set.This behaviour when the argument is defined as
PIC 9may be unacceptable, as an argument defined asPIC 9(3)but passed in a value of ‘1’ from the command line will receive a value of ‘100’, not ‘001’. Consider defining “numeric” command line arguments asPIC Xand then using theNUMVALintrinsic function (see NUMVAL) function to determine the proper numeric value.
PROCEDURE DIVISION RETURNING
PROCEDURE DIVISION RETURNING Syntax
=======================================================================
RETURNING { identifier-1 }
~~~~~~~~~ { OMITTED }
~~~~~~~
=======================================================================
The RETURNING clause on the PROCEDURE DIVISION header documents that the subprogram in which the clause appears will be returning a numeric value back to the program that called it. This is only available for functions as it does not work for programs and has issues depending on the platform (operating system) in use - You must test for this for the specific platform.
The
RETURNINGclause is optional within a subroutine, as not all subroutines return a value to their caller.The
RETURNINGclause is mandatory within a user-defined function, as all such must return a numeric result.The <identifier-1> data item should be defined as a
USAGE BINARY-LONGdata item.Main programs that wish to “pass back” a return code value to the operating system when they exit do not use
RETURNING- they do so simply by MOVEing a value to theRETURN-CODEspecial register.This is not the only mechanism that a subprogram may use to pass a value back to its caller. Other possibilities are:
The subprogram may modify any argument that is specified as
BY REFERENCEon itsPROCEDURE DIVISIONheader. Whether the calling program can actually “see” any modifications depends upon how the calling program passed the argument to the subprogram. See CALL, for more information.A data item with the
GLOBAL(see GLOBAL) attribute specified in its description in the calling program is automatically visible to and updatable by a subprogram nested with the calling program. See Independent vs Contained vs Nested Subprograms, for more information on subprogram nesting.A data item defined with the
EXTERNAL(see EXTERNAL) attribute in a subprogram and the calling program (same name in both programs) is automatically visible to and updatable by both programs, even if those programs are compiled separately from one another.
PROCEDURE DIVISION Sections and Paragraphs
The procedure division is the only one of the COBOL divisions that allows you to create your own sections and paragraphs. These are collectively referred to as Procedures, and the names you create for those sections and paragraphs are called Procedure Names.
Procedure names are optional in the procedure division and — when used — are named entirely according to the needs and whims of the programmer.
Procedure names may be up to thirty one (31) characters long and may consist of letters, numbers, dashes and underscores. A procedure name may neither begin nor end with a dash (‘-’) or underscore (‘_’) character. This means that Main, 0100-Read-Transaction and 17 are all perfectly valid procedure names.
There are three circumstances under which the use of certain GnuCOBOL statements or options will require the specification of procedures. These situations are:
When
DECLARATIVES(see DECLARATIVES) are specified.When the
ENTRYstatement (see ENTRY) is being used.When any procedure division statement that references procedures is used. These statements are:
ALTER procedure-nameGO TO procedure-nameMERGE … OUTPUT PROCEDURE procedure-namePERFORM procedure-nameSORT … INPUT PROCEDURE procedure-nameand/orSORT … OUTPUT PROCEDURE procedure-name
DECLARATIVES
DECLARATIVES Syntax
=======================================================================
[ DECLARATIVES.
~~~~~~~~~~~~
{ section-name-1 SECTION.
~~~~~~~
USE statement.
~~~
[ sentence-1 ]...
[ paragraph-name-1. [ sentence-2 ]... ]... }...
END DECLARATIVES. ]
~~~ ~~~~~~~~~~~~
Where the USE statement can be one of 4 following formats:
1.FILE EXCEPTIONS procedures,
2.DEBUGGING procedures,
3.REPORTING procedures to be executed before the printing of the designated
Report Group,
4.EXCEPTION CONDITIONS procedures to be executed after detection of exception
conditions.
USE { [ GLOBAL ] AFTER STANDARD { EXCEPTION } PROCEDURE ON { INPUT } }
~~~ { ~~~~~~ { ~~~~~~~~~ } { ~~~~~ } }
{ { ERROR } { OUTPUT } }
{ ~~~~~ { ~~~~~~ } }
{ { I-O } }
{ { ~~~ } }
{ { EXTEND } }
{ { ~~~~~~ } }
{ { {file-name-1 }...} }
{ }
{ }
{ FOR DEBUGGING ON { procedure-name-1 } }
{ ~~~~~~~~~ { ALL PROCEDURES } }
{ { ~~~ ~~~~~~~~~~ } }
{ { REFERENCES OF identifier-1 } }
{ }
{ [ GLOBAL ] BEFORE REPORTING identifier-2 }
{ ~~~~~~ ~~~~~~ ~~~~~~~~~ }
{ }
{ AFTER {EC|EXCEPTION CONDITION} {exception-name-1 } }
{ ~~ ~~~~~~~~~ ~~~~~~~~~ {exception-name-2 {FILE file-name-2}...} } }
~~~~
The AFTER EXCEPTION CONDITION and AFTER EC clauses are syntactically recognized but are otherwise non-functional.
=======================================================================
The DECLARATIVES area of the procedure division allows the programmer to define a series of “trap” procedures (referred to as declarative procedures) capable of intercepting certain events that may occur at program execution time. The syntax diagram above shows the format of a single such procedure.
The reserved words
AFTER,FOR,ON,PROCEDUREandSTANDARDare optional and may be omitted. The presence or absence of these words has no effect upon the program.ECandEXCEPTION CONDITIONare interchangeable.The declaratives area may contain any number of declarative procedures, but no two declarative procedures should be coded to trap the same event.
The following points apply to the
USE BEFORE REPORTINGclause:<identifier-2> must be a report group.
At run-time, the declaratives procedure will be executed prior to the processing of the specified report group’s presentation; within the procedure you may take either of the following actions:
You may adjust the value(s) of any items referenced in
SUM(see SUM) orSOURCE(see SOURCE) clauses in the report group.You may execute the
SUPPRESS(see SUPPRESS) statement to squelch the presentation of the specified report group altogether. Note that you will be suppressing this one specific instance of that group’s presentation and not all of them.
The following points apply to the
USE FOR DEBUGGINGclause:This clause allows you to define a declarative procedure that will be invoked whenever…
…<identifier-1> is referenced on any statement.
…<procedure-name-1> is executed.
…any procedure is executed (
ALL PROCEDURES).
A
USE FOR DEBUGGINGdeclarative procedure will be ignored at compilation time unlessWITH DEBUGGING MODEis specified in theSOURCE-COMPUTER(see SOURCE-COMPUTER) paragraph. Neither the compiler’s-fdebugging-lineswitch nor-debugswitch will activate this feature.Any
USE FOR DEBUGGINGdeclarative procedures will be ignored at execution time unless theCOB_SET_DEBUGrun-time environment variable (see Run Time Environment Variables) has been set to a value of ‘Y’, ‘y’ or ‘1’.The typical use of a
USE FOR DEBUGGINGdeclarative procedure is to display theDEBUG-ITEMspecial register, which will be implicitly and automatically created in your program for you ifWITH DEBUGGING MODEis active.The structure of
DEBUG-ITEMwill be as follows:01 DEBUG-ITEM. 05 DEBUG-LINE PIC X(6). 05 FILLER PIC X(1) VALUE SPACE. 05 DEBUG-NAME PIC X(31). 05 FILLER PIC X(1) VALUE SPACE. 05 DEBUG-SUB-1 PIC S9(4) SIGN LEADING SEPARATE. 05 FILLER PIC X(1) VALUE SPACE. 05 DEBUG-SUB-2 PIC S9(4) SIGN LEADING SEPARATE. 05 FILLER PIC X(1) VALUE SPACE. 05 DEBUG-SUB-3 PIC S9(4) SIGN LEADING SEPARATE. 05 FILLER PIC X(1) VALUE SPACE. 05 DEBUG-CONTENTS PIC X(31).where…
DEBUG-LINE-
… is the program line number of the statement that triggered the declaratives procedure.
DEBUG-NAME-
… is the procedure name or identifier name that triggered the declaratives procedure.
DEBUG-SUB-1-
… is the first subscript value (if any) for the reference of the identifier that triggered the declaratives procedure.
DEBUG-SUB-2-
… is the second subscript value (if any) for the reference of the identifier that triggered the declaratives procedure.
DEBUG-SUB-3-
… is the third subscript value (if any) for the reference of the identifier that triggered the declaratives procedure.
DEBUG-CONTENTS-
… is a (brief) statement of the manner in which the procedure that triggered the declaratives procedure was executed or the first 31 characters of the value of the identifier whose reference triggered the declaratives procedure (the value after the statement was executed).
The
USE AFTER STANDARD ERROR PROCEDUREclause defines a declarative procedure invoked any time a failure is encountered with the specified I/O type (or against the specified file(s)).The
GLOBAL(see GLOBAL) option, if used, allows a declarative procedure to be used across the program containing theUSEstatement and any subprograms nested within that program.Declarative procedures may not reference any other procedures defined outside the scope of DECLARATIVES.
Common Clauses on Executable Statements
AT END + NOT AT END
AT END Syntax
=======================================================================
[ AT END imperative-statement-1 ]
~~~
[ NOT AT END imperative-statement-2 ]
~~~ ~~~
=======================================================================
AT END clauses may be specified on READ (see READ), RETURN (see RETURN), SEARCH (see SEARCH) statements (Serial Search and Binary Search).
The following points pertain to the use of these clauses on
READ(see READ) andRETURN(see RETURN) statements:The
AT ENDclause will — if present — cause <imperative-statement-1> (see Imperative Statement) to be executed if the statement fails due to a file status of 10 (end-of-file). See File Status Codes, for a list of possible File Status codes.An
AT ENDclause will not detect other non-zero file-status values.Use a
DECLARATIVES(see DECLARATIVES) routine or an explicitly-declared file status field tested after theREADorRETURNto detect error conditions other than end-of-file.A
NOT AT ENDclause will cause <imperative-statement-2> to be executed if theREADorRETURNattempt is successful.
The following points pertain to the use of these clauses on
SEARCH(see SEARCH) statements (Serial Search and Binary Search):An
AT ENDclause detects and handles the case where either form of table search has failed to locate an entry that satisfies the search conditions being used.The
NOT AT ENDclause is not allowed on either form of table search.
CORRESPONDING
Three GnuCOBOL statements — ADD (see ADD CORRESPONDING), MOVE (see MOVE CORRESPONDING) and SUBTRACT (see SUBTRACT CORRESPONDING) support the use of a CORRESPONDING option:
ADD CORRESPONDING group-item-1 TO group-item-2
MOVE CORRESPONDING group-item-1 TO group-item-2
SUBTRACT CORRESPONDING group-item-1 FROM group-item-2
This option allows one or more data items within one group item (<group-item-1> — the first named on the statement) to be paired with correspondingly-named (hence the name) in a second group item (<group-item-2> — the second named on the statement). The contents of <group-item-1> will remain unaffected by the statement while one or more data items within <group-item-2> will be changed.
In order for <data-item-1>, defined subordinate to group item <group-item-1> to be a corresponding match to <data-item-2> which is subordinate to <group-item-2>, each of the following must be true:
Both <data-item-1> and <data-item-2> must have the same name, and that name may not explicitly or implicitly be
FILLER.Both <data-item-1> and <data-item-2>…
…must exist at the same relative structural “depth” of definition within <group-item-1> and <group-item-2>, respectively
…and all “parent” data items defined within each group item must have identical (but non-
FILLER) names.
When used with a
MOVEverb……one of <data-item-1> or <data-item-2> (but not both) is allowed to be a group item
…and it must be valid to move <data-item-1> TO <data-item-2>.
When used with
ADDorSUBTRACTverbs, both <data-item-1> and <data-item-2> must be numeric, elementary, unedited items.Neither <data-item-1> nor <data-item-2> may be a
REDEFINES(see REDEFINES) orRENAMES(see RENAMES) of another data item.Neither <data-item-1> nor <data-item-2> may have an
OCCURS(see OCCURS) clause, although either may contain subordinate data items that do have anOCCURSclause (assuming rule 3a applies)
Observe the definitions of data items ‘Q’ and ‘Y’…
01 Q. 01 Y.
03 X. 02 A PIC X(1).
05 A PIC 9(1). 02 G1.
05 G1. 03 G2.
10 G2. 04 B PIC X(1).
15 B PIC X(1). 02 C PIC X(1).
05 C. 02 G3.
10 FILLER PIC X(1). 03 G5.
05 G3. 04 D PIC X(1).
10 G4. 03 G6 PIC X(1).
15 D PIC X(1). 02 E PIC 9(1).
05 E PIC X(1). 02 F PIC X(1).
05 F REDEFINES V1 02 G PIC X(4).
PIC X(1). 02 H OCCURS 4 TIMES
05 G. PIC X(1).
10 G6 OCCURS 4 TIMES 66 I RENAMES E.
PIC X(1). 02 J.
05 H PIC X(4). 03 K.
05 I PIC 9(1). 04 L.
05 J. 05 M.
10 K.
15 M PIC X(1).
The following are the valid CORRESPONDING matches, assuming the statement MOVE CORRESPONDING X TO Y is being executed (there are no valid corresponding matches for ADD CORRESPONDING or SUBTRACT CORRESPONDING because every potential match up violates rule #4):
A, B, C, G
The following are the CORRESPONDING match ups that passed rule #1 (but failed on another rule), and the reasons why they failed.
| Data Item | Failure Reason |
|---|---|
D |
Fails due to rule #2b |
E |
Fails due to rule #3b |
F |
Fails due to rule #5 |
G1 |
Fails due to rule #3a |
G2 |
Fails due to rule #3a |
G3 |
Fails due to rule #3a |
G4 |
Fails due to rule #1 |
G5 |
Fails due to rule #1 |
G6 |
Fails due to rule #6 |
H |
Fails due to rule #6 |
I |
Fails due to rule #5 |
J |
Fails due to rule #3a |
K |
Fails due to rule #3a |
L |
Fails due to rule #1 |
M |
Fails due to rule #2a |
INVALID KEY + NOT INVALID KEY
INVALID KEY Syntax
=======================================================================
[ INVALID KEY imperative-statement-1 ]
~~~~~~~
[ NOT INVALID KEY imperative-statement-2 ]
~~~ ~~~~~~~
=======================================================================
INVALID KEY clauses may be specified on DELETE (see DELETE), READ (see Random READ), REWRITE (see REWRITE), START (see START) and WRITE (see WRITE) statements.
Specification of an INVALID KEY clause will allow your program to trap an I/O failure condition (with an I/O error code in the file’s FILE-STATUS (see SELECT) field) that has occurred due to a record-not-found condition and handle it gracefully by executing <imperative-statement-1> (see Imperative Statement).
An optional NOT INVALID KEY clause will cause <imperative-statement-2> to be executed if the statement’s execution was successful.
ON EXCEPTION + NOT ON EXCEPTION
ON EXCEPTION Syntax
=======================================================================
[ ON EXCEPTION imperative-statement-1 ]
~~~~~~~~~
[ NOT ON EXCEPTION imperative-statement-2 ]
~~~ ~~~~~~~~~
=======================================================================
EXCEPTION clauses may be specified on ACCEPT (see ACCEPT), CALL (see CALL) and DISPLAY (see DISPLAY) statements.
Specification of an exception clause will allow your program to trap a failure condition that has occurred and handle it gracefully by executing <imperative-statement-1> (see Imperative Statement). If such a condition occurs at runtime without having one of these clauses specified, an error message will be generated (by the GnuCOBOL runtime library) to the SYSERR device (pipe 2). The program may also be terminated, depending upon the type and severity of the error.
An optional NOT ON EXCEPTION clause will cause <imperative-statement-2> to be executed if the statement’s execution was successful.
ON OVERFLOW + NOT ON OVERFLOW
ON OVERFLOW Syntax
=======================================================================
[ ON OVERFLOW imperative-statement-1 ]
~~~~~~~~
[ NOT ON OVERFLOW imperative-statement-2 ]
~~~ ~~~~~~~~
=======================================================================
OVERFLOW clauses may be specified on CALL (see CALL), STRING (see STRING) and UNSTRING (see UNSTRING) statements.
An ON OVERFLOW clause will allow your program to trap a failure condition that has occurred and handle it gracefully by executing <imperative-statement-1> (see Imperative Statement). If such a condition occurs at runtime without having one of these clauses specified, an error message will be generated (by the GnuCOBOL runtime library) to the SYSERR device (pipe 2). The program may also be terminated, depending upon the type and severity of the error.
An optional NOT ON OVERFLOW clause will cause <imperative-statement-2> to be executed if the statement’s execution was successful.
ON SIZE ERROR + NOT ON SIZE ERROR
ON SIZE ERROR Syntax
=======================================================================
[ ON SIZE ERROR imperative-statement-1 ]
~~~~ ~~~~~
[ NOT ON SIZE ERROR imperative-statement-2 ]
~~~ ~~~~ ~~~~~
=======================================================================
SIZE ERROR clauses may be included on ADD (see ADD), COMPUTE (see COMPUTE), DIVIDE (see DIVIDE), MULTIPLY (see MULTIPLY) and SUBTRACT (see SUBTRACT) statements.
Including an ON SIZE ERROR clause on an arithmetic statement will allow your program to trap a failure of an arithmetic statement (either generating a result too large for the receiving field, or attempting to divide by zero) and handle it gracefully by executing <imperative-statement-1> (see Imperative Statement). Field size overflow conditions occur silently, usually without any runtime messages being generated, even though such events rarely lend themselves to generating correct results. Division by zero errors, when no ON SIZE ERROR clause exists, will produce an error message (by the GnuCOBOL runtime library) to the SYSERR device (pipe 2) and will also abort the program.
An optional NOT ON SIZE ERROR clause will cause <imperative-statement-2> to be executed if the arithmetic statement’s execution was successful.
ROUNDED
ROUNDED Syntax
=======================================================================
ROUNDED [ MODE IS { AWAY-FROM-ZERO } ]
~~~~~~~ ~~~~ { ~~~~~~~~~~~~~~ }
{ NEAREST-AWAY-FROM-ZERO }
{ ~~~~~~~~~~~~~~~~~~~~~~ }
{ NEAREST-EVEN }
{ ~~~~~~~~~~~~ }
{ NEAREST-TOWARD-ZERO }
{ ~~~~~~~~~~~~~~~~~~~ }
{ PROHIBITED }
{ ~~~~~~~~~~ }
{ TOWARD-GREATER }
{ ~~~~~~~~~~~~~~ }
{ TOWARD-LESSER }
{ ~~~~~~~~~~~~~ }
{ TRUNCATION }
~~~~~~~~~~
=======================================================================
GnuCOBOL provides for control over the final rounding process applied to the receiving fields on all arithmetic verbs. Each of the arithmetic statements (ADD (see ADD), COMPUTE (see COMPUTE), DIVIDE (see DIVIDE), MULTIPLY (see MULTIPLY) and SUBTRACT (see SUBTRACT)) statements allow an optional ROUNDED clause to be applied to each receiving data item.
The following rules apply to the rounding behaviour induced by this clause.
Rounding only applies when the result being saved to a receiving field with a
ROUNDEDclause is a non-integer value.Absence of a
ROUNDEDclause is the same as specifyingROUNDED MODE IS TRUNCATION.Use of a
ROUNDEDclause without aMODEspecification is the same as specifyingROUNDED MODE IS NEAREST-AWAY-FROM-ZERO.
The behaviour of the eight different rounding modes is defined in the following table. Note that a ‘…’ indicates the last digit repeats. The examples assume an integer receiving field.
AWAY-FROM-ZERO-
Rounding is to the nearest value of larger magnitude.
-3.510 ⇒ -4 +3.510 ⇒ +4 -3.500 ⇒ -4 +3.500 ⇒ +4 -3.499… ⇒ -4 +3.499… ⇒ +4 -2.500 ⇒ -3 +2.500 ⇒ +3 -2.499… ⇒ -3 +2.499… ⇒ +3 NEAREST-AWAY-FROM-ZERO-
Rounding is to the nearest value (larger or smaller). If two values are equally near, the value with the larger absolute value is selected.
-3.510 ⇒ -4 +3.510 ⇒ +4 -3.500 ⇒ -4 +3.500 ⇒ +4 -3.499… ⇒ -3 +3.499… ⇒ +3 -2.500 ⇒ -3 +2.500 ⇒ +3 -2.499… ⇒ -2 +2.499… ⇒ +2 NEAREST-EVEN-
Rounding is to the nearest value (larger or smaller). If two values are equally near, the value whose rightmost digit is even is selected. This mode is sometimes called “Banker’s rounding”.
-3.510 ⇒ -4 +3.510 ⇒ +4 -3.500 ⇒ -4 +3.500 ⇒ +4 -3.499… ⇒ -3 +3.499… ⇒ +3 -2.500 ⇒ -2 +2.500 ⇒ +2 -2.499… ⇒ -2 +2.499… ⇒ +2 NEAREST-TOWARD-ZERO-
Rounding is to the nearest value (larger or smaller). If two values are equally near, the value with the smaller absolute value is selected.
-3.510 ⇒ -4 +3.510 ⇒ +4 -3.500 ⇒ -3 +3.500 ⇒ +3 -3.499… ⇒ -3 +3.499… ⇒ +3 -2.500 ⇒ -2 +2.500 ⇒ +2 -2.499… ⇒ -2 +2.499… ⇒ +2 PROHIBITED-
No rounding is performed. If the value cannot be represented exactly in the desired format, the
EC-SIZE-TRUNCATIONcondition (exception code 1005) is set (and may be retrieved via theACCEPT(see ACCEPT FROM Runtime-Info) statement) and the results of the operation are undefined.-3.510 ⇒ Undefined +3.510 ⇒ Undefined -3.500 ⇒ Undefined +3.500 ⇒ Undefined -3.499… ⇒ Undefined +3.499… ⇒ Undefined -2.500 ⇒ Undefined +2.500 ⇒ Undefined -2.499… ⇒ Undefined +2.499… ⇒ Undefined TOWARD-GREATER-
Rounding is toward the nearest value whose algebraic value is larger.
-3.510 ⇒ -3 +3.510 ⇒ +4 -3.500 ⇒ -3 +3.500 ⇒ +4 -3.499… ⇒ -3 +3.499… ⇒ +4 -2.500 ⇒ -2 +2.500 ⇒ +3 -2.499… ⇒ -2 +2.499… ⇒ +3 TOWARD-LESSER-
Rounding is toward the nearest value whose algebraic value is smaller.
-3.510 ⇒ -4 +3.510 ⇒ +3 -3.500 ⇒ -4 +3.500 ⇒ +3 -3.499… ⇒ -4 +3.499… ⇒ +3 -2.500 ⇒ -3 +2.500 ⇒ +2 -2.499… ⇒ -3 +2.499… ⇒ +2 TRUNCATION-
Rounding is to the nearest value whose magnitude is smaller.
-3.510 ⇒ -3 +3.510 ⇒ +3 -3.500 ⇒ -3 +3.500 ⇒ +3 -3.499… ⇒ -3 +3.499… ⇒ +3 -2.500 ⇒ -2 +2.500 ⇒ +2 -2.499… ⇒ -2 +2.499… ⇒ +2
Special Registers
GnuCOBOL, like other COBOL dialects, includes a number of data items that are automatically available to a programmer without the need to actually define them in the data division. COBOL refers to such items as registers or special registers. The special registers available to a GnuCOBOL program are as follows:
COB-CRT-STATUS-
PIC 9(4) — This is the default data item allocated for use by the
ACCEPT data-itemstatement (see ACCEPT data-item), if noCRT STATUS(see SPECIAL-NAMES) clause was specified.. DEBUG-ITEM-
Group Item — A group item in which debugging information generated by a
USE FOR DEBUGGINGsection in the declaratives area of the procedure division will place information documenting why theUSE FOR DEBUGGINGprocedure was invoked. Consult theDECLARATIVES(see DECLARATIVES) documentation for information on the structure of this register. LINAGE-COUNTER-
BINARY-LONG SIGNED— An occurrence of this register exists for each selected file having aLINAGE(see File/Sort-Description) clause. If there are multiple files whose file descriptions haveLINAGEclauses, any explicit references to this register will require qualification (usingOF file-name). The value of this register will be the current logical line number within the page body. The value of this register cannot be modified. LINE-COUNTER-
BINARY-LONG SIGNED— An occurrence of this register exists for each report defined in the program (via anRD(see REPORT SECTION)). If there are multiple reports, any explicit references to this register not made in the report section will require qualification (OF report-name). The value of this register will be the current logical line number on the current page. The value of this register cannot be modified. NUMBER-OF-CALL-PARAMETERS-
BINARY-LONG SIGNED— This register contains the number of arguments passed to a subroutine — the same value that would be returned by theC$NARGbuilt-in system subroutine (see C$NARG). Its value will be zero when referenced in a main program. This register, when referenced from within a user-defined function, returns a value of one (‘1’) if the function has any number of arguments and a zero if it has no arguments. PAGE-COUNTER-
BINARY-LONG SIGNED— An occurrence of this register exists for each report having anRD(see REPORT SECTION). If there are multiple such reports, any explicit references to this register not made in the report section will require qualification (OF report-name). The value of this register will be the current report page number. The value of this register cannot be modified. RETURN-CODE-
BINARY-LONG SIGNED— This register provides a numeric data item into which a subroutine mayMOVE(see MOVE) a value (which will then be available to the calling program) prior to transferring control back to the program that called it, or into which a main program mayMOVEa value before returning control to the operating system. Many built-in subroutines will return a value using this register. These values are — by convention — used to signify success (usually with a value of 0) or failure (usually with a non-zero value) of the process the program was attempting to perform. This register may also be modified by a subprogram as a result of that subprogram’s use of theRETURNING(see PROCEDURE DIVISION RETURNING) clause. SORT-RETURN-
BINARY-LONG SIGNED— This register is used to report the success/fail status of aRELEASE(see RELEASE) orRETURN(see RETURN) statement. A value of 0 is reported on success. A value of 16 denotes failure. AnAT END(see AT END + NOT AT END) condition on aRETURNis not considered a failure. WHEN-COMPILED-
PIC X(16)— This register contains the date and time the program was compiled in the format ‘mm/dd/yyhh.mm.ss’. Note that only a two-digit year is provided.
LENGTH OF Syntax
=======================================================================
LENGTH OF numeric-literal-1 | identifier-1
~~~~~~
=======================================================================
Alphanumeric literals and identifiers may optionally be prefixed with the LENGTH OF clause. The compile-time value generated by this clause will be the number of bytes in the alphanumeric literal or the defined size (in bytes) of the identifier.
The reserved word
OFis optional and may be omitted. The presence or absence of this word has no effect upon the program. Here is an example. The following two GnuCOBOL statements both display the same result (27):01 Demo-Identifier PIC X(27). ... DISPLAY LENGTH OF "This is a LENGTH OF Example" DISPLAY LENGTH OF Demo-IdentifierThe
LENGTH OFclause on a literal or identifier reference may generally be used anywhere a numeric literal might be specified, with the following exceptions:
GnuCOBOL Statements
ACCEPT
ACCEPT FROM CONSOLE
ACCEPT FROM CONSOLE Syntax
=======================================================================
ACCEPT identifier-1 [ FROM mnemonic-name-1 ] [ END-ACCEPT ]
~~~~~~ ~~~~ ~~~~~~~~~~
=======================================================================
This format of the ACCEPT statement is used to read a value from the console window or the standard input device and store it into a data item (<identifier-1>).
If no
FROMclause is specified,FROM CONSOLEis assumed.The specified <mnemonic-name-1> must either be one of the built-in device names
CONSOLE,STDIN,SYSINorSYSIPT, or a user-defined (see SPECIAL-NAMES) mnemonic name attached to one of those four device names.Input will be read either from the console window (
CONSOLE) or from the system-standard input (pipe 0 =STDIN,SYSINorSYSIPT) and will be saved in <identifier-1>.If <identifier-1> is a numeric data item, the character value read from the console or standard-input device will be parsed according to the rules for input to the
NUMVALintrinsic function (see NUMVAL), except that none of the trailing sign formats are honoured.
ACCEPT FROM COMMAND-LINE
ACCEPT FROM COMMAND-LINE Syntax
=======================================================================
ACCEPT identifier-1
~~~~~~
FROM { COMMAND-LINE }
~~~~ { ~~~~~~~~~~~~ }
{ ARGUMENT-NUMBER }
{ ~~~~~~~~~~~~~~~ }
{ ARGUMENT-VALUE [ ON EXCEPTION|ESCAPE imperative-statement-1 ] }
{ ~~~~~~~~~~~~~~ ~~~~~~~~~ ~~~~~~ }
{ [ NOT ON EXCEPTION|ESCAPE imperative-statement-2 ] }
~~~ ~~~~~~~~~ ~~~~~~
[ END-ACCEPT ]
~~~~~~~~~~
=======================================================================
This format of the ACCEPT statement is used to retrieve information from the program’s command line.
The reserved word
ONis optional and may be omitted. The presence or absence of this word has no effect upon the program.When you accept from the
COMMAND-LINEoption, you will retrieve the entire set of arguments entered on the command line that executed the program, exactly as they were specified. Parsing that returned data into its meaningful information will be your responsibility.Using
COMMAND-LINEorARGUMENT-VALUEin a *nix based platform and that includes Linux, OSX, BSD and under windows running msys or MinGW etc, the shell process will expand any arguments that have a ‘*’ in the list — such as ‘a*’, ‘abc*.*’, etc. — and create a list of all files that match the pattern. To avoid this if not wanted, put all such argument within quotes, e.g.,progundertest "a*" b c d "ef*" "*hg"and the text within quotes will be passed verbatim to the program (as in the exampleprogundertest).By accepting from
ARGUMENT-NUMBER, you will be asking the GnuCOBOL run-time system to parse the arguments from the command line and return the number of arguments found. Parsing will be conducted according to the following rules:Arguments will be separated by treating spaces and/or tab characters as the delimiters between arguments. The number of such delimiters separating two non-blank argument values is irrelevant.
Strings enclosed in double-quote characters (‘
"’) will be treated as a single argument, regardless of how many spaces or tab characters (if any) might be embedded within the quotation characters.On Windows systems, single-quote, or apostrophe, characters (‘
'’) will be treated just like any other data character and will not delineate argument strings.
By accepting from
ARGUMENT-VALUE, you will be asking the GnuCOBOL run-time system to parse the arguments from the command line and return the “current” argument. You specify which argument number is “current” via theARGUMENT-NUMBERoption on theDISPLAYstatement (see DISPLAY UPON COMMAND-LINE). Parsing of arguments will be conducted according to the rules set forth above.The optional
ON EXCEPTIONandNOT ON EXCEPTIONclauses may be used to detect and react to the failure or success, respectively, of an attempt to retrieve anARGUMENT-VALUE. See ON EXCEPTION + NOT ON EXCEPTION, for additional information.Program Example: >>SOURCE FREE identification division. program-id. TESTACCEPTARG. data division. working-storage section. 01 wACC-CMD PIC X(30) value ALL 'x'. 01 wACCNR PIC 9(03) value zero. 01 wACC01 PIC X(10) value ALL 'x'. 01 wACC02 PIC X(10) value ALL 'x'. 01 wACC03 PIC X(10) value ALL 'x'. 01 wACC04 PIC X(10) value ALL 'x'. 01 wACC05 PIC X(10) value ALL 'x'. 01 wACCxx PIC X(10) value ALL 'x'. procedure division. accept wACC-CMD from command-line. display 'Command line: >' wACC-CMD '<'. accept wACCNR from argument-number. if wACCNR = 4 accept wACC01 from argument-value accept wACC02 from argument-value accept wACC03 from argument-value accept wACC04 from argument-value accept wACC05 from argument-value on escape display 'Accept Argument 5 does not exist' not on escape display 'Accept Argument 5 no exception' end-accept display wACCNR '-' wACC01'-' wACC02 '-' wACC03 '-' wACC04 '-' wACC05 display 2 upon argument-number on exception display 'Display Argument 2 does not exist' not on exception display 'Display Argument 2 no exception' end-display accept wACCxx from argument-value display 'Arg 2= ' waccxx display 5 upon argument-number on exception display 'Display Argument 5 does not exist' not on exception display 'Display Argument 5 no exception' end-display move zero to wACCNR accept wACCNR from argument-number display 'Arguments: ' wACCNR end-display accept wACCxx from argument-value *> read the next argument on escape display 'Argument does not exist' not on escape display 'Argument no exception' end-accept display 'Next arg= ' wACCxx else display '4 arguments are required. Arguments are: ' wACCNR end-if STOP RUN. Execute as follows: testacceptarg 1 2 3 4 The result will be: Command line: >1 2 3 4 < Accept Argument 5 does not exist 004-1 -2 -3 -4 -xxxxxxxxxx Display Argument 2 no exception Arg 2= 2 Display Argument 5 does not exist Arguments: 004 Argument no exception Next arg= 3Argument-number assigned to 0 gives the actual OS command used to start the process from argument-value. Function module-id instead gives the internal program-id. In the following case TESTACCEPTARG2.COB is the source filename. program-id is actually "SAMPLE3" in the code.
>>SOURCE FREE identification division. program-id. SAMPLE3. data division. working-storage section. 01 wProgname pic x(32). procedure division. display 0 upon argument-number accept wProgname from argument-value display "argument-value zero >" wProgname "<" display "function module-id >" function module-id "<" accept omitted goback. end program SAMPLE3. The result will be: argument-value zero >C:\yourfolder\TESTACCEPTARG2.exe < function module-id >SAMPLE3<
ACCEPT FROM ENVIRONMENT
ACCEPT FROM ENVIRONMENT Syntax
=======================================================================
ACCEPT identifier-1 FROM { ENVIRONMENT { literal-1 } }
~~~~~~ ~~~~ { ~~~~~~~~~~~ { identifier-1 } }
{ }
{ ENVIRONMENT-VALUE }
~~~~~~~~~~~~~~~~~
[ ON EXCEPTION|ESCAPE imperative-statement-1 ]
~~~~~~~~~ ~~~~~~
[ NOT ON EXCEPTION|ESCAPE imperative-statement-2 ]
~~~ ~~~~~~~~~ ~~~~~~
[ END-ACCEPT ]
~~~~~~~~~~
=======================================================================
This format of the ACCEPT statement is used to retrieve environment variable values.
The reserved word
ONis optional and may be omitted. The presence or absence of this word has no effect upon the program.By accepting from
ENVIRONMENT-VALUE, you will be asking the GnuCOBOL run-time system to retrieve the value of the environment variable whose name is currently in theENVIRONMENT-NAMEregister. A value may be placed into theENVIRONMENT-NAMEregister using theENVIRONMENT-NAMEoption of theDISPLAYstatement (see DISPLAY UPON ENVIRONMENT).A simpler approach to retrieving an environment variables value is to use the
ENVIRONMENToption, where you specify the environment variable whose value is to be retrieved right on theACCEPTstatement itself.With the option ACCEPT "var" FROM ENVIRONMENT runtime-config-option you can receive the value set in one of the runtime-configuration-options listed in chapter 10.2.3 Run Time Environment Variables. As an example: ACCEPT identifier-1 FROM ENVIRONMENT ‘COB_INSERT_MODE’ returns whether insert mode is active ( = ‘true’ or 1 ) or inactive ( = ‘false’ or 0 ).
The optional
ON EXCEPTIONandNOT ON EXCEPTIONclauses may be used to detect and react to an attempt to retrieve the value of a non-existent environment variable or the successful retrieval of an environment variable’s value, respectively. See ON EXCEPTION + NOT ON EXCEPTION, for additional information.
ACCEPT data-item
ACCEPT data-item Syntax
=======================================================================
ACCEPT { identifier-1 } [ FROM CRT ] [ MODE IS BLOCK ]
~~~~~~ { OMITTED } ~~~~ ~~~ ~~~~ ~~~~~
~~~~~~~
[ { | AT LINE NUMBER { integer-1 } | } ]
[ { | ~~~~ { identifier-2 } | } ]
[ { | { arithmetic-expression-1 } | } ]
[ { | | } ]
[ { | AT COLUMN|POSITION NUMBER { integer-2 } | } ]
[ { | ~~~ ~~~ { identifier-3 } | } ]
[ { | { arithmetic-expression-2 } | } ]
[ { } ]
[ { AT { integer-3 } } ]
[ { ~~ { identifier-4 } } ]
[ WITH AUTO|AUTO-SKIP|AUTOTERMINATE|TAB ]
~~~~ ~~~~~~~~~ ~~~~~~~~~~~~~ ~~~
[ WITH [ NO ] BELL|BEEP ]
~~ ~~~~ ~~~~
[ WITH PROMPT [ CHARACTER IS literal-2|identifier-5 ] ]
~~~~~~ ~~~~~~~~~
[ WITH BACKGROUND-COLOR|BACKGROUND-COLOUR IS integer-4|identifier-6 ]
~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~
[ WITH FOREGROUND-COLOR|FOREGROUND-COLOUR IS integer-5|identifier-7 ]
~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~
[ WITH HIGHLIGHT|LOWLIGHT ]
~~~~~~~~~ ~~~~~~~~
[ WITH BLINK ]
~~~~~
[ WITH REVERSE-VIDEO|REVERSE|REVERSED ]
~~~~~~~~~~~~~ ~~~~~~~ ~~~~~~~~
[ WITH LEFTLINE ]
~~~~~~~~
[ WITH OVERLINE ]
~~~~~~~~
[ WITH UNDERLINE ]
~~~~~~~~~
[ WITH REQUIRED|EMPTY-CHECK ]
~~~~~~~~ ~~~~~~~~~~~
[ WITH FULL|LENGTH-CHECK ]
~~~~ ~~~~~~~~~~~~
[ WITH NO ECHO|NO-ECHO|OFF|SECURE ]
~~~~~~~ ~~~~~~~ ~~~ ~~~~~~
[ WITH LOWER|UPPER ]
~~~~~ ~~~~~
[ WITH SCROLL [ UP ] [ { integer-6 } LINE|LINES ] ]
[ ~~~~~~ [ ~~ ] [ { identifier-8 } ~~~~ ~~~~~ ] ]
[ [ DOWN ] ]
~~~~
[ { WITH TIMEOUT|TIME-OUT AFTER } { integer-7 } ]
[ { ~~~~~~~ ~~~~~~~~ } { identifier-9 } ]
[ { BEFORE TIME } ]
~~~~
[ WITH [ NO ] UPDATE|DEFAULT ]
~~ ~~~~~~ ~~~~~~~
[ WITH CONVERSION ]
~~~~~~~~~~
[ WITH CURSOR identifier-10 ]
~~~~~~
[ WITH PROTECTED SIZE IS { integer-8 } ]
[ ~~~~ { identifier-11 } ]
[ WITH CONTROL { literal-8 } ]
[ ~~~~~~~ { identifier-12 } ]
[ WITH COLOUR|COLOR IS { integer-9 } ]
[ ~~~~~~ ~~~~~ { identifier-13 } ]
[ ON EXCEPTION|ESCAPE imperative-statement-1 ]
~~~~~~~~~ ~~~~~~
[ NOT ON EXCEPTION|ESCAPE imperative-statement-2 ]
~~~ ~~~~~~~~~ ~~~~~~
[ END-ACCEPT ]
~~~~~~~~~~
The FROM CRT, MODE IS BLOCK and CONVERSION clauses are syntactically recognized but are otherwise non-functional.
=======================================================================
This format of the ACCEPT statement is used to retrieve data from a working storage item or a formatted console window screen.
The reserved words
AFTER,IS,NUMBERandONare optional and may be omitted. The presence or absence of these words has no effect upon the program.The reserved words
COLUMN,COLandPOSITIONare interchangeable.The reserved words
TIMEOUTandTIME-OUTare interchangeable.If <identifier-1> is defined in the
SCREEN SECTION(see SCREEN SECTION), anyAT, <Attribute-Specification>,LOWER,UPPERorSCROLLclauses will be ignored. In these cases, an impliedDISPLAY(see DISPLAY data-item) of <identifier-1> will occur before input is accepted. Coding an explicitDISPLAY identifier-1before anACCEPT identifier-1is redundant and will incur the performance penalty of painting the screen contents twice.The various
ATclauses provide a means of positioning the cursor to a specific spot on the screen before the screen is read. One or the other (but not both) may be used, as follows:The
LINEandCOLUMNclauses provide one mechanism for specifying the line and column position to which the cursor will be positioned before allowing the user to enter data. In the absence of one or the other, a value of 1 will be assumed for the one that is missing. The suggested preference, however, is to explicitly code both.The <integer-3> or <identifier-4> value, if specified, must be a four- or six-digit value with the 1st half of the number indicating the line where the cursor should be positioned and the second half indicating the column. You may code only one of each clause on any
ACCEPT.If you don’t want to explicitly specify the
LINEfor the subsequentACCEPT, you can useLINE 0extension, which gives something like the usualACCEPTbehaviour. Namely,LINE 0positions theACCEPTat the line following the lastACCEPT. The same behavior occurs when the <integer-3> or <identifier-4> value is specified (a four- or six-digit value) as 00nn or 000nnn.If you don’t want to explicitly specify the
COLUMNfor the subsequentACCEPT, you can useCOLUMN 0extension, which gives something like the usualACCEPTbehaviour. Namely,COLUMN 0positions theACCEPTat the column following the lastACCEPT. The same behavior occurs when the <integer-3> or <identifier-4> value is specified (a four- or six-digit value) as nn00 or nnn000.You can also use both
LINE 0andCOLUMN 0extension, which gives something like the usualACCEPTbehaviour. Namely,COLUMN 0positions theACCEPTat the same line but column following the lastACCEPT. The same behavior occurs when the <integer-3> or <identifier-4> value is specified (a four- or six-digit value as 0000 or 000000.
WITHoptions (including the various individual <Attribute-Specifications>) should be coded only once.The following <Attribute-Specification> clauses are allowed on the
ACCEPTstatement; many of those are also allowed forSCREEN SECTIONdata items but not all of them. A particular <Attribute-Specification> may be used only once in anyACCEPT:AUTO(see AUTO)BACKGROUND-COLOR(see BACKGROUND-COLOR)BELL(see BELL)BLINK(see BLINK)FOREGROUND-COLOR(see FOREGROUND-COLOR)FULL(see FULL)HIGHLIGHT(see HIGHLIGHT)LEFTLINE(see LEFTLINE)LOWLIGHT(see LOWLIGHT)OVERLINE(see OVERLINE)PROMPT(see PROMPT)REQUIRED(see REQUIRED)REVERSE-VIDEO(see REVERSE-VIDEO)SECURE(see SECURE)UNDERLINE(see UNDERLINE)
The
BEFORE TIMEoption is functionally the same as theTIMEOUTclause. The value of identifier-1 or literal-1 specifies the length of time before automatically terminating the ACCEPT statement when no data is entered by the user.The
CURSORoffset into the field at ACCEPT termination is returned to the program in identifier-10. Identifier-10, can also be used to indicate, as an offset, where you want the cursor to be positioned when the ACCEPT is executed.The
SCROLLoption will cause the entire contents of the screen to be scrolledUPorDOWNby the specified number of lines before any value is displayed on the screen. It is syntactically allowable to specify aSCROLL UPclause as well as aSCROLL DOWNclause. In such an instance, it is the last one specified that will be honoured. If noLINESspecification is made,1 LINEwill be assumed. These two options cannot be used in Screen Section.The
SIZEspecifies size of Variable to accept from the screen. <identifier-11> or <integer-8> must be numeric.SIZE<greater than zero>If <identifier-11> or <integer-8> is less than the length of <identifier-1> then only the
SIZEnumber of characters accept into the field. <identifier-1> pads with spaces afterSIZEto the end of the field.If <identifier-11> or <integer-8> is greater than <identifier-1>, then the screen pads with spaces after <identifier-1> to the
SIZElength.SIZE ZEROorSIZE<option not specified>The <identifier-1> accepts to its field length.
The
TIMEOUToption will cause theACCEPTto wait no more than the specified number of seconds for input. The wait count may be specified as a positive integer or a numeric data item with a positive value.The
UPDATEoption will display the existing data before allowing user to update it. This allows the user to update the field without having to type it all again. TheDEFAULTclause is synonymous with theUPDATEclause. Without this clause, the ACCEPT field is always blank (NO UPDATE or NO DEFAULT is assumed).This clause will enable the supplied data field to be updated having been displayed on screen prior to data being entered by overwriting, if needed. When this option is not used the input field is cleared prior to input and this is the default but can be changed by the use of compiler steering command -faccept-with-update that can be input when starting the compiler or included in the configuration file e.g., default.conf used when selected by default
-std=default. For more information see cobc - The GnuCOBOL Compiler option switches) and Compiler Configuration Files.The
LOWERclause provides a means of explicitly stating that accepted data will be converted to lower case.The
UPPERclause provides a means of explicitly stating that accepted data will be converted to upper case.This format of the
ACCEPTstatement will be terminated by any of the following events:When the Enter key is pressed.
Expiration of the
TIMEOUTtimer — this will be treated as if the Enter key had been pressed with no data being entered.When a function key (F) is pressed.
The pressing of the PgUp or PgDn keys, if the
COB_SCREEN_EXCEPTIONSrun-time environment variable (see Run Time Environment Variables) is set to any non-blank value.The pressing of the Esc key if both the
COB_SCREEN_ESCrun-time environment variable as well asCOB_SCREEN_EXCEPTIONSrun-time environment variable are set to any non-blank value.The pressing of the Up-arrow, Down-Arrow or PrtSc (Print Screen) keys. These keys are not detectable on Windows systems, however.
The following apply when <identifier-1> is defined in the
SCREEN SECTION:Alphanumeric data entered into <identifier-1> or any screen data item subordinate to it must be consistent with the
PICTURE(see PICTURE) clause of that item. This will be enforced at runtime by theACCEPTstatement.If <identifier-1> or any screen data item subordinate to it are defined as numeric, entered data must be acceptable as
NUMVALintrinsic function (see NUMVAL) input (no decimal points are allowed, however). The value stored into the screen data item will be as if the input were passed to that function.If <identifier-1> or any screen data item subordinate to it are defined as numeric edited, entered data must be acceptable as
NUMVAL-Cintrinsic function (see NUMVAL-C) input (again, no decimal points are allowed). The value stored into the screen data item will be as if the input were passed to that function.
The following apply when <identifier-1> is not defined in the
SCREEN SECTION:Alphanumeric data entered into <identifier-1> should be consistent with the
PICTURE(see PICTURE) clause of that item, although that will not be enforced by theACCEPTstatement. You may useClass Conditions(see Class Conditions) after the data is accepted to enforce the data type.If <identifier-1> is defined as numeric, entered data must be acceptable as
NUMVALintrinsic function (see NUMVAL) input (no decimal points are allowed, however). The value stored into <identifier-1> will be as if the input were passed to that function.If <identifier-1> is defined as numeric edited, entered data must be acceptable as
NUMVAL-Cintrinsic function (see NUMVAL-C) input (again, no decimal points are allowed). The value stored into <identifier-1> will be as if the input were passed to that function.
The optional
ON EXCEPTIONandNOT ON EXCEPTIONclauses may be used to detect and react to the failure or success, respectively, of the screen I/O attempt. See ON EXCEPTION + NOT ON EXCEPTION, for additional information. The ESCAPE sub clause is allowed instead of EXCEPTION as a synonymous, with the same meaning.After this format of the
ACCEPTstatement is executed, the program’sCRT STATUS(see SPECIAL-NAMES) identifier will be populated with one of the following:Code Meaning 0000 ENTER key pressed 1001–1064 F1–F64, respectively, were pressed 2001 PgUp was pressed 2002 PgDn was pressed 2003 Up-Arrow was pressed 2004 Down-Arrow was pressed 2005 Esc was pressed 2006 PrtSc (Print Screen) was pressed 2007 Tab 2008 Back Tab 2009 Key Left 2010 Key Right 2011 Insert Key on accept omitted 2012 Delete Key on accept omitted 2013 Backspace Key on accept omitted 2014 Home Key on accept omitted 2015 End Key on accept omitted 2040- 2095 Exception keys for Mouse Handling 2040 Mouse Move 2041 Left Pressed 2042 Left Released 2043 Left Dbl Click 2044 Mid Pressed 2045 Mid Released 2046 Mid Dbl Click 2047 Right Pressed 2048 Right Released 2049 Right Dbl Click 2050 Shift Move 2051 Shift Left Pressed 2052 Shift Left Released 2053 Shift Left Dbl Click 2054 Shift Mid Pressed 2055 Shift Mid Released 2056- Shift Mid Dbl Click 2057 Shift Right Pressed 2058 Shift Right Released 2059 Shift Right Dbl Click 2060 Ctrl Move 2061 Ctrl Left Pressed 2062 Ctrl Left Released 2063 Ctrl Left Dbl Click 2064 Ctrl Mid Pressed 2065 Ctrl Mid Released 2066 Ctrl Mid Dbl Click 2067 Ctrl Right Pressed 2068 Ctrl Right Released 2069 Ctrl Right Dbl Click 2070 Alt Move 2071 Alt Left Pressed 2072 Alt Left Released 2073- Alt Left Dbl Click 2074 Alt Mid Pressed 2075 Alt Mid Released 2076 Alt Mid Dbl Click 2077 Alt Right Pressed 2078 Alt Right Released 2079 Alt Right Dbl Click 2080 Wheel Up 2081 Wheel Down 2082 Wheel Left 2083 Wheel Right 2084 Shift Wheel Up 2085 Shift Wheel Down 2086 Shift Wheel Left 2087 Shift Wheel Right 2088 Ctrl Wheel Up 2089 Ctrl Wheel Down 2090 Ctrl Wheel Left 2091 Ctrl Wheel Right 2092 Alt Wheel Up 2093 Alt Wheel Down 2094 Alt Wheel Left 2095 Alt Wheel Right Input validation 8000 NO Field 8001 Time Out Other errors 9000 Fatal 9001 Max Field The actual key pressed to generate a function key (F) will depend on the type of terminal device you’re using (PC, Macintosh, VT100, etc.) and what type of enhanced display driver was configured with the version of GnuCOBOL you’re using.
For example, on a GnuCOBOL build for a Windows PC using MinGW and “PDCurses”, F1–F12 are the actual F-keys on the PC keyboard, F–F are entered by shifting the F-keys, F–F are entered by holding Ctrl while pressing an F-key and F–F are entered by holding Alt while pressing an F-key. On the other hand, a GnuCOBOL implementation built for Windows using Cygwin and NCurses treats the PCs F–F keys as the actual F–F, while shifted F-keys will enter F–F0. With Cygwin/NCurses, Ctrl- and Alt-modified F-keys aren’t recognized, nor are Shift-F or Shift-F.
Mouse Key codes are populated only if mouse management has been enabled. To enable mouse it is first necessary to set
COB_MOUSE_FLAGS(either externally via terminal command, or internally viaSET ENVIRONMENTto the applicable ?mouse mask? (specifying which activities you wish the program to detect). Here is an example of setting the mask from a COBOL program:COPY screenio.cpy. 01 mouse-flags PIC 9(4). ... COMPUTE mouse-flags = COB-AUTO-MOUSE-HANDLING + COB-ALLOW-LEFT-DOWN + COB-ALLOW-MIDDLE-DOWN + COB-ALLOW-RIGHT-DOWN SET ENVIRONMENT "COB_MOUSE_FLAGS" TO mouse-flags.Once that has been done, every (extended) ACCEPT, will return a value in COB_CRT_STATUS reflecting mouse activity, when such activity occurs. The applicable values are shown in screenio.cpy under ?Exception keys for mouse handling?. If you define a variable in SPECIAL NAMES as follows:
SPECIAL-NAMES. CURSOR IS data-name. *> where data-name is PIC 9(4) or 9(6).The cursor or mouse position will be returned as well. The position is expressed as row and column (rrcc or rrrccc).
Numeric keypad keys are not recognizable on Windows MinGW/PDCurses builds of GnuCOBOL, regardless of the number lock settings. Windows Cygwin/NCurses builds recognize numeric keypad inputs properly. Although not tested during the preparation of this documentation, I would expect native Windows builds using PDCurses to behave as MinGW builds do and native Unix builds using NCurses to behave as do Cygwin builds.
The optional
EXCEPTION-STATUSclause may be used to detect exceptions from a prior arithmetic verb such as COMPUTE to recover any errors produced. These are recovered using the functionEXCEPTION-STATUS.The use of
CONTROLThe value of literal-8 and identifier-8 in the CONTROL phrase is used to specify a dynamic option list. The value must be a character-string consisting of a series of keywords delimited by commas; Some keywords allow assignment of a value by following the keyword with an equal sign and the value. Blanks are ignored in the character-string. Lowercase letters are treated as uppercase letters within keywords. Keywords specified override corresponding static options specified as phrases for the same identifier-1. Keywords may be specified in any order. Keywords, which specify options that do not apply to the statement, are ignored.The keywords that affect an ACCEPT statement are BEEP, BLINK, ECHO, PROMPT, REVERSE, TAB, UNDERLINE, UPDATE, ERASE, ERASE EOL, ERASE EOS, HIGH, LOW, UPPER, NO BEEP, NO BLINK, NO ECHO, NO PROMPT, NO REVERSE, NO TAB, NO UNDERLINE, NO UPDATE, NO ERASE.
The meanings of these keywords when they appear in the value of the CONTROL phrase operand are the same as the corresponding phrases which may be written as static options of the ACCEPT statement, with the addition of the negative forms to allow suppression of statically declared options.
The keywords UNDERLINE and UPPER are not available as static options of the ACCEPT statement. When specified, UPPER causes all lowercase alphabetic characters contained in the screen field to be changed to uppercase alphabetic characters before input data conversion and storing in the receiving field.
When specified, UNDERLINE causes the field on the screen to be shown in underlined mode, provided the terminal supports that mode.
GnuCOBOL provides two additional keywords in the CONTROL phrase that affect an ACCEPT field.
1. FCOLOR = color-name
When FCOLOR is present, color-name specifies the foreground color of the ACCEPT field. This name is then used as the default value for subsequent ACCEPT statements in the program. The initial default for color-name is white.
2. BCOLOR = color-name
When BCOLOR is present, color-name specifies the background color of the DISPLAY field. This value is then used as the default value for subsequent ACCEPT statements in the program. The initial default for color-name is black.
Following table contains a list of all the valid names for color-name. The left column contains the valid color name. The right column shows the color that appears when high intensity is specified (the default intensity).
+--------------------------------------------------------------+ | Valid GnuCOBOL Color Names | +-------------------+------------------------------------------+ |Valid Color Names | High-Intensity Color Values (Defaults) | +-------------------+------------------------------------------+ |Black | Gray | |Blue | Light Blue | |Green | Light Green | |Cyan | Light Cyan | |Red | Light Red | |Magenta | Light Magenta | |Brown | Yellow | |White | High-Intensity White | -------------------+------------------------------------------+ Sample program: >>SOURCE FREE id division. program-id. prog. data division. working-storage section. 01 wVAR pic x(10). procedure division. accept wVAR at 0101 with control "fcolor=white, bcolor=red, erase eos" stop run.COLOR Phrase
The COLOR phrase provides an alternate method for setting video attributes. Integer-9 must be a numeric literal. Identifier-9 must be a numeric data item. It also allows the specification of colors for screen fields and controls. They can be set to different numeric values to express various combinations of colors and video attributes.
You may make combinations by adding the appropriate values together. The following color values are accepted:
+--------+--------------+-------------+ |Color | Foreground | Background | +--------+--------------+-------------+ |Black | 1 | 32 | |Blue | 2 | 64 | |Green | 3 | 96 | |Cyan | 4 | 128 | |Red | 5 | 160 | |Magenta | 6 | 192 | |Brown | 7 | 224 | |White | 8 | 256 | +--------+--------------+-------------+You may specify other video attributes by adding the following values:
+-------------------------+--------+ |Reverse video | 1024 | |Low intensity | 2048 | |High intensity | 4096 | |Underline | 8192 | |Blink | 16384 | |Protected | 32768 | |Background low-intensity | 65536 | |Background high-intensity| 131072 | +-------------------------+--------+You may also specify high intensity by adding "8" to the foreground color value.
The OMITTED format of the
ACCEPTstatement will wait for a keyboard event that terminates input; function keys, or Enter/Return, among others. CRT STATUS (COB-CRT-STATUSCRT STATUS(see SPECIAL-NAMES) if not explicitly defined) is set with the keycode, listed in copy/screenio.cpy. You can use extended attributes, useful for setting timeouts or positioning. It also handles a few other keycode terminations not normally used to complete an extended accept.The following are examples of keycodes that can be used:
COB-SCR-INSERT COB-SCR-DELETE COB-SCR-BACKSPACE COB-SCR-KEY-HOME COB-SCR-KEY-END
ACCEPT data-item (Microsoft v1-v2)
ACCEPT data-item Syntax
=======================================================================
=======================================================================
This format of the ACCEPT statement is used to retrieve data from a working storage item using the Microsoft format from v1 and v2 compilers (MsDos). See previous ACCEPT data-Item for detailed information.
ACCEPT FROM DATE/TIME
ACCEPT FROM DATE/TIME Syntax
=======================================================================
ACCEPT identifier-1 FROM { DATE [ YYYYMMDD ] } [ END-ACCEPT ]
~~~~~~ ~~~~ { ~~~~ ~~~~~~~~ } ~~~~~~~~~~
{ DAY [ YYYYDDD ] }
{ ~~~ ~~~~~~~ }
{ DAY-OF-WEEK }
{ ~~~~~~~~~~~ }
{ TIME }
{ ~~~~ }
{ MICROSECOND-TIME }
~~~~~~~~~~~~~~~~
=======================================================================
This format of the ACCEPT statement is used to retrieve the current system date, time or current day of the week and store it into a data item.
The data retrieved from the system and the format in which it is structured will vary, as follows:
Syntax Data Retrieved Format DATECurrent date in Gregorian form yymmdd DATE YYYYMMDDCurrent date in Gregorian form yyyymmdd DAYCurrent date in Julian form yyddd DAY YYYYDDDCurrent date in Julian form yyyyddd DAY-OF-WEEKCurrent day within a week where 1 = Monday.., 7 = Sunday d TIMETime, including hundredths of a second (n) hhmmssnn MICROSECOND-TIMETime, including micro seconds (u) hhmmssuuuuuu When using one of
--std=acuor--std=acu-strict, ACCEPT FROM TIME data-item with data-item providing more than 12 digits behaves as if ACCEPT FROM MICROSECOND-TIME data-item is used (six decimal places for fractional seconds).Consider using the standard
FUNCTION FORMATTED-CURRENT-DATEif you need a high precision (up to eight decimal places for fractional seconds).
ACCEPT FROM Screen-Info
ACCEPT FROM Screen-Info Syntax
=======================================================================
ACCEPT identifier-1 FROM { LINES|LINE-NUMBER } [ END-ACCEPT ]
~~~~~~ ~~~~ { ~~~~~ ~~~~~~~~~~~ } ~~~~~~~~~~
{ COLS|COLUMNS }
{ ~~~~ ~~~~~~~ }
{ ESCAPE KEY }
~~~~~~ ~~~
=======================================================================
This format of the ACCEPT statement is used to retrieve information about the console window or about the user’s interactions with it.
The reserved words
LINESandLINE-NUMBERare interchangeable.The reserved words
COLSandCOLUMNSare interchangeable.The following points pertain to the use of the
LINESandCOLUMNSoptions:The
LINESandCOLUMNSoptions will retrieve the respective components of the size of the console display.When the console is running in a windowed environment, this will be the sizing of the window in which the program is executing, in terms of horizontal (
COLUMNS) or vertical (LINES) character counts — not pixels.When the system is not running a windowing environment, the physical console screen attributes will be returned.
Values of 0 will be returned if GnuCOBOL was not generated to include screen I/O.
See the documentation on the
CBL_GET_SCR_SIZEbuilt-in system subroutine (see CBL_GET_SCR_SIZE) for another way to retrieve this information.
The
ESCAPE KEYoption may be used after an ACCEPT data-item has been used to retrieve data off a formatted screen. The result returned, will be the four-digit key id of the special key that was pressed to terminate the ACCEPT data-item (a 0000 is returned for the Enter key).If you specify the CRT STATUS is Identifier-1 clause in SPECIAL NAMES, then for an ACCEPT data-item, the system sets a code in the identifier-1 field that indicates which key ended the ACCEPT data-item.
If the CRT STATUS clause IS identifier-1 is not specified in SPECIAL NAMES. then within the program, you can write two consecutive ACCEPTs:
ACCEPT data-item ACCEPT identifier-1 FROM ESCAPE KEYIn this way in the identifier-1 field you will have the return code which indicates which key completed the ACCEPT data-item.
ACCEPT FROM Runtime-Info
ACCEPT FROM Runtime-Info Syntax
=======================================================================
ACCEPT identifier-1 FROM { EXCEPTION STATUS } [ END-ACCEPT ]
~~~~~~ ~~~~ { ~~~~~~~~~ ~~~~~~ } ~~~~~~~~~~
{ USER NAME }
~~~~ ~~~~
=======================================================================
This format of the ACCEPT statement is used to retrieve run-time information such as the most-recent error exception code and the current user’s user name.
The following points pertain to the use of the
EXCEPTION STATUSoption:<identifier-1> must be defined as a
PIC X(4)item.See Error Exception Codes, for a complete list of the exception codes and their meanings.
An alternative to the use of
ACCEPT FROM Runtime-Infois to use theEXCEPTION-STATUSintrinsic function (see EXCEPTION-STATUS).
The following points pertain to the use of the
USER NAMEoption:The returned result is the userid that was used to login to the system with, and not any actual first and/or last name of the user in question (unless, of course, that is the information used as a logon id). It is not the PID or UID numbers but the name associated with the UID under *nix based systems.
<identifier-1> should be defined large enough to receive the longest user-name on the system.
If insufficient space is allocated, the returned value will be truncated.
If excess space is allocated, the returned value will be padded with spaces (to the right).
ADD
ADD TO
ADD TO Syntax
=======================================================================
ADD { identifier-1 }... TO { identifier-2 [ rounded-phrase ] }...
~~~ { literal-1 } ~~
[ ON SIZE ERROR imperative-statement-1 ]
~~~~ ~~~~~
[ NOT ON SIZE ERROR imperative-statement-2 ]
~~~ ~~~~ ~~~~~
[ END-ADD ]
~~~~~~~
=======================================================================
This format of the ADD statement generates an intermediate arithmetic sum of the values of all <identifier-1> and <literal-1>) items. The value of each <identifier-2> will be replaced, in turn, by the sum of that <identifier-2>s value and the intermediate sum.
The reserved words
ISandONare optional and may be omitted. The presence or absence of these words has no effect upon the program.Both <identifier-1> and <identifier-2> must be numeric unedited data items while <literal-1> must be a numeric literal.
An <identifier-1> data item may also be coded as an <identifier-2>. Note, however, that the value of such a data item will therefore be included twice in the result.
The contents of each <identifier-1> will remain unchanged by this statement.
The optional
ROUNDED(see ROUNDED) clause available to each <identifier-2> will control how non-integer results will be saved.The optional
ON SIZE ERRORandNOT ON SIZE ERRORclauses may be used to detect and react to the failure or success, respectively, of an attempt to perform a calculation. In this case, failure is defined as being an <identifier-2> with an insufficient number of digit positions available to the left of any implied decimal point. See ON SIZE ERROR + NOT ON SIZE ERROR, for additional information.
ADD GIVING
ADD GIVING Syntax
=======================================================================
ADD { identifier-1 }... [ TO { identifier-2 } ]
~~~ { literal-1 } { literal-2 }
GIVING { identifier-3 [ rounded-phrase ] }...
~~~~~~
[ ON SIZE ERROR imperative-statement-1 ]
~~~~ ~~~~~
[ NOT ON SIZE ERROR imperative-statement-2 ]
~~~ ~~~~ ~~~~~
[ END-ADD ]
~~~~~~~
=======================================================================
This format of the ADD statement generates the arithmetic sum of the values of all <identifier-1>, <literal-1>) and <identifier-2> (if any) items and then saves that sum to each <identifier-3>.
The reserved words
ISandONare optional and may be omitted. The presence or absence of these words has no effect upon the program.Both <identifier-1> and <identifier-2> must be numeric unedited data items while <literal-1> must be a numeric literal; <identifier-3> may be either a numeric or numeric edited data item.
An <identifier-1> or <identifier-2> data item may be used as an <identifier-3>, if desired.
The contents of each <identifier-1> and <identifier-2> will remain unchanged by this statement, unless they happen to also be specified as an <identifier-3>.
The current value in each <identifier-3> at the start of the statement’s execution is irrelevant, since the contents of each <identifier-3> will simply be replaced with the computed sum.
The optional
ROUNDED(see ROUNDED) clause available to each <identifier-3> will control how non-integer results will be saved.The optional
ON SIZE ERRORandNOT ON SIZE ERRORclauses may be used to detect and react to the failure or success, respectively, of an attempt to perform a calculation. In this case, failure is defined as being an <identifier-3> with an insufficient number of digit positions available to the left of any implied decimal point. See ON SIZE ERROR + NOT ON SIZE ERROR, for additional information.
ADD CORRESPONDING
ADD CORRESPONDING Syntax
=======================================================================
ADD CORRESPONDING identifier-1 TO identifier-2 [ rounded-phrase ]
~~~ ~~~~ ~~
[ ON SIZE ERROR imperative-statement-1 ]
~~~~ ~~~~~
[ NOT ON SIZE ERROR imperative-statement-2 ]
~~~ ~~~~ ~~~~~
[ END-ADD ]
~~~~~~~
=======================================================================
This format of the ADD statement generates code equivalent to individual ADD TO (see ADD TO) statements for corresponding matches of data items found subordinate to the two identifiers.
The reserved words
ISandONare optional and may be omitted. The presence or absence of these words has no effect upon the program.Both <identifier-1> and <identifier-2> must be group items.
See CORRESPONDING, for information on how corresponding matches will be found between <identifier-1> and <identifier-2>.
The optional
ROUNDED(see ROUNDED) clause available to each <identifier-3> will control how non-integer results will be saved.The optional
ON SIZE ERRORandNOT ON SIZE ERRORclauses may be used to detect and react to the failure or success, respectively, of an attempt to perform a calculation. In this case, failure is defined as being an <identifier-3> with an insufficient number of digit positions available to the left of any implied decimal point. See ON SIZE ERROR + NOT ON SIZE ERROR, for additional information.
ALLOCATE
ALLOCATE Syntax
=======================================================================
Format 1. Allocate a "BASED" item.
ALLOCATE identifier-1
~~~~~~~~
[ { INITIALIZED } ] [ RETURNING identifier-3 ]
{ ~~~~~~~~~~~ } ~~~~~~~~~
{ INITIALISED }
~~~~~~~~~~~
Format 2. Allocate a memory block.
ALLOCATE { literal-1 } CHARACTERS
~~~~~~~~ { identifier-2 } ~~~~~~~~~~
{ arithmetic-expression-1 }
[ { INITIALIZED } [ TO { literal-1 } ] ] RETURNING identifier-3
{ ~~~~~~~~~~~ } [ ~~ { identifier-2 } ] ~~~~~~~~~
{ INITIALISED }
~~~~~~~~~~~
=======================================================================
The ALLOCATE statement is used to dynamically allocate memory at run-time.
The reserved words
INITIALIZEDandINITIALISEDare interchangeable.If <identifier-1> is specified, the RETURNING phrase may be omitted; otherwise, the RETURNING phrase shall be specified.
If used, <arithmetic-expression-1> must be an arithmetic expression with a non-zero positive integer value and the RETURNING phrase must be specified.
If used, <identifier-1> should be an 01-level item defined in working-storage or local-storage with the
BASED(see BASED) attribute. It may be an 01 item defined in the linkage section without theBASEDattribute, but using such a data item is not recommended.If used, <identifier-3> should be a
POINTER(see USAGE) data item.The optional
RETURNINGclause will return the address of the allocated memory block into the specifiedUSAGE POINTER<identifier-3> data item. When this option is used, knowledge of the originally-requested size of the allocated memory block will be retained by the program in case aFREE(see FREE) statement is ever issued against <identifier-3>.When the <identifier-1> option is used in conjunction with
INITIALIZED(or its internationalized alternativeINITIALISED), the allocated memory block will be initialized as if anINITIALIZE identifier-1 WITH FILLER ALL TO VALUE THEN TO DEFAULT(see INITIALIZE) were executed.When the
arithmetic-expression-1 CHARACTERSoption is used,INITIALIZEDwill initialize the allocated memory block to binary zeros. IfINITIALIZEDis not used, the initial contents of allocated memory will be left to whatever rules of memory allocation are in effect for the operating system the program is running under.There are two basic ways in which this statement is used. The simplest is:
ALLOCATE My-01-ItemWith this form, a block of storage equal in size to the defined size of My-01-Item (which must have been defined with the
BASEDattribute) will be allocated. The address of that block of storage will become the base address of My-01-Item so that it and its subordinate data items become usable within the program.A second (and equivalent) approach is:
ALLOCATE LENGTH OF My-01-Item CHARACTERS RETURNING The-Pointer SET ADDRESS OF My-01-Item TO The-PointerWith this form My-01-Item can either be defined with the
BASEDattribute or be defined in LINKAGE SECTION. Instead of LENGTH OF My-01-Item you may also use a size smaller to the maximum field size as long as you ensure that the complete field is never used.Referencing a
BASEDdata item either before its storage has been allocated or after its storage has been released (via theFREEstatement) will lead to “unpredictable results”. That’s how reference manuals and standards specifications talk about this situation. In the author’s experience, the results are all too predictable: the program aborts from an attempt to reference an unallocated area of memory.
ALTER
ALTER Syntax
=======================================================================
ALTER { procedure-name-1 TO PROCEED TO procedure-name-2 }...
~~~~~ ~~
=======================================================================
The ALTER statement was used in the early years of the COBOL language to edit the object code of a program at execution time, changing a GO TO (see Simple GO TO) statement to branch to a spot in the program different than where the GO TO statement was originally compiled for.
The reserved words
PROCEEDandTO(the one afterPROCEED) are optional and may be omitted. The presence or absence of these words has no effect upon the program.<procedure-name-1> must contain only a single statement, and that statement must be a simple
GO TO.The effect of this statement will be as if the generated machine-language code for the
GO TOstatement in <procedure-name-1> is changed so that theGO TOstatement now transfers control to <procedure-name-2>, rather than to whatever procedure name was specified in the program source code.Support for the
ALTERverb has been added to GnuCOBOL for the purpose of enabling GnuCOBOL to pass those National Institute of Standards and Technology (NIST) tests for the COBOL programming language that require support forALTER.Because of the catastrophic effect this statement has on program readability and therefore the programmer’s ability to debug problems with program logic, the use of
ALTERin new programs is STRONGLY discouraged.
CALL
CALL Syntax
=======================================================================
CALL [ { STATIC } ] [ WITH { STDCALL } LINKAGE ] { literal-1 }
~~~~ { ~~~~~~ } ~~~~ { ~~~~~~~ } ~~~~~~~ { identifier-1 }
{ STDCALL } { C }
{ ~~~~~~~ } { ~ }
{ C } { PASCAL }
{ ~ } ~~~~~~
{ PASCAL }
{ ~~~~~~ }
{ EXTERN }
{ ~~~~~~ }
{ mnemonic-name-1 }
[ USING { [ BY { REFERENCE } ]
~~~~~ { { ~~~~~~~~~ }
{ { CONTENT }
{ { ~~~~~~~ }
{ { VALUE }
~~~~~
{ [ UNSIGNED SIZE IS { AUTO } ] { literal-2 }... } }... ]
{ ~~~~ { ~~~~ } { identifier-2 } } }
{ { integer-1 } } }
{ } }
{ OMITTED } }
[ RETURNING|GIVING { INTO identifier-3 } ]
~~~~~~~~~ ~~~~~~ { ADDRESS OF identifier-4 }
{ ~~~~~~~ }
{ NOTHING }
{ ~~~~~~~ }
{ NULL }
{ ~~~~ }
{ OMITTED }
~~~~~~~
[ ON OVERFLOW|EXCEPTION imperative-statement-1 ]
~~~~~~~~ ~~~~~~~~~
[ NOT ON EXCEPTION imperative-statement-2 ]
~~~ ~~~~~~~~~
[ END-CALL ]
~~~~~~~~
=======================================================================
The CALL statement is used to transfer control to a subroutine. See Sub-Programming, for the specifics of using subprograms with GnuCOBOL programs.
The reserved words
BY,ISandONare optional and may be omitted. The presence or absence of these words has no effect upon the program.The reserved words
EXCEPTIONandOVERFLOWare interchangeable.The reserved words
GIVINGandRETURNINGare interchangeable.The expectation is that the subroutine will eventually return control back to the calling program, at which point the
CALLing program will resume execution starting with the statement immediately following theCALL. Subprograms are not required to return to their callers, however, and are free to halt program execution if they wish.The <mnemonic-name-1> /
STATIC/STDCALLoption, if used, affects the linkage conventions that will be used to the subroutine being called, as follows:STATIC-
causes the linkage to the subroutine to be performed in such a way as to require the subroutine to be statically-linked with the calling program. Note that this enables static-linking to be used on a subroutine-by-subroutine selective basis.
STDCALL-
allows system standard calling conventions (as opposed to GnuCOBOL calling conventions) to be used when calling a subroutine. The definition of what constitutes “system standard” may vary from operating system to operating system. Use of this requires special knowledge about the linkage requirements of subroutines you are intending to
CALL. Subroutines written in GnuCOBOL do not need this option. - <mnemonic-name-1>
-
allows a custom defined calling convention to be used. Such mnemonic names are defined using the
CALL-CONVENTION(see SPECIAL-NAMES) clause. That clause associates a decimal integer value with <mnemonic-name-1> such that the individual bits set on or off in the binary equivalent of the integer affect linkage to the subroutine as described in the following chart. Those rows of the chart marked with a “No” in the Supported column represent bit positions (switch settings) in the integer value that are currently accepted (to provide compatibility to other COBOL implementations) if coded, but are otherwise unsupported.Note that bit 0 is the right-most bit in the binary value.
Bit Supported Meaning if 0 Meaning if 1 0 No Arguments will be passed in right-to-left sequence Arguments will be passed in left-to-right sequence. 1 No The calling program will flush processed arguments from the argument stack. The called program (subroutine) will flush processed arguments from the argument stack. 2 Yes The RETURN-CODEspecial register (see Special Registers) will be updated in addition to anyRETURNINGorGIVINGdata item.The RETURN-CODEspecial register will not be updated (but anyRETURNINGorGIVINGdata item still will).3 Yes If CALL literalis used, the subroutine will be located and linked in with the calling program at compile time or may be dynamically located and loaded at execution time, depending on compiler switch settings and operating system capabilities.If CALL literalis used, the subroutine can only be located and linked with the calling program at compilation time.4 No OS/2 “OPTLINK” conventions will not be used to CALL the subprogram. OS/2 “OPTLINK” conventions will be used to CALL the subprogram. 5 No Windows 16-bit “thunking” will not be in effect. Windows 16-bit “thunking” will be used to call the subroutine as a DLL. 6 Yes The STDCALLconvention will not be used.The STDCALLconvention, required to use the Microsoft Win32 API, will be used.Using the
STATICoption on aCALLstatement is equivalent to usingCALL-CONVENTION 8(only bit 3 set).Using the
STDCALLoption on aCALLstatement is equivalent to usingCALL CONVENTION 64(only bit 6 set).
The value of <literal-1> or <identifier-1> is the entry-point of the subprogram you wish to call.
When you call a subroutine using <identifier-1>, you are forcing the runtime system to call a dynamically-loadable subprogram. The contents of <identifier-1> will be the entry-point name within that module. If this is the first call to any entry-point within the module being made at run-time, the contents of <identifier-1> must be the primary entry-point name of the module (which must also match the filename, minus any OS-mandated extension) of the executable file comprising the module).
You can force the GnuCOBOL runtime system to pre-load all dynamically-loaded modules that could ever be called by the program, at the time the program starts executing. This is accomplished through the use of the
COB_PRE_LOADrun-time environment variable (see Run Time Environment Variables). If used, this will only pre-load those modules invoked viaCALL literal-1, as the runtime contents of <identifier-1> cannot be predicted.If the subprogram being called is a GnuCOBOL program, and if that program had the
INITIAL(see IDENTIFICATION DIVISION) attribute specified on itsPROGRAM-IDclause, all of the subprogram’s data division data will be restored to its initial state each time the subprogram is executed, regardless of which entry-point within the subprogram is being referenced.This [re]-initialization behaviour will always apply to any subprogram’s local-storage (if any), regardless of the use (or not) of
INITIAL.The
USINGclause defines a list of arguments that may be passed from the calling program to the subprogram. The manner in which any given argument is passed to the subroutine depends upon theBYclause (if any) coded (or implied) for that argument, as follows:BY REFERENCE-
passes the address of the argument to the subprogram. If the subprogram changes the contents of that argument, the change will be “visible” to the calling program.
BY CONTENT-
passes the address of a copy of the argument to the subprogram. If the subprogram changes the value of such an argument, the change only affects the copy back in the calling program, not the original version.
BY VALUE-
passes the actual numeric value of the literal or identifiers contents as the argument. This feature exists to provide compatibility with C, C++ and other languages and would not normally be used when calling GnuCOBOL subprograms. Only numeric literals or numeric data items should be passed in this manner.
If an argument lacks a
BYclause, the most-recently encounteredBYspecification on thatCALLstatement will be assumed. If the first argument specified on aCALLlacks aBYclause,BY REFERENCEwill be assumed.No more than 251 arguments may be passed to a subroutine, unless the GnuCOBOL compiler was built with a specifically different argument limit specified for it. If you have access to the GnuCOBOL source code, you may adjust this limit by changing the value of the
COB_MAX_FIELD_PARAMSin thecall.cfile (found in thelibcobfolder) as well as the last shown#if MAX_CALL_FIELD_PARAMSstatement before you runmaketo build the compiler and run-time library.The
RETURNINGclause allows you to specify a numeric data item into which the subroutine should return a numeric value. If you use this clause on theCALL, the subroutine should include aRETURNING(see PROCEDURE DIVISION RETURNING) clause on its procedure division header. Of course, a subroutine may pass a value of any kind back in any argument passedBY REFERENCE.The optional
ON OVERFLOWandNOT ON OVERFLOWclauses (orON EXCEPTIONandNOT ON EXCEPTION— they are interchangeable) may be used to detect and react to the failure or success, respectively, of an attempt toCALLthe subroutine. Failure, in this context, is defined as the inability to either locate or load the object code of the subroutine at execution time. See ON OVERFLOW + NOT ON OVERFLOW, for additional information.Call also supports using an entry point stored in a
PROGRAM-POINTER, avoiding the dynamic runtime lookup. GnuCOBOL keeps a cache of lookups during a program run. Repeated use of a named function does not suffer much penalty, butPROGRAM-POINTERwill be just that little bit faster. To set aPROGRAM-POINTERuseSET program-reference TO ENTRY "name"(or get the address from an API, and take part in callback programming).An extension of
CALLallows a call to a <Program-Pointer-1> which is preset usingSET program-pointer-1 TO ENTRY x. Additional theRETURNINGclause may return a data pointer or aPROGRAM-POINTER
CANCEL
CANCEL Syntax
=======================================================================
CANCEL { literal-1 }...
~~~~~~ { identifier-1 }
=======================================================================
The CANCEL statement unloads the dynamically-loadable subprogram module containing the entry-point specified as <literal-1> or <identifier-1> from memory.
If a dynamically-loadable module unloaded by the
CANCELstatement is subsequently re-executed, all data division storage for that module will once again be in its initial state.Whether the
CANCELstatement actually physically unloads a dynamically-loaded module or simply marks it as logically-unloaded depends on the use and value of theCOB_PHYSICAL_CANCELrun-time environment variable (see Run Time Environment Variables).Since the
CANCELstatement applies only to dynamically-loadable subprogram modules, it will have no effect if the subroutine is statically linked with the calling program.For further details, see CALL, see Dynamic vs Static Subprograms.
CLOSE
CLOSE Syntax
=======================================================================
CLOSE { file-name-1 [ { REEL|UNIT [ FOR REMOVAL ] } ] }...
~~~~~ { ~~~~ ~~~~ ~~~~~~~ }
{ WITH LOCK }
{ ~~~~ }
{ WITH NO REWIND }
~~ ~~~~~~
The REEL, LOCK and NO REWIND clauses are syntactically recognized but are otherwise non-functional, except for the CLOSE…NO REWIND statement, which will generate a file status of 07 rather than the usual 00 (but take no other action).
=======================================================================
The CLOSE statement terminates the program’s access to the specified file(s).
The reserved words
FORandWITHare optional and may be omitted. The presence or absence of these words has no effect upon the program.The reserved words
REELandUNITare interchangeable.The
CLOSEstatement may only be executed against files that have been successfully opened.A successful
CLOSEwill write any remaining unwritten record buffers to the file (similar to anUNLOCKstatement (see UNLOCK)) and release any file locks for the file, regardless of open mode. A closed file will then be no longer available for subsequent I/O statements until it is once again OPENED.When a
ORGANIZATION LINE SEQUENTIAL(see ORGANIZATION LINE SEQUENTIAL) orLINE ADVANCING(see LINE ADVANCING) file is closed, a final delimiter sequence will be written to the file to signal the termination point of the final data record in the file. This will only be necessary if the final record written to the file was written with theAFTER ADVANCING(see WRITE) option.
COMMIT
COMMIT Syntax
=======================================================================
COMMIT
~~~~~~
=======================================================================
The COMMIT statement performs an UNLOCK against every currently-open file, but does not close any of the files. See the UNLOCK statement (see UNLOCK) for additional details.
COMPUTE
COMPUTE Syntax
=======================================================================
COMPUTE { identifier-1 [ rounded-phrase ] }...
~~~~~~~
=|EQUALS arithmetic-expression-1|boolean-expression-1
~~~~~
[ ON SIZE ERROR imperative-statement-1 ]
~~~~ ~~~~~
[ NOT ON SIZE ERROR imperative-statement-2 ]
~~~ ~~~~ ~~~~~
[ END-COMPUTE ]
~~~~~~~~~~~
=======================================================================
The COMPUTE statement provides a means of easily performing complex arithmetic operations with a single statement, instead of using cumbersome and possibly confusing sequences of ADD, SUBTRACT, MULTIPLY and DIVIDE statements. COMPUTE also allows the use of exponentiation — an arithmetic operation for which no other statement exists in COBOL.
The reserved words
ISandONare optional and may be omitted. The presence or absence of these words has no effect upon the program.The reserved word
EQUALis interchangeable with the use of ‘=’.Each <identifier-1> must be a numeric or numeric-edited data item.
The optional
ROUNDED(see ROUNDED) clause available to each <identifier-1> will control how non-integer results will be saved.See Arithmetic Expressions, for more information on arithmetic expressions.
The optional
ON SIZE ERRORandNOT ON SIZE ERRORclauses may be used to detect and react to the failure or success, respectively, of an attempt to perform a calculation. In this case, failure is defined either as having an <identifier-3> with an insufficient number of digit positions available to the left of any implied decimal point or attempting to divide by zero. See ON SIZE ERROR + NOT ON SIZE ERROR, for additional information.The COMPUTE verb can also be used to evaluate boolean expressions. See the following example:
>>SOURCE FREE IDENTIFICATION DIVISION. PROGRAM-ID. TESTBOOLEAN. DATA DIVISION. WORKING-STORAGE SECTION. 01 A pic 9 comp-x value B'00000101'. 01 B pic 9 comp-x value B'00000011'. 01 c pic 9 value LOW-VALUE. PROCEDURE DIVISION. display space display ' a b c a b c ' display ' --- ------ --- --- -------- -------- -------- --------' display ' ' a ' initial ' b ' ' c ' ' FUNCTION BIT-Of(a) ' initial ' FUNCTION BIT-Of(b) ' ' FUNCTION BIT-OF(c) display space display space display ' a operator b c a operator b c ' display ' --- ------ --- --- -------- -------- -------- --------' compute c = a B-AND b display ' ' a ' AND ' b ' = ' c ' ' FUNCTION BIT-Of(a) ' AND ' FUNCTION BIT-Of(b) ' = ' FUNCTION BIT-OF(c) compute c = a B-OR b display ' ' a ' OR ' b ' = ' c ' ' FUNCTION BIT-Of(a) ' OR ' FUNCTION BIT-Of(b) ' = ' FUNCTION BIT-OF(c) compute c = a B-XOR b display ' ' a ' XOR ' b ' = ' c ' ' FUNCTION BIT-Of(a) ' XOR ' FUNCTION BIT-Of(b) ' = ' FUNCTION BIT-OF(c) compute c = B-NOT b display ' -' ' NOT ' b ' = ' c ' - ' ' NOT ' FUNCTION BIT-Of(b) ' = ' FUNCTION BIT-OF(c) accept omitted STOP RUN.and in particular with the boolean shift operators, see the following example:
>>SOURCE FREE IDENTIFICATION DIVISION. PROGRAM-ID. TESTBOOLEANSHIFT. DATA DIVISION. WORKING-STORAGE SECTION. 01 A pic 9 comp-x value B'00000001'. 01 B pic 9 comp-x value B'00000101'. 01 c pic 9 value LOW-VALUE. PROCEDURE DIVISION. display space display ' a b c a b c ' display ' --- ------ --- --- -------- ---------- -------- --------' display ' ' a ' initial ' b ' ' c ' ' FUNCTION BIT-Of(a) ' initial ' FUNCTION BIT-Of(b) ' ' FUNCTION BIT-OF(c) display space display space display ' a operator b c a operator b c ' display ' --- ------ --- --- -------- ---------- -------- --------' compute c = a B-SHIFT-L b display ' ' a ' B-SHIFT-L ' b ' = ' c ' ' FUNCTION BIT-Of(a) ' B-SHIFT-L ' FUNCTION BIT-Of(b) ' = ' FUNCTION BIT-OF(c) compute c = a B-SHIFT-LC b display ' ' a ' B-SHIFT-LC ' b ' = ' c ' ' FUNCTION BIT-Of(a) ' B-SHIFT-LC ' FUNCTION BIT-Of(b) ' = ' FUNCTION BIT-OF(c) compute c = a B-SHIFT-R b display ' ' a ' B-SHIFT-R ' b ' = ' c ' ' FUNCTION BIT-Of(a) ' B-SHIFT-R ' FUNCTION BIT-Of(b) ' = ' FUNCTION BIT-OF(c) compute c = a B-SHIFT-RC b display ' ' a ' B-SHIFT-RC ' b ' = ' c ' ' FUNCTION BIT-Of(a) ' B-SHIFT-RC ' FUNCTION BIT-Of(b) ' = ' FUNCTION BIT-OF(c) accept omitted STOP RUN.
CONTINUE
CONTINUE Syntax
=======================================================================
CONTINUE [ AFTER { literal-1 } SECONDS ]
~~~~~~~~ ~~~~~ { identifier-1 } ~~~~~~~
{ arithmetic-expression-1 }
=======================================================================
The CONTINUE statement is a no-operation statement that may be coded anywhere an imperative statement (see Imperative Statement) may be coded.
The
CONTINUEstatement has no effect on the execution of the program.This statement (perhaps in combination with an appropriate comment or two) makes a convenient “place holder” — particularly in
ELSE(see IF) orWHEN(see EVALUATE) clauses where no code is currently expected to be needed, but a place for code to handle the conditions in question is to be reserved in case it’s ever needed.The optional extension of (AFTER) when used with the
CONTINUEstatement pauses execution for a specified length of time.
DELETE
DELETE Syntax
=======================================================================
Format 1
DELETE file-name-1 RECORD
~~~~~~
[ INVALID KEY imperative-statement-1 ]
~~~~~~~
[ NOT INVALID KEY imperative-statement-2 ]
~~~ ~~~~~~~
[ END-DELETE ]
~~~~~~~~~~
Format 2
DELETE FILE { file-name-1 }...
~~~~~~ ~~~~
[ ON EXCEPTION imperative-statement-1 ]
~~~~~~~~~
[ NOT ON EXCEPTION imperative-statement-2 ]
~~~ ~~~~~~~~~
[ END-DELETE ]
~~~~~~~~~~
=======================================================================
The Format 1 DELETE statement logically deletes a record from a file, the following pertains to such.
The reserved words
KEYandRECORDare optional and may be omitted. The presence or absence of these words has no effect upon the program.The
ORGANIZATIONof <file-name-1> cannot beORGANIZATION LINE SEQUENTIAL(see ORGANIZATION LINE SEQUENTIAL).The <file-name-1> file cannot be a sort/merge work file (a file described using a
SD(see File/Sort-Description)).For files in the
SEQUENTIALaccess mode, the last input-output statement executed against <file-name-1> prior to the execution of theDELETEstatement must have been a successfully executed sequential-formatREADstatement (see Sequential READ). ThatREADwill therefore identify the record to be deleted.If <file-name-1> is a
RELATIVEfile whoseACCESS MODE(see ORGANIZATION RELATIVE) is eitherRANDOMorDYNAMIC, the record to be deleted is the one whose relative record number is currently the value of the field specified as the filesRELATIVE KEYin itsSELECTstatement.If <file-name-1> is an
INDEXEDfile whoseACCESS MODE(see ORGANIZATION INDEXED) isRANDOMorDYNAMIC, the record to be deleted is the one whose primary key is currently the value of the field specified as theRECORD KEYin the file’sSELECTstatement.The optional
INVALID KEYandNOT INVALID KEYclauses may be used to detect and react to the failure or success, respectively, of an attempt to delete a record. See INVALID KEY + NOT INVALID KEY, for additional information.No
INVALID KEYorNOT INVALID KEYclause may be specified for a file who’sACCESS MODE IS SEQUENTIAL.
The Format 2 DELETE FILE statement deletes a file and the following pertains to such.
DELETE FILE takes from 1 to n "ASSIGN" names, sets and return the FILE-STATUS (like ex. 35 FILE not found), has ON EXCEPTION and NOT ON EXCEPTION routines and always deletes all parts belonging to a multi-part ISAM file (the index file or files and the data file).
Instead CBL_DELETE_FILE takes any "filename string" and only deletes exactly that, while C$DELETE can (depending on the file-type parameter) delete multiple files (like isam.1, isam.2, ...) and also takes a "filename string".
DISPLAY
DISPLAY UPON device
DISPLAY UPON device Syntax
=======================================================================
DISPLAY { literal-1 }... [ UPON mnemonic-name-1 ] [ WITH NO ADVANCING ]
~~~~~~~ { identifier-1 } ~~~~ ~~ ~~~~~~~~~
[ ON EXCEPTION imperative-statement-1 ]
~~~~~~~~~
[ NOT ON EXCEPTION imperative-statement-2 ]
~~~ ~~~~~~~~~
[ END-DISPLAY ]
~~~~~~~~~~~
=======================================================================
This format of the DISPLAY statement displays the specified identifier contents and/or literal values on the system output device specified via the UPON clause.
The reserved words
ONandWITHare optional and may be omitted. The presence or absence of these words has no effect upon the program.If no
UPONclause is specified,UPON CONSOLEwill be assumed. If theUPONclause is specified, <mnemonic-name-1> must be one of the built-in output device namesCONSOLE,PRINTER,STDERR,STDOUT,SYSERR,SYSLIST,SYSLSTorSYSOUTor a mnemonic name assigned to one of those devices via theSPECIAL-NAMES(see SPECIAL-NAMES) paragraph.When displaying upon the
STDERRorSYSERRdevices or to a <mnemonic-name-1> attached to one of those two devices, the output will be written to output pipe #2, which will normally cause the output to appear in the console output window. You may, if desired, redirect that output to a file by appending2> filenameto the end of the command that executes the program. This applies to both Windows (any type) or Unix versions of GnuCOBOL.When displaying upon the
CONSOLE,PRINTER,STDOUT,SYSLIST,SYSLSTorSYSOUTdevices or to a <mnemonic-name-1> attached to one of them, the output will be written to output pipe #1, which will normally cause the output to appear in the console output window. You may, if desired, redirect that output to a file by appending1> filenameor simply> filenameto the end of the command that executes the program. This applies to both Windows (any type) or Unix versions of GnuCOBOL.The
NO ADVANCINGclause, if used, will suppress the carriage-return / line-feed sequence that is normally added to the end of any console display.The optional
ON EXCEPTIONandNOT ON EXCEPTIONclauses may be used to detect and react to the failure or success, respectively, of an attempt to display output to the specified device. See ON EXCEPTION + NOT ON EXCEPTION, for additional information.
DISPLAY UPON COMMAND-LINE
DISPLAY UPON COMMAND-LINE Syntax
=======================================================================
DISPLAY { literal-1 } UPON { ARGUMENT-NUMBER | COMMAND-LINE }
~~~~~~~ { identifier-1 } ~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~
[ ON EXCEPTION imperative-statement-1 ]
~~~~~~~~~
[ NOT ON EXCEPTION imperative-statement-2 ]
~~~ ~~~~~~~~~
[ END-DISPLAY ]
~~~~~~~~~~~
=======================================================================
This form of the DISPLAY statement may be used to specify the command-line argument number to be retrieved by a subsequent ACCEPT FROM ARGUMENT-VALUE statement (see ACCEPT FROM COMMAND-LINE) or to specify a new value for the command-line arguments themselves.
The reserved word
ONis optional and may be omitted. The presence or absence of this word has no effect upon the program.By displaying a numeric integer value
UPONARGUMENT-NUMBER, you will specify which argument (by its relative number) will be retrieved by a subsequentACCEPT FROM ARGUMENT-VALUEstatement.Executing a
DISPLAY UPON COMMAND-LINEwill influence subsequentACCEPT FROM COMMAND-LINEstatements (which will then return the value you displayed), but will not influence subsequentACCEPT FROM ARGUMENT-VALUEstatements — these will continue to return the original program execution parameters.The optional
ON EXCEPTIONandNOT ON EXCEPTIONclauses may be used to detect and react to the failure or success, respectively, of an attempt to display output to the specified item. See ON EXCEPTION + NOT ON EXCEPTION, for additional information.
DISPLAY UPON ENVIRONMENT
DISPLAY UPON ENVIRONMENT Syntax
=======================================================================
DISPLAY { literal-1 } UPON { ENVIRONMENT-VALUE }
~~~~~~~ { identifier-1 } ~~~~ { ~~~~~~~~~~~~~~~~~ }
{ ENVIRONMENT-NAME }
~~~~~~~~~~~~~~~~
[ ON EXCEPTION imperative-statement-1 ]
~~~~~~~~~
[ NOT ON EXCEPTION imperative-statement-2 ]
~~~ ~~~~~~~~~
[ END-DISPLAY ]
~~~~~~~~~~~
=======================================================================
This form of the DISPLAY statement can be used to create or modify environment variables.
The reserved word
ONis optional and may be omitted. The presence or absence of this word has no effect upon the program.To create or change an environment variable will require two
DISPLAYstatements. The following example sets the environment variableMY_ENV_VARto a value of ‘Demonstration Value’:DISPLAY "MY_ENV_VAR" UPON ENVIRONMENT-NAME DISPLAY "Demonstration Value" UPON ENVIRONMENT-VALUEEnvironment variables created or changed from within GnuCOBOL programs will be available to any sub-shell processes spawned by that program (i.e.
CALL 'SYSTEM'(see SYSTEM)) but will not be known to the shell or console window that started the GnuCOBOL program.Consider using
SET ENVIRONMENT(see SET ENVIRONMENT) in lieu ofDISPLAYto set environment variables as it is much simpler.The optional
ON EXCEPTIONandNOT ON EXCEPTIONclauses may be used to detect and react to the failure or success, respectively, of an attempt to display output to the specified item. See ON EXCEPTION + NOT ON EXCEPTION, for additional information.
DISPLAY data-item
DISPLAY data-item Syntax
=======================================================================
DISPLAY { { identifier-1 } [ UPON CRT|CRT-UNDER ] [ MODE IS BLOCK ]
~~~~~~~ { literal-1 } ~~~~ ~~~ ~~~~~~~~~ ~~~~ ~~~~~
[ { | AT LINE NUMBER { integer-1 } | } ]
[ { | ~~~~ { identifier-2 } | } ]
[ { | { arithmetic-expression-1 } | } ]
[ { | | } ]
[ { | AT COLUMN|POSITION NUMBER { integer-2 } | } ]
[ { | ~~~ ~~~ { identifier-3 } | } ]
[ { | { arithmetic-expression-2 } | } ]
[ { } ]
[ { AT { integer-3 } } ]
[ { ~~ { identifier-4 } } ]
[ WITH BELL|BEEP ]
~~~~ ~~~~
[ WITH BLANK { LINE|SCREEN } ]
~~~~~ ~~~~ ~~~~~~
[ WITH ERASE { EOL|EOS } ]
[ ~~~~~ { ~~~ ~~~ } ]
[ { [ TO END OF ] LINE|SCREEN } ]
~~~ ~~~~ ~~~~~~
[ WITH BACKGROUND-COLOR|BACKGROUND-COLOUR IS|= integer-4|identifier-5 ]
~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~
[ WITH FOREGROUND-COLOR|FOREGROUND-COLOUR IS|= integer-5|identifier-6 ]
~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~
[ WITH HIGHLIGHT|LOWLIGHT ]
~~~~~~~~~ ~~~~~~~~
[ WITH BLINK ]
~~~~~
[ WITH REVERSE-VIDEO|REVERSE|REVERSED ]
~~~~~~~~~~~~~ ~~~~~~~ ~~~~~~~~
[ WITH OVERLINE ]
~~~~~~~~
[ WITH UNDERLINE ]
~~~~~~~~~
[ WITH SCROLL [ UP ] [ { integer-6 } LINE|LINES ] ]
[ ~~~~~~ [ ~~ ] [ { identifier-9 } ~~~~ ~~~~~ ] ]
[ [ DOWN ] ]
~~~~
[ WITH CONVERSION ]
~~~~~~~~~~
[ WITH SIZE IS { integer-7 } ]
[ ~~~~ { identifier-8 } ]
[ WITH CONTROL { literal-7 } ]
[ ~~~~~~~ { identifier-7 } ]
[ WITH COLOUR|COLOR IS { integer-8 } ]
[ ~~~~~~ ~~~~~ { identifier-10 } ] }...
[ ON EXCEPTION imperative-statement-1 ]
~~~~~~~~~
[ NOT ON EXCEPTION imperative-statement-2 ]
~~~ ~~~~~~~~~
[ END-DISPLAY ]
~~~~~~~~~~~
The UPON CRT, UPON CRT-UNDER and CONVERSION clauses are syntactically recognized but are otherwise non-functional. They are supported to provide compatibility with COBOL source written for other COBOL implementations.
=======================================================================
This format of the DISPLAY statement presents data onto a formatted screen.
The reserved words
AFTER,LINE,LINES,NUMBERandONare optional and may be omitted. The presence or absence of these words has no effect upon the program.The reserved words
COLUMNandPOSITIONare interchangeable.The reserved words
LINEandLINESare interchangeable.If <identifier-1> is defined in the
SCREEN SECTION(see SCREEN SECTION), anyAT, <Attribute-Specification> andWITHclauses will be ignored. All field definition, cursor positioning and screen control will occur as a result of the screen section definition of <identifier-1>.The reserved word
OMITTEDwhen used, will act to position the cursor or any screen clearance without changing any content of the screen.The following points apply if <identifier-1> is not defined in the screen section:
The purpose of the
ATclause is to define where on the screen <identifier-1> should be displayed. See ACCEPT data-item, for additional information.The purpose of the
WITHclause is to define the visual attributes that should be applied to <identifier-1> when it is displayed on the screen as well as other presentation-control characteristics.The following <Attribute-Specification> clauses are allowed on the
DISPLAYstatement — these are the same as those allowed forSCREEN SECTIONdata items. A particular <Attribute-Specification> may be used only once in anyDISPLAY:BACKGROUND-COLOR(see BACKGROUND-COLOR)BELL(see BELL)BLANK(see BLANK)BLINK(see BLINK)ERASE(see ERASE)FOREGROUND-COLOR(see FOREGROUND-COLOR)HIGHLIGHT(see HIGHLIGHT)LOWLIGHT(see LOWLIGHT)OVERLINE(see OVERLINE)REVERSE-VIDEO(see REVERSE-VIDEO)UNDERLINE(see UNDERLINE)
SIZE<positive-integer>If
SIZEis less than the length of <identifier-1> then only theSIZEnumber of characters display.If
SIZEis greater than the length of <identifier-1>, then the screen pads with spaces after the field to theSIZElength.Figurative constants display repeatedly the number of times in
SIZE. Except thatLOW-VALUESalways positions the cursor (seeSIZEZERO below).SIZE ZEROorSIZEoption not specified><identifier-1> displays with the field length.
CONTROLThe CONTROL phrase allow dynamic (runtime as opposed to compile time) specification of characteristics. Literal-7 must be a nonnumeric literal. Identifier-7 must be a nonnumeric data item. The value of identifier-7 or literal-7 in the CONTROL phrase must be a character-string consisting of a series of keywords delimited by commas; some keywords allow assignment of a value by following the keyword with an equal sign and the value. Blanks are ignored in the character-string. Lowercase letters are treated as uppercase letters within keywords. Keywords specified override corresponding static options specified as phrases. Keywords may be specified in any order. Keywords, which specify options that do not apply to the statement, are ignored.The keywords that affect a DISPLAY statement are BEEP, BLINK, HIGH, LOW, CONVERT, REVERSE, UNDERLINE, ERASE, ERASE EOL, ERASE EOS, NO ERASE, NO BEEP, NO BLINK, NO CONVERT, NO REVERSE, NO UNDERLINE. The meanings of these keywords when they appear in the value of the CONTROL phrase operand are the same as the corresponding phrases which may be written as static options of the DISPLAY statement, with the addition of the negative forms to allow suppression of statically declared options.
GnuCOBOL provides three additional keywords in the CONTROL phrase that affect a DISPLAY field. 1. FCOLOR = color-name When FCOLOR is present, color-name specifies the foreground color of the DISPLAY field. This name is then used as the default value for subsequent DISPLAY statements in the program. The initial default for color-name is white. 2. BCOLOR = color-name When BCOLOR is present, color-name specifies the background color of the DISPLAY field. This value is then used as the default value for subsequent DISPLAY statements in the program. The initial default for color-name is black. Following table contains a list of all the possible names for color-name. The left column contains the valid color name. The right column shows the color that appears when high intensity is specified (the default intensity).
+--------------------------------------------------------------+ | Valid COBOL Color Names | +-------------------+------------------------------------------+ |Valid Color Names | High-Intensity Color Values (Defaults) | +-------------------+------------------------------------------+ |Black | Gray | |Blue | Light Blue | |Green | Light Green | |Cyan | Light Cyan | |Red | Light Red | |Magenta | Light Magenta | |Brown | Yellow | |White | High-Intensity White | +-------------------+------------------------------------------+GRAPHICSThe GRAPHICS keyword causes the characters in following table to be translated to line draw characters. Characters that are not listed in the following table are output unchanged.+-------------------------------------------------------------------+ | Line Draw Characters | +-------------------+-----------------------+-----------------------+ |Description | Single-Line Character | Double-Line Character | |lower-right corner | j(+) | J(+) | |upper-right corner | k(+) | K(+) | |upper-left corner | l(+) | L(+) | |lower-left corner | m(+) | M(+) | |plus | n(+) | N(+) | |horizontal line | q(-) | Q(-) | |left tee | t(+) | T(+) | |right tee | u(+) | U(+) | |bottom tee | v(-) | V(-) | |top tee | w(-) | W(-) | |vertical line | x(|) | X(|) | +-------------------+-----------------------+-----------------------+If the requested line draw characters are not available, the runtime system uses the best available characters. If double-line characters are requested and only single-line characters are available, they are used. If no line draw characters are available, then plus-characters, vertical bars, and dashes are used.
Sample program that demonstrates how boxes are drawn: >>SOURCE FREE IDENTIFICATION DIVISION. PROGRAM-ID. CONTROL1. DATA DIVISION. WORKING-STORAGE SECTION. 01 success-flag PIC X VALUE 'Y'. 88 success VALUE 'Y', 'y'. 77 LIN-START PIC 99 COMP-5. 77 LIN PIC 99 COMP-5. 01 scr1 PIC X(75) VALUE 'Enter "y" if you see line draw characters. ' & 'The first set (single/double)'. 01 scr2 PIC X(75) VALUE 'uses HIGHLIGHT, the second uses ' & 'LOWLIGHT, BLINK and MAGENTA.'. 01 graphcontrol PIC X(50) VALUE 'HIGH, GRAPHICS'. PROCEDURE DIVISION. MOVE 2 TO LIN DISPLAY scr1 AT LINE LIN COL 2 ADD 1 TO LIN DISPLAY scr2 AT LINE LIN COL 2 MOVE 5 TO LIN-START PERFORM DSPCOL MOVE 12 TO LIN-START MOVE "LOW BLINK FCOLOR=MAGENTA GRAPHICS" TO graphcontrol PERFORM DSPCOL ACCEPT success-flag AT 1801 UPDATE REQUIRED IF success AND COB-CRT-STATUS = 0 GOBACK RETURNING 0 ELSE GOBACK RETURNING 1. DSPCOL. *> Single-line graphics MOVE LIN-START TO LIN DISPLAY "lqqqqwqqqqk" LINE LIN COL 05, CONTROL graphcontrol. ADD 1 TO LIN DISPLAY "x x x" LINE LIN COL 05, CONTROL graphcontrol. ADD 1 TO LIN DISPLAY "tqqqqnqqqqu" LINE LIN COL 05, CONTROL graphcontrol. ADD 1 TO LIN DISPLAY "x x x" LINE LIN COL 05, CONTROL graphcontrol. ADD 1 TO LIN DISPLAY "mqqqqvqqqqj" LINE LIN COL 05, CONTROL graphcontrol. *> Double-line graphics MOVE LIN-START TO LIN DISPLAY "LQQQQWQQQQK" LINE LIN COL 20, CONTROL graphcontrol. ADD 1 TO LIN DISPLAY "X X X" LINE LIN COL 20, CONTROL graphcontrol. ADD 1 TO LIN DISPLAY "TQQQQNQQQQU" LINE LIN COL 20, CONTROL graphcontrol. ADD 1 TO LIN DISPLAY "X X X" LINE LIN COL 20, CONTROL graphcontrol. ADD 1 TO LIN DISPLAY "MQQQQVQQQQJ" LINE LIN COL 20, CONTROL graphcontrol.COLOURThe COLOR phrase provides an alternate method for setting video attributes. Integer-8 must be a numeric literal. Identifier-8 must be a numeric data item. It also allows the specification of colors for screen fields and controls. They can be set to different numeric values to express various combinations of colors and video attributes. You may make combinations by adding the appropriate values together. The following color values are accepted:+--------+--------------+-------------+ |Color | Foreground | Background | +--------+--------------+-------------+ |Black | 1 | 32 | |Blue | 2 | 64 | |Green | 3 | 96 | |Cyan | 4 | 128 | |Red | 5 | 160 | |Magenta | 6 | 192 | |Brown | 7 | 224 | |White | 8 | 256 | +--------+--------------+-------------+You may specify other video attributes by adding the following values:
+-------------------------+--------+ |Reverse video | 1024 | |Low intensity | 2048 | |High intensity | 4096 | |Underline | 8192 | |Blink | 16384 | |Protected | 32768 | |Background low-intensity | 65536 | |Background high-intensity| 131072 | +-------------------------+--------+You may also specify high intensity by adding "8" to the foreground color value.
Sample program that demonstrates how COLOR is used. >>SOURCE FREE IDENTIFICATION DIVISION. PROGRAM-ID. COLOR1. DATA DIVISION. WORKING-STORAGE SECTION. 01 wLIN PIC 99 value zero. 01 wCOLOR PIC 999999 value zero. 01 wBlack-Fore PIC 999 value 1. 01 wBlack-Back PIC 999 value 32. 01 wBlue-Fore PIC 999 value 2. 01 wBlue-Back PIC 999 value 64. 01 wGreen-Fore PIC 999 value 3. 01 wGreen-Back PIC 999 value 96. 01 wCyan-Fore PIC 999 value 4. 01 wCyan-Back PIC 999 value 128. 01 wRed-Fore PIC 999 value 5. 01 wRed-Back PIC 999 value 160. 01 wMagenta-Fore PIC 999 value 6. 01 wMagenta-Back PIC 999 value 192. 01 wBrown-Fore PIC 999 value 7. 01 wBrown-Back PIC 999 value 224. 01 wWhite-Fore PIC 999 value 8. 01 wWhite-Back PIC 999 value 256. 01 wReverseVideo PIC 999999 value 1024. 01 wLowIntensity PIC 999999 value 2048. 01 wHighIntensity PIC 999999 value 4096. 01 wUnderline PIC 999999 value 8192. 01 wBlink PIC 999999 value 16384. 01 wProtected PIC 999999 value 32768. 01 wBackground-low-intensity PIC 999999 value 65536. 01 wBackground-high-intensity PIC 999999 value 131072. PROCEDURE DIVISION. ADD 1 to WLIN compute wCOLOR = wCyan-Fore + wWhite-Back + wUnderline DISPLAY FUNCTION CONCATENATE ("XXX COLOR=" wCOLOR " XXXXXXXXX ") AT LINE wLIN COL 001 COLOR wCOLOR. ADD 1 to WLIN compute wCOLOR = wBrown-Fore + wRed-Back + wHighIntensity DISPLAY FUNCTION CONCATENATE ("XXX COLOR=" wCOLOR " XXXXXXXXX ") AT LINE wLIN COL 001 COLOR wCOLOR. ADD 1 to WLIN compute wCOLOR = wBrown-Fore + wRed-Back + wHighIntensity + wReverseVideo DISPLAY FUNCTION CONCATENATE ("XXX COLOR=" wCOLOR " XXXXXXXXX ") AT LINE wLIN COL 001 COLOR wCOLOR. ADD 1 to WLIN compute wCOLOR = wWhite-Fore + wGreen-Back + wBlink DISPLAY FUNCTION CONCATENATE ("XXX COLOR=" wCOLOR " XXXXXXXXX ") AT LINE wLIN COL 001 COLOR wCOLOR. STOP RUN.See ACCEPT data-item, for additional information on the other
WITHclause options.
The optional
ON EXCEPTIONandNOT ON EXCEPTIONclauses may be used to detect and react to the failure or success, respectively, of the screen I/O attempt. See ON EXCEPTION + NOT ON EXCEPTION, for additional information.
When DISPLAY is used with Line and column where multiple variables or literals are used before LINE only the first will be displayed.
If this is needed then the use of CONCATENATE to built more than one element together prior to the display, e.g., DISPLAY FUNCTION CONCATENATE (VARS-1 VARS-2) AT 0201.
When DISPLAY is used without line or column controls only one variable or literal may will appear on a line, so the use of the above example should also be employed.
DISPLAY data-item (Microsoft v1-v2)
DISPLAY data-item Syntax
=======================================================================
DISPLAY { position-spec { identifier-1 }... }
~~~~~~~ { { literal-1 } }
{ { ERASE } }
{ ~~~~~ }
{ ERASE }
~~~~~
[ WITH [ BELL|BEEP ]
~~~~ ~~~~ ~~~~
[ BLANK LINE|SCREEN ]
~~~~~ ~~~~ ~~~~~~
[ ERASE { EOL|EOS } ]
[ ~~~~~ { ~~~ ~~~ } ]
[ { [ TO END OF ] LINE|SCREEN } ]
~~~ ~~~~ ~~~~~~
[ BACKGROUND-COLOR|BACKGROUND-COLOUR IS|= integer-4|identifier-5 ]
~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~
[ FOREGROUND-COLOR|FOREGROUND-COLOUR IS|= integer-5|identifier-6 ]
~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~
[ HIGHLIGHT|LOWLIGHT ]
~~~~~~~~~ ~~~~~~~~
[ BLINK ]
~~~~~
[ REVERSE-VIDEO|REVERSE|REVERSED ]
~~~~~~~~~~~~~ ~~~~~~~ ~~~~~~~~
[ OVERLINE ]
~~~~~~~~
[ UNDERLINE ]
~~~~~~~~~
[ SCROLL [ UP ] [ { integer-6 } LINE|LINES ] ]
[ ~~~~~~ [ ~~ ] [ { identifier-9 } ~~~~ ~~~~~ ] ]
[ [ DOWN ] ]
~~~~
[ CONVERSION ]
~~~~~~~~~~
[ SIZE IS { integer-7 } ]
[ ~~~~ { identifier-8 } ]
[ CONTROL { literal-7 } ]
[ ~~~~~~~ { identifier-7 } ]
[ COLOUR|COLOR IS { integer-8 } ]
[ ~~~~~~ ~~~~~ { identifier-10 } ] ]
[ END-DISPLAY ]
~~~~~~~~~~~
where position-spec is
{ (position-spec-num, position-spec-num) }
{ (,position-spec-num) }
{ (position-spec-num,) }
where position-spec-num is
{ identifier-11 } [ +|- integer-10 ]
{ integer-9 }
=======================================================================
This format of the DISPLAY statement presents data onto a formatted screen using the Microsoft format from v1 and v2 compilers (MsDos).
DIVIDE
DIVIDE INTO
DIVIDE INTO Syntax
=======================================================================
DIVIDE { literal-1 } INTO { identifier-2 [ rounded-phrase ] }...
~~~~~~ { identifier-1 } ~~~~
[ ON SIZE ERROR imperative-statement-1 ]
~~~~ ~~~~~
[ NOT ON SIZE ERROR imperative-statement-2 ]
~~~ ~~~~ ~~~~~
[ END-DIVIDE ]
~~~~~~~~~~
For further clarification, the following examples are provided to be used with the various flavours of the DIVIDE statement when using BY, INTO and GIVING.
--------------------------------------+---+-----+--------------+-------------------+
DIVIDE Operation | A | B | C | D |
--------------------------------------+---+-----+--------------+-------------------+
DIVIDE A INTO B | A | B/A | | |
--------------------------------------+---+-----+--------------+-------------------+
DIVIDE A INTO B GIVING C | A | B | B/A | |
--------------------------------------+---+-----+--------------+-------------------+
DIVIDE A INTO B GIVING C REMAINDER D | A | B | Integer(B/A) | Integer remainder |
--------------------------------------+---+-----+--------------+-------------------+
DIVIDE A BY B GIVING C | A | B | A/B | |
--------------------------------------+---+-----+--------------+-------------------+
DIVIDE A BY B GIVING C REMAINDER D | A | B | Integer(A/B) | Integer remainder |
--------------------------------------+---+-----+--------------+-------------------+
=======================================================================
This format of the DIVIDE statement will divide a numeric value (specified as a literal or numeric data item) into another numeric value (also specified as a literal or numeric data item) and will then replace the contents of one or more receiving data items with the results of that division.
The reserved words
ISandONare optional and may be omitted. The presence or absence of these words has no effect upon the program.Both <identifier-1> and <identifier-2> must be numeric unedited data items and <literal-1> must be a numeric literal.
A division operation will be performed for each <identifier-2>, in turn. Each of the results of those divisions will be saved to the corresponding <identifier-2> data item(s).
Should any <identifier-2> be an integer numeric data item, the result computed when that <identifier-2> is divided by <literal-1> or <identifier-1> will also be an integer — any remainder from that division will be discarded.
The optional
ROUNDED(see ROUNDED) clause available to each <identifier-2> will control how non-integer results will be saved.The optional
ON SIZE ERRORandNOT ON SIZE ERRORclauses may be used to detect and react to the failure or success, respectively, of an attempt to perform a calculation. In this case, failure is defined as being numeric truncation caused by an <identifier-2> with an insufficient number of digit positions available to the left of any implied decimal point, or an attempt to divide by zero. See ON SIZE ERROR + NOT ON SIZE ERROR, for additional information.
DIVIDE INTO GIVING
DIVIDE INTO GIVING Syntax
=======================================================================
DIVIDE { literal-1 } INTO { literal-2 }
~~~~~~ { identifier-1 } ~~~~ { identifier-2 }
GIVING { identifier-3 [ rounded-phrase ] }...
~~~~~~
[ REMAINDER identifier-4 [ rounded-phrase ] ]
~~~~~~~~~
[ ON SIZE ERROR imperative-statement-1 ]
~~~~ ~~~~~
[ NOT ON SIZE ERROR imperative-statement-2 ]
~~~ ~~~~ ~~~~~
[ END-DIVIDE ]
~~~~~~~~~~
=======================================================================
This format of the DIVIDE statement will divide one numeric value (specified as a literal or numeric data item) into another numeric value (also specified as a literal or numeric data item) and will then replace the contents of one or more receiving data items with the results of that division.
The reserved words
ISandONare optional and may be omitted. The presence or absence of these words has no effect upon the program.Both <identifier-1> and <identifier-2> must be numeric unedited data items while both <identifier-3> and <identifier-4> must be numeric (edited or unedited) data items.
Both <literal-1> and <literal-2> must be numeric literals.
If the
REMAINDERclause is coded, there may be only one <identifier-3> specified.The result obtained when the value of <literal-2> or <identifier-2> is divided by the value of <literal-1> or <identifier-1> is computed; this result is then moved into each <identifier-3>, in turn, applying the rules defined by the
ROUNDED(see ROUNDED) clause (if any) for that <identifier-3> to the move.If a
REMAINDERclause is specified, the value of the one and only <identifier-3> (as stated earlier, ifREMAINDERis specified there may only be a single <identifier-3> coded on the statement) after it was assigned a value according to the previous rule will be multiplied by the value of <literal-1> or <identifier-1>; that result is then subtracted from the value of <literal-2> or <identifier-2> and that result is the value which is moved to <identifier-4>.The optional
ON SIZE ERRORandNOT ON SIZE ERRORclauses may be used to detect and react to the failure or success, respectively, of an attempt to perform a calculation. In this case, failure is defined as being an <identifier-2> with an insufficient number of digit positions available to the left of any implied decimal point, or an attempt to divide by zero. See ON SIZE ERROR + NOT ON SIZE ERROR, for additional information.
DIVIDE BY GIVING
DIVIDE BY GIVING Syntax
=======================================================================
DIVIDE { literal-1 } BY { literal-2 }
~~~~~~ { identifier-1 } ~~ { identifier-2 }
GIVING { identifier-3 [ rounded-phrase ] }...
~~~~~~
[ REMAINDER identifier-4 [ rounded-phrase ] ]
~~~~~~~~~
[ ON SIZE ERROR imperative-statement-1 ]
~~~~ ~~~~~
[ NOT ON SIZE ERROR imperative-statement-2 ]
~~~ ~~~~ ~~~~~
[ END-DIVIDE ]
~~~~~~~~~~
=======================================================================
This format of the DIVIDE statement will divide one numeric value (specified as a literal or numeric data item) by another numeric value (also specified as a literal or numeric data item) and will then replace the contents of one or more receiving data items with the results of that division.
The reserved words
ISandONare optional and may be omitted. The presence or absence of these words has no effect upon the program.Both <identifier-1> and <identifier-2> must be numeric unedited data items while both <identifier-3> and <identifier-4> must be numeric (edited or unedited) data items.
Both <literal-1> and <literal-2> must be numeric literals.
If the
REMAINDERclause is coded, there may be only one <identifier-3> specified.The result obtained when the value of <literal-1> or <identifier-1> is divided by the value of <literal-2> or <identifier-2> is computed; this result is then moved into each <identifier-3>, in turn, applying the rules defined by the
ROUNDED(see ROUNDED) clause (if any) for that <identifier-3> to the move.If a
REMAINDERclause is specified, the value of the one and only <identifier-3> (as stated earlier, ifREMAINDERis specified there may only be a single <identifier-3> coded on the statement) after it was assigned a value according to the previous rule will be multiplied by the value of <literal-2> or <identifier-2>; that result is then subtracted from the value of <literal-1> or <identifier-1> and that result is the value which is moved to <identifier-4>.The optional
ON SIZE ERRORandNOT ON SIZE ERRORclauses may be used to detect and react to the failure or success, respectively, of an attempt to perform a calculation. In this case, failure is defined as being an <identifier-2> with an insufficient number of digit positions available to the left of any implied decimal point, or an attempt to divide by zero. See ON SIZE ERROR + NOT ON SIZE ERROR, for additional information.
ENTRY
ENTRY Syntax
=======================================================================
ENTRY [ { STATIC } ] [ WITH { STDCALL } LINKAGE ] literal-1
~~~~~ { ~~~~~~ } ~~~~ { ~~~~~~~ } ~~~~~~~
{ STDCALL } { C }
{ ~~~~~~~ } { ~ }
{ C } { PASCAL }
{ ~ } ~~~~~~
{ PASCAL }
{ ~~~~~~ }
{ EXTERN }
{ ~~~~~~ }
{ mnemonic-name-1 }
[ USING { [ BY { REFERENCE } ] { identifier-1 }... }... ]
~~~~~ { ~~~~~~~~~ }
{ VALUE }
~~~~~
Format 2 (Special purpose and for GO TO )
ENTRY FOR GO TO literal-2
~~~~~ ~~~ ~~ ~~
Note for Fixed format sources, this statement must only be used in area B.
=======================================================================
The ENTRY statement is used to define an alternate entry-point into a subroutine, along with the arguments that subroutine will be expecting.
The reserved word
BYis optional and may be omitted. The presence or absence of this word has no effect upon the program.You may not use an
ENTRYstatement in a nested subprogram, nor may you use it in any form of user-defined function.The
USINGclause defines the arguments the subroutine entry-point supports. This list of arguments must match up against theUSINGclause of anyCALLstatement that will be invoking the subroutine using this entry-point.Each <ENTRY-Argument> specified on the
ENTRYstatement must be defined in the linkage section of the subroutine in which theENTRYstatement exists.The <literal-1> value will specify the entry-point name of the subroutine. It must be specified exactly on
CALLstatements (with regard to the use of upper- and lower-case letters) as it is specified on theENTRYstatement.The meaning of
REFERENCEandVALUEare the same as the equivalent specifications on theCALLstatement (see CALL). Whatever specification will be used for an argument on theCALLto this entry-point should match the specification used in the corresponding <ENTRY-Argument>. The same rules regarding the presence or absence of aBYclause on aCALLstatement apply to the presence or absence of aBYclause on the corresponding argument of theENTRYstatement.The <GO TO> with the ENTRY FOR is an GnuCOBOL special purpose extension for use with various GnuCobol tools.
The
ENTRYstatement when coding using FIXED format source must start within area B only.
An example:
IDENTIFICATION DIVISION.
PROGRAM ID. MAINPROG.
...
DATA DIVISION.
FILE SECTION.
FD INV-FILE.
01 INV-REC.
02 PT-NUM PIC X(10).
02 PT-NAME PIC X(30).
02 BEGIN-QTY PIC 9(6).
02 PRICE-WHSL PIC 9(3)V99.
02 PRICE-RETAIL PIC 9(4)V99.
FD SALES-FILE.
01 SALES-REC.
02 SOLD-PT-NO PIC X(10).
02 SOLD-PART PIC X(30).
02 SOLD-QTY PIC 9(6).
...
PROCEDURE DIVISION.
MAIN-PARA-001.
...
IF SOLD-QTY IS NOT EQUAL TO ZERO
CALL "SUBPRO1-ENTRY" USING INV-REC, SALES-REC.
...
STOP RUN.
Following is the subprogram:
IDENTIFICATION DIVISION.
PROGRAM-ID. SUBPRO1.
...
DATA DIVISION.
FILE SECTION.
FD PRINT-FILE.
01 P-REC PIC X(132).
...
WORKING-STORAGE SECTION.
01 HEADER.
...
01 WRITE-SALES.
02 FILLER PIC X(15) VALUE SPACES.
02 NAME PIC X(30) VALUE SPACES.
02 FILLER PIC X(5) VALUE SPACES.
02 NUM-1 PIC X(10) VALUE SPACES.
02 FILLER PIC X(5) VALUE SPACES.
02 QUANTITY PIC Z(3)9(3) VALUE ZERO.
02 FILLER PIC X(5) VALUE SPACES.
02 GROSS-SALES PIC $Z(10).99 VALUE ZEROS.
02 FILLER PIC X(5) VALUE SPACES.
02 GROSS-PROFIT PIC $9(10).99.
...
LINKAGE SECTION.
01 ORIGINAL.
02 PT-NUM PIC X(10).
02 PT-NAME PIC X(30).
02 START-QTY PIC 9(6).
02 OUR-PRICE PIC 9(3)V99.
02 THEIR-PRICE PIC 9(4)V99.
01 SALES.
02 SOLD-NUM PIC X(10).
02 SOLD-NAME PIC X(30).
02 QTY-SOLD PIC 9(6).
PROCEDURE DIVISION.
SUB-PARA-001.
...
CALC-PARA-100.
ENTRY "SUBPRO1-ENTRY" USING ORIGINAL, SALES.
MULTIPLY QTY-SOLD BY THEIR-PRICE GIVING GROSS-SALES.
SUBTRACT START-QTY FROM QTY-SOLD GIVING QUANTITY.
COMPUTE GROSS-PROFIT = (THEIR-PRICE - OUR-PRICE) * QTY-SOLD.
MOVE PT-NUM TO NUM-1.
MOVE PT-NAME TO NAME.
WRITE P-REC FROM HEADER AFTER ADVANCING 1 LINES.
WRITE P-REC FROM WRITE-SALES AFTER ADVANCING 3 LINES.
GOBACK.
...
EVALUATE
EVALUATE Syntax
=======================================================================
EVALUATE Selection-Subject-1 [ ALSO Selection-Subject-2 ]...
~~~~~~~~ ~~~~
{ WHEN Selection-Object-1 [ ALSO Selection-Object-2 ]...
~~~~ ~~~~
[ imperative-statement-1 ] }...
[ WHEN OTHER
~~~~ ~~~~~
imperative-statement-other ]
[ END-EVALUATE ]
~~~~~~~~~~~~
=======================================================================
EVALUATE Selection Subject Syntax
=======================================================================
{ TRUE }
{ ~~~~ }
{ FALSE }
{ ~~~~~ }
{ expression-1 }
{ identifier-1 }
{ literal-1 }
=======================================================================
EVALUATE Selection Object Syntax
=======================================================================
{ ANY }
{ ~~~ }
{ TRUE }
{ ~~~~ }
{ FALSE }
{ ~~~~~ }
{ partial-expression-1 }
{ }
{ { expression-2 } [ THRU|THROUGH { expression-3 } ] }
{ { identifier-2 } ~~~~ ~~~~~~~ { identifier-3 } }
{ { literal-2 } { literal-3 } }
=======================================================================
The EVALUATE statement provides a means of defining processing that should take place under any number of mutually-exclusive conditions.
The reserved words
THRUandTHROUGHare interchangeable.There must be at least one
WHENclause (in addition to anyWHEN OTHERclause) specified on anyEVALUATEstatement.There must be at least one <Selection-Subject> specified on the
EVALUATEstatement. Any number of additional <Selection-Subject> clauses may be specified, using theALSOreserved word to separate each from the prior.Each
WHENclause (other than theWHEN OTHERclause, if any) must have the same number of <Selection-Object> clauses as there are <Selection-Subject> clauses.When using
THRU, the values on both sides of theTHRUmust be the same class (both numeric, both alphanumeric, etc.).A <partial-expression> is one of the following:
A Class Condition without a leading <identifier-1> (see Class Conditions).
A Sign Condition without a leading <identifier-1> (see Sign Conditions).
A Relation Condition with nothing to the left of the relational operator (see Relation Conditions).
At execution time, each <Selection-Subject> on the
EVALUATEstatement will have its value matched against that of the corresponding <Selection-Object> on aWHENclause, in turn, until:A
WHENclause has each of its <Selection-Object>(s) successfully matched by the corresponding <Selection-Subject>; this will be referred to as the ‘Selected WHEN clause’.The complete list of
WHENclauses (except for theWHEN OTHERclause, if any) has been exhausted. In this case, there is no ‘Selected WHEN Clause’.
If a ‘Selected WHEN Clause’ was identified:
The <imperative-statement-1> (see Imperative Statement) immediately following the ‘Selected WHEN Clause’ will be executed. If the ‘Selected WHEN Clause’ is lacking an <imperative-statement-1>, the first <imperative-statement-1> found after any following
WHENclause will be executed.Once the <imperative-statement-1> has been executed, or no <imperative-statement-1> was found anywhere after the ‘Selected WHEN Clause’, control will proceed to the statement following the
END-EVALUATEor, if there is noEND-EVALUATE, the first statement that follows the next period. If, however, the <imperative-statement-1> included aGO TOstatement, and thatGO TOwas executed, then control will transfer to the procedure named on theGO TOinstead.
If no ‘Selected WHEN Clause’ was identified:
The
WHEN OTHERclause’s <imperative-statement-other> will be executed, if such a clause was coded.Control will then proceed to the statement following the
END-EVALUATEor the first statement that follows the next period if there is noEND-EVALUATE. If,however, the <imperative-statement-other> included aGO TOstatement, and thatGO TOwas executed, then control will transfer to the procedure named on theGO TOinstead.
In order for a <Selection-Subject> to match the corresponding <Selection-Object> on a
WHENclause, at least one of the following must be true:The <Selection-Object> is
ANYThe implied Relation Condition
Selection-Subject = Selection ObjectisTRUE— See Relation Conditions, for the rules on how the comparison will be made.The value of the <Selection-Subject> falls within the range of values specified by the
THRUclause of the <Selection-Object>If the <Selection-Object> is a <partial-expression>, then the conditional expression that would be represented by coding
Selection-Subject Selection-Objectevaluates toTRUE
Here is a sample program that illustrates the EVALUATE statement.
IDENTIFICATION DIVISION. PROGRAM-ID. DEMOEVALUATE. DATA DIVISION. WORKING-STORAGE SECTION. 01 Test-Digit PIC 9(1). 88 Digit-Is-Odd VALUE 1, 3, 5, 7, 9. 88 Digit-Is-Prime VALUE 1, 3, 5, 7. PROCEDURE DIVISION. PERFORM UNTIL EXIT DISPLAY "Enter a digit (0 Quits): " WITH NO ADVANCING ACCEPT Test-Digit IF Test-Digit = 0 EXIT PERFORM END-IF EVALUATE Digit-Is-Odd ALSO Digit-Is-Prime WHEN TRUE ALSO FALSE DISPLAY Test-Digit " is ODD" WITH NO ADVANCING WHEN TRUE ALSO TRUE DISPLAY Test-Digit " is PRIME" WITH NO ADVANCING WHEN FALSE ALSO ANY DISPLAY Test-Digit " is EVEN" WITH NO ADVANCING END-EVALUATE EVALUATE Test-Digit WHEN < 5 DISPLAY " and it's small too" WHEN < 8 DISPLAY " and it's medium too" WHEN OTHER DISPLAY " and it's large too" END-EVALUATE END-PERFORM DISPLAY "Bye!" STOP RUN.Console output when run (user input follows the colons on the prompts for input):
Enter a digit (0 Quits): 1 1 is PRIME and it's small too Enter a digit (0 Quits): 2 2 is EVEN and it's small too Enter a digit (0 Quits): 3 3 is PRIME and it's small too Enter a digit (0 Quits): 4 4 is EVEN and it's small too Enter a digit (0 Quits): 5 5 is PRIME and it's medium too Enter a digit (0 Quits): 6 6 is EVEN and it's medium too Enter a digit (0 Quits): 7 7 is PRIME and it's medium too Enter a digit (0 Quits): 8 8 is EVEN and it's large too Enter a digit (0 Quits): 9 9 is ODD and it's large too Enter a digit (0 Quits): 0 Bye!
EXAMINE
EXAMINE Syntax
=======================================================================
EXAMINE identifier-1
~~~~~~~
{ TALLYING { ALL } literal-1 [ REPLACING BY literal-2 ] }
{ ~~~~~~~~ { ~~~ } ~~~~~~~~~ ~~ }
{ { LEADING } }
{ { ~~~~~~~ } }
{ { UNTIL FIRST } }
{ ~~~~~ ~~~~~ }
{ }
{ REPLACING { ALL } literal-3 BY literal-4 }
{ ~~~~~~~~~ { ~~~ } ~~ }
{ { LEADING } }
{ { ~~~~~~~ } }
{ { [ UNTIL ] FIRST } }
~~~~~ ~~~~~
=======================================================================
The EXAMINE statement is the pre runner for INSPECT which should be used over the pre 1970 Cobol standard EXAMINE, and it is used to count the number of times a specified character appears in a data item and/or to replace a character with another character.
This statement is only available subject to specific dialects being set when running the GnuCOBOL compiler.
In all cases, the description of identifier must be such that its usage is display (explicitly or implicitly).
When identifier represents a non numeric data item, examination starts at the leftmost character and proceeds to the right. Each character in the data item is examined in turn. For purposes of the EXAMINE statement, external floating point items are treated as non numeric data items.
When identifier represents a numeric data item, this data item must consist of numeric characters, and may possess an operational sign. Examination starts at the leftmost character and proceeds to the right. Each character is examined in turn.
If the letter ‘S’ is used in the PICTURE of the data item description to indicate the presence of an operational sign, the sign is ignored by the EXAMINE statement.
Each literal must consist of a single character belonging to a class consistent with that of the identifier; in addition, each literal may be any figurative constant except ALL. If identifier is numeric, each literal must be an unsigned integer or the figurative constant ZERO (ZEROES, ZEROS).
When Format 1 is used, an integral count is created which replaces the value of a special register called TALLY, whose implicit description is that of an unsigned integer of five digits.
When the ALL option is used, this count represents the number of occurrences of literal-1.
When the LEADING option is used, this count represents the number of occurrences of literal-1 prior to encountering a character other than literal-1.
When the UNTIL FIRST option is used, this count represents all characters encountered before the first occurrence of literal-1.
Whether Format 2 is used, or the REPLACING option of Format 1, the replacement rules are the same. They are as follows:
When the ALL option is used, literal-2 is substituted for each occurrence of literal-1.
When the LEADING option is used, the substitution of literal-2 for each occurrence of literal-1 terminates as soon as a character other than literal-1 or the right hand boundary of the data item is encountered.
When the UNTIL FIRST option is used, the substitution of literal-2 terminates as soon as literal-1 or the right hand boundary of the data item is encountered.
EXHIBIT
EXHIBIT Syntax
=======================================================================
EXHIBIT [CHANGED][NAMED] [position-spec] [ERASE] {identifier-1 | literal-1} ...
~~~~~~~ ~~~~~~~ ~~~~~ ~~~~~
[UPON mnemonic-name-1]
~~~~
where position-spec is
{(position-spec-num, position-spec-num)}
{(, position-spec-num) }
{(position-spec-num, ) }
where position-spec-num is
{identifier-2} [{+} integer-2]
{integer-1 } [{-} ]
=======================================================================
The EXHIBIT statement causes an (optionally conditional) display of the literals, and/or identifiers (optionally preceded by the identifier name) specified in the statement for the purposes of debugging.
EXHIBIT is only present to ease migrations, this is an archaic language element in GnuCOBOL (but without the archaic message warning because there is no explicit dialect configuration for that other than the reserved word). Depending on the -std used it will either compile or not. As the standard says about archaic language elements:
it should not be used in new compilation groups because better programming practices exist
The use of DISPLAY is more portable and allows for the same feature-set (with the exception of CHANGED which GnuCOBOL may not support for a long time and with the need of a literal for NAMED). This statement can be removed from any later version.
The reserved words
NAMED,CHANGEDare optional and may be omitted. The presence or absence of these words has no effect upon the program.Each identifier specified in the EXHIBIT statement can be any class of data. TALLY and RETURN-CODE are the only special registers that can be used as identifiers.
Literals and identifiers displayed by the EXHIBIT statement are separated by a space on the displayed line.
Each literal can be any figurative constant other than ALL.
If the literal is numeric, it must be an unsigned integer.
Each execution of an EXHIBIT NAMED statement displays each identifier or literal specified, with each identifier (including any qualifiers and subscripts) followed by a "=" (equal sign) and its current value. They all appear on a single line on the order in which they appear in the statement.
Each execution of an EXHIBIT CHANGED NAMED statement displays each identifier or literal specified, with each identifier (including any qualifiers and subscripts) followed by a "=" (equal sign) and its current value. They all appear on a single line on the order in which they appear in the statement. However, the display for each identifier (name and value) is conditional on the value of that identifier having changed since the last execution of the current EXHIBIT statement. If one or more of the identifier values have not changed, neither the name nor the value is printed for those identifiers. If none of the identifier values has changed, and no literals are specified, no display takes place (display of a blank line is suppressed).
Each execution of an EXHIBIT CHANGED statement displays the current value of each identifier or literal specified. They all appear on a single line on the order in which they appear in the statement. However, the value display for each identifier is conditional on the value of that identifier having changed since the last execution of the current EXHIBIT statement. If one or more of the identifier values have not changed, the value for those identifiers are not printed and spaces are inserted instead. If none of the identifier values has changed, and no literals are specified, a blank line is displayed (display of a blank line is not suppressed).
Each execution of an EXHIBIT statement with neither the CHANGED nor the NAMED option displays each identifier or literal specified. They all appear on a single line in the order in which they appear in the statement.
An EXHIBIT statement is the same as an EXHIBIT NAMED statement.
ERASE is a display attribute which got into GnuCOBOL when MS-COBOL support was increased, it is not yet implemented.
The CHANGED clause is not yet implemented but recognised by GnuCOBOL.
The UPON mnemonic-name-1 clause is not yet implemented but recognised by GnuCOBOL.
EXIT
EXIT Syntax
=======================================================================
EXIT [ { PROGRAM [ RETURNING|GIVING { identifier-1 } ] } ]
~~~~ { ~~~~~~~~ ~~~~~~~~~ ~~~~~~ { literal-1 } }
{ }
{ }
{ FUNCTION }
{ ~~~~~~~~ }
{ }
{ PERFORM [ CYCLE ] }
{ ~~~~~~~ ~~~~~ }
{ }
{ SECTION }
{ ~~~~~~~ }
{ PARAGRAPH }
~~~~~~~~~
=======================================================================
The EXIT statement is a multi-purpose statement; it may provide a common end point for a series of procedures, exit an in-line PERFORM, paragraph or section or it may mark the logical end of a subprogram, returning control back to the calling program.
The
EXIT PROGRAMstatement is not legal anywhere within a user-defined function.The
EXIT FUNCTIONstatement cannot be used anywhere within a subroutine.Neither
EXIT PROGRAMnorEXIT FUNCTIONmay be used within aUSE GLOBALroutine inDECLARATIVES(see DECLARATIVES).The following points describe the
EXITstatement with none of the optional clauses:When this form of an
EXITstatement is used, it must be the only statement in the procedure (paragraph or section) in which it occurs. This is not enforced in GnuCOBOL.This usage of the
EXITstatement simply provides a common “GO TO” end point for a series of procedures, as may be seen in the following example:01 Switches. 05 Input-File-Switch PIC X(1). 88 EOF-On-Input-File VALUE ``Y'' FALSE ``N''. … SET EOF-On-Input-File TO FALSE. PERFORM 100-Process-A-Transaction THRU 199-Exit UNTIL EOF-On-Input-File. … 100-Process-A-Transaction. READ Input-File AT END SET EOF-On-Input-File TO TRUE GO TO 199-Exit END-READ. IF Input-Rec of Input-File = SPACES GO TO 199-Exit *> IGNORE BLANK RECORDS! END-IF. <<process the record just read>> 199-Exit. EXIT.In this case, the
EXITstatement takes no other run-time action.
The following points apply to the
EXIT PARAGRAPHandEXIT SECTIONstatements:If an
EXIT PARAGRAPHstatement orEXIT SECTIONstatement resides in a paragraph within the scope of a proceduralPERFORM(see Procedural PERFORM), control will be returned back to thePERFORMfor evaluation of anyTIMES,VARYINGand/orUNTILclauses.If an
EXIT PARAGRAPHstatement orEXIT SECTIONstatement resides outside the scope of a proceduralPERFORM, control simply transfers to the first executable statement in the next paragraph (EXIT PARAGRAPH) or section (EXIT SECTION).The following shows how the previous example could have been coded without a
GO TOby utilizing anEXIT PARAGRAPHstatement.01 Switches. 05 Input-File-Switch PIC X(1). 88 EOF-On-Input-File VALUE ``Y'' FALSE ``N''. … SET EOF-On-Input-File TO FALSE. PERFORM 100-Process-A-Transaction UNTIL EOF-On-Input-File. … 100-Process-A-Transaction. READ Input-File AT END SET EOF-On-Input-File TO TRUE EXIT PARAGRAPH END-READ. IF Input-Rec of Input-File = SPACES EXIT PARAGRAPH *> IGNORE BLANK RECORDS! END-IF. <<process the record just read>>
The following points apply to the
EXIT PERFORMandEXIT PERFORM CYCLEstatements:The
EXIT PERFORMandEXIT PERFORM CYCLEstatements are intended to be used in conjunction with an in-linePERFORMstatement (see Inline PERFORM).An
EXIT PERFORM CYCLEstatement will terminate the current iteration of the in-linePERFORM, giving control to anyTIMES,VARYINGand/orUNTILclauses for them to determine if another cycle needs to be performed.An
EXIT PERFORMstatement will terminate the in-line PERFORM outright, transferring control to the first statement following theEND-PERFORM(if there is one) or to the next sentence following thePERFORMif there is noEND-PERFORM.This last example shows the final modification to the previous examples by using an in-line
PERFORMalong withEXIT PERFORMandEXIT PERFORM CYCLEstatements:PERFORM FOREVER READ Input-File AT END EXIT PERFORM END-READ IF Input-Rec of Input-File = SPACES EXIT PERFORM CYCLE *> IGNORE BLANK RECORDS! END-IF <<process the record just read>> END PERFORM
The following points apply to the
EXIT PROGRAMandEXIT FUNCTIONstatements:The
EXIT PROGRAMandEXIT FUNCTIONstatements terminate the execution of a subroutine (i.e. a program that has been CALLed by another) or user-defined function, respectively, returning control back to the calling program.An
EXIT PROGRAMstatement returns control back to the statement following theCALL(see CALL) of the subprogram. AnEXIT FUNCTIONstatement returns control back to the processing of the statement in the calling program that invoked the user-defined function.For
EXIT PROGRAMstatement usage ofRETURNINGstatement orGIVINGstatement will provide value defined by indentifer-1 or literal-1 back to the calling routine.If executed by a main program, neither the
EXIT PROGRAMnorEXIT FUNCTIONstatements will take any action.The COBOL2002 standard has made a common extension to the COBOL language — the
GOBACKstatement (see GOBACK) — a standard language element; theGOBACKstatement should be strongly considered as the preferred alternative to bothEXIT PROGRAMandEXIT FUNCTIONfor new subprograms.
FREE
FREE Syntax
=======================================================================
FREE { [ ADDRESS OF ] identifier-1 }...
~~~~ ~~~~~~~
=======================================================================
The FREE statement releases memory previously allocated to the program by the ALLOCATE statement (see ALLOCATE).
The
ADDRESS OFclause is optional and may be omitted. The presence or absence of this clause has no effect upon the program.<identifier-1> must have a
USAGE(see USAGE) ofPOINTER, or it must be an 01-level data item with theBASED(see BASED) attribute.If <identifier-1> is a
USAGE POINTERdata item and it contains a valid address, theFREEstatement will release the memory block the pointer references. In addition, anyBASEDdata items that the pointer was used to provide an address for will become un-based and therefore unusable. If <identifier-1> did not contain a valid address, no action will be taken.If <identifier-1> is a
BASEDdata item and that data item is currently based (meaning it currently has memory allocated to it), its memory is released and <identifier-1> will become un-based and therefore unusable. If <identifier-1> was not based, no action will be taken.
GENERATE
GENERATE Syntax
=======================================================================
GENERATE { report-name-1 }
~~~~~~~~ { identifier-1 }
=======================================================================
The GENERATE statement presents data to a report.
The following points apply when <identifier-1> is specified:
<identifier-1> must be the name of a
DETAIL(see RWCS Lexicon) report group.If necessary, <identifier-1> may be qualified with a report name.
The file in whose
FDaREPORTclause exists for the report in which <identifier-1> is a detail group must be opened forOUTPUTorEXTENDat the time theGENERATEis executed. See OPEN, for information on file open modes.The report in which <identifier-1> is a
DETAILgroup must have been successfully initiated via theINITIATEstatement (see INITIATE) and not yet terminated via theTERMINATEstatement (see TERMINATE) at the time theGENERATEis executed.If at least one
GENERATEstatement of this form is executed against a report, the report is said to be a detail report. If noGENERATEstatements of this form are executed against a report, the report is said to be a summary report.
The following points apply when <report-name-1> is specified:
<report-name-1> must be the name of a report having an
RDdefined for it in the report section.There must be at least one
CONTROL(see RWCS Lexicon) group defined for <report-name-1>.There cannot be more than one
DETAILgroup defined for <report-name-1>.The file in whose
FDaREPORT report-name-1clause exists must be open forOUTPUTorEXTENDat the time the GENERATE is executed.<report-name-1> must have been successfully initiated (via
INITIATE report-name-1) and not yet terminated (via TERMINATE) at the time theGENERATEis executed. See OPEN, for information on file open modes.The
DETAILgroup which is defined for <report-name-1> will be processed but will not actually be presented to any report page. This will allow summary processing to take place. If allGENERATEstatements are of this form, the report is said to be a summary report. If at least oneGENERATE identifier-1is executed, the report is considered to be a detail report.
When the first
GENERATEstatement for a report is executed, the contents of all control fields are saved so they may be referenced during the processing of subsequentGENERATEstatements.When, during the processing of a subsequent
GENERATE, it is determined that a control field has changed value (ie. a control break has occurred), the appropriate control footing and control heading processing will take place and a snapshot of the current values of all control fields will again be saved.
GOBACK
GOBACK Syntax
=======================================================================
GOBACK [ RETURNING|GIVING { literal-1 } ]
~~~~~~ ~~~~~~~~~ ~~~~~~ { identifier-1 }
=======================================================================
The GOBACK statement is used to logically terminate an executing program.
If executed within a subprogram (i.e. a subroutine or user-defined function),
GOBACKbehaves like anEXIT PROGRAMorEXIT FUNCTIONstatement, respectively.If executed within a main program,
GOBACKwill act as aSTOP RUNstatement.The optional
RETURNINGclause provides the opportunity to return a numeric value to the operating system (technically, an exit status The manner in which the exit status value is interrogated by the operating system varies. Windows can use%ERRORLEVEL%to query the exit status while Unix shells such assh,bashandkshcan query the exit status as$?. Other Unix shells may have different ways to access the exit status.
GO TO
Simple GO TO
Simple GO TO Syntax
=======================================================================
GO TO procedure-name-1
~~
GO TO ENTRY literal-1
~~ ~~~~~
=======================================================================
This form of the GO TO statement unconditionally transfers control in a program to the first executable statement within the specified <procedure-name-1>.
The reserved word
TOis optional and may be omitted. The presence or absence of this word has no effect upon the program.If this format of the
GO TOstatement appears in a consecutive sequence of imperative statements (see Imperative Statement) within a sentence, it must be the final statement in the sentence.If a
GO TOis executed within the scope of…...an in-line
PERFORM(see PERFORM), thePERFORMis terminated as control of execution transfers to <procedure-name-1>....a procedural
PERFORM(see PERFORM), and <procedure-name-1> lies outside the scope of thatPERFORM, thePERFORMis terminated as control of execution transfers to <procedure-name-1>....a
MERGEstatement (see MERGE)OUTPUT PROCEDUREor within the scope of either anINPUT PROCEDUREorOUTPUT PROCEDUREof aSORTstatement (see File SORT), and <procedure-name-1> lies outside the scope of that procedure, theSORTorMERGEoperation is terminated as control of execution transfers to <procedure-name-1>. Any sorted or merged data accumulated to that point is lost.
A
GO TO ENTRYis an GnuCOBOL special purpose extension for use with various GnuCobol tools and is not part of any current ISO standard. See alsoENTRY.The
GO TO ENTRYformat has to be used together withENTRY FOR GO TO.
GO TO DEPENDING ON
GO TO DEPENDING ON Syntax
=======================================================================
GO TO {procedure-name-1}... DEPENDING ON identifier-1
~~ ~~~~~~~~~
GO TO ENTRY {literal-1}... DEPENDING ON identifier-1
~~ ~~~~~ ~~~~~~~~~
=======================================================================
This form of the GO TO statement will transfer control to any one of a number of specified procedure names depending on the numeric value of the identifier specified on the statement.
The reserved word
TOis optional and may be omitted. The presence or absence of this word has no effect upon the program but does help with read-ability.The
PICTURE(see PICTURE) and/orUSAGE(see USAGE) of the specified <identifier-1> must be such as to define it as a numeric, unedited, preferably unsigned integer data item.If the value of <identifier-1> has the value 1, control will be transferred to the 1st specified procedure name. If the value is 2, control will transfer to the 2nd procedure name, and so on.
The
GO TO ENTRY ... DEPENDING ONformat has to be used together withENTRY FOR GO TO.If control of execution is transferred to a procedure named on the statement, and the
GO TOis executed within the scope of…...an in-line
PERFORM(see PERFORM), thePERFORMis terminated as control of execution transfers to the procedure named on the statement....a procedural
PERFORM(see PERFORM), and <procedure-name-1> lies outside the scope of thatPERFORM, thePERFORMis terminated as control of execution transfers to the procedure named on the statement....a
MERGEstatement (see MERGE)OUTPUT PROCEDUREor within the scope of either anINPUT PROCEDUREorOUTPUT PROCEDUREof aSORTstatement (see File SORT), and <procedure-name-1> lies outside the scope of that procedure, theSORTorMERGEoperation is terminated as control of execution transfers to the procedure named on the statement. Any sorted or merged data accumulated to that point is lost.
If the value of <identifier-1> is less than 1 or exceeds the total number of procedure names specified on the statement, control will simply fall through into the next statement following the
GO TO.The following example shows how
GO TO ... DEPENDING ONmay be used in a real application situation, and compares it against an alternative —EVALUATE(see EVALUATE).GO TO DEPENDING ON EVALUATE GO TO ACCT-TYPE-1 ACCT-TYPE-2 ACCT-TYPE-3 DEPENDING ON Acct-Type. <<< Invalid Acct Type >>> GO TO All-Done. Acct-Type-1. <<< Handle Acct Type 1 >>> GO TO All-Done. Acct-Type-2. <<< Handle Acct Type 2 >>> GO TO All-Done. Acct-Type-3. <<< Handle Acct Type 3 >>> All-Done.EVALUATE Acct-Type WHEN 1 <<< Handle Acct Type 1 >>> WHEN 2 <<< Handle Acct Type 2 >>> WHEN 3 <<< Handle Acct Type 3 >>> WHEN OTHER <<< Invalid Acct Type >>> END-EVALUATE.Current programming philosophy would prefer the use of the
EVALUATEstatement to that of this form of theGO TOstatement.
IF
IF Syntax
=======================================================================
IF conditional-expression
~~
THEN { imperative-statement-1 }
{ NEXT SENTENCE }
~~~~ ~~~~~~~~
[ ELSE { imperative-statement-2 } ]
~~~~ { NEXT SENTENCE }
~~~~ ~~~~~~~~
[ END-IF ]
~~~~~~
=======================================================================
The IF statement is used to conditionally execute an imperative statement (see Imperative Statement) or to select one of two different imperative statements to execute based upon the TRUE/FALSE value of a conditional expression.
The reserved word
THENis optional and may be omitted. The presence or absence of this word has no effect upon the program.You cannot use both
NEXT SENTENCEand theEND-IFscope terminator in the sameIFstatement.If <conditional-expression> evaluates to
TRUE, <imperative-statement-1> will be executed regardless of whether or not anELSEclause is present. Once <imperative-statement-1> has been executed, control falls into the first statement following theEND-IFor to the first statement of the next sentence if there is noEND-IFclause.If the optional
ELSEclause is present and conditional-expression evaluates to false, then (and only then) <imperative-statement-2> will be executed. Once <imperative-statement-2> has been executed, control falls into the first statement following theEND-IFor to the first statement of the next sentence if there is noEND-IFclause.The clause
NEXT SENTENCEmay be substituted for either imperative-statement, but not both. If control reaches aNEXT SENTENCEclause due to the truth or falsehood of <conditional-expression>, control will be transferred to the first statement of the next sentence found in the program (the first statement after the next period).NEXT SENTENCEwas needed for COBOL programs that were coded according to pre-1985 standards that wish to nest oneIFstatement inside another. See Use of VERB/END-VERB Constructs, for an explanation of whyNEXT SENTENCEwas necessary.Programs coded for 1985 (and beyond) standards don’t need it, instead using the explicit scope-terminator
END-IFto inform the compiler where <imperative-statement-2> (or <imperative-statement-1> if there is noELSEclause coded) ends. New GnuCOBOL programs should be coded to use theEND-IFscope terminator forIFstatements. See Use of VERB/END-VERB Constructs, for additional information.
INITIALIZE
INITIALIZE Syntax
=======================================================================
INITIALIZE|INITIALISE identifier-1...
~~~~~~~~~~ ~~~~~~~~~~
[ WITH FILLER ]
~~~~~~
[ { category-name-1 } TO VALUE ]
{ ALL } ~~~~~
~~~
[ THEN REPLACING { category-name-2 DATA BY
~~~~~~~~~ ~~
[ LENGTH OF ] { literal-1 } }... ]
~~~~~~ { identifier-1 }
[ THEN TO DEFAULT ]
~~~~~~~
=======================================================================
The INITIALIZE statement initializes each <identifier-1> with certain specific values, depending upon the options specified.
The reserved words
DATA,OF,THEN,TOandWITHare optional and may be omitted. The presence or absence of these words has no effect upon the program.The reserved words
INITIALIZEandINITIALISEare interchangeable.The
WITH FILLER,REPLACINGandDEFAULTclauses are meaningful only if <identifier-1> is a group item. They are accepted if it’s an elementary item, but will serve no purpose. TheVALUEclause is meaningful in both cases.A <category-name-1> and/or <category-name-2> may be any of the following:
- ALPHABETIC
-
The
PICTURE(see PICTURE) of the data item only containsAsymbols. - ALPHANUMERIC
-
The
PICTUREof the data item contains onlyXor a combination ofAand9symbols. - ALPHANUMERIC-EDITED
-
The
PICTUREof the data item contains onlyXor a combination ofAand9symbols plus at least oneB,0(zero) or/symbol. - NUMERIC
-
The data item is one that is described with a picture less
USAGE(see USAGE) or has aPICTUREcomposed of nothing butP,9,SandVsymbols. - NUMERIC-EDITED
-
The
PICTUREof the data item contains nothing but the symbol9and at least one of the editing symbols$,+,-,CR,DB,.,,,*orZ. - NATIONAL
-
The data item is one containing nothing but the
Nsymbol. - NATIONAL-EDITED
-
The data item contains nothing but
N,B,/and0symbols.
From the sequence of <identifier-1> data items specified on the
INITIALIZEstatement, a list of initialized fields referred to as the field list in the remainder of this section, will include:Every <identifier-1> that is an elementary item, including any that may have the
REDEFINES(see REDEFINES) clause in their descriptions.Every non-
FILLERelementary item subordinate to <identifier-1>, provided that elementary item neither contains aREDEFINESclause in its definition nor belongs to a group item subordinate to <identifier-1> which contains aREDEFINESclause in its definition.If the optional
WITH FILLERclause is included on theINITIALIZEstatement, then every FILLER elementary item subordinate to each <identifier-1> will be included as well, provided that elementary item neither contains aREDEFINESclause in its definition nor belongs to a group item subordinate to <identifier-1> which contains aREDEFINESclause in its definition..
Once a field list has been determined, each item in that field list will be initialized as if an individual
MOVE(see MOVE) statement to that effect had been coded. The rules for initialization are as follows:If no
VALUE,REPLACINGorDEFAULTclauses are coded, each member of the field list will be initialized as if the figurative constantZERO(if the field list item is numeric or numeric-edited) orSPACES(otherwise) were being moved to it.If a
VALUEclause is specified on theINITIALIZEstatement, each qualifying member of the field list having a compile-timeVALUE(see VALUE) specified in its definition will be initialized to that value. Field list members withVALUEclauses will qualify for this treatment as follows:If the
ALLkeyword was specified on theVALUEclause, all members of the field list withVALUEclauses will qualify.If <category-name-1> is specified instead of
ALL, only those members of the field list withVALUEclauses that also meet the criteria set down for the specified <category-name> (see the list above) will qualify.If you need to apply
VALUEinitialization to multiple <category-name-1> values, you will need to use multipleINITIALIZEstatements.
If a
REPLACINGclause is specified on theINITIALIZEstatement, each qualifying member of the field list that was not already initialized by aVALUEclause, if any, will be initialized to the specified <literal-1> or <identifier-1> value.Only those as-yet uninitialized list members meeting the criteria set forth for the specified <category-name-2> will qualify for this initialization.
If you need to apply
REPLACINGinitialization to multiple <category-name-2> values, you may repeat the syntax after the reserved wordREPLACING, as necessary.If a
DEFAULTclause is specified, any remaining uninitialized members of the field list will be initialized according to the default for their class (numeric and numeric-edited are initialized toZERO, all others are initialized toSPACES).The following example may help your understanding of how the
INITIALIZEstatement works. The sample code makes use of theCOBDUMPprogram to dump the storage that is (or is not) being initialized. See section “COBDUMP” in GnuCOBOL Sample Programs, for a source and cross-reference listing of theCOBDUMPprogram.IDENTIFICATION DIVISION. PROGRAM-ID. DemoInitialize. DATA DIVISION. WORKING-STORAGE SECTION. 01 Item-1. 05 I1-A VALUE ALL '*'. 10 FILLER PIC X(1). 10 I1-A-1 PIC 9(1) VALUE 9. 05 I1-B USAGE BINARY-CHAR. 05 I1-C PIC A(1) VALUE 'C'. 05 I1-D PIC X/X VALUE 'ZZ'. 05 I1-E OCCURS 2 TIMES PIC 9. PROCEDURE DIVISION. 000-Main. DISPLAY "MOVE HIGH-VALUES TO Item-1" PERFORM 100-Init-Item-1 CALL "COBDUMP" USING Item-1 DISPLAY " " DISPLAY "INITIALIZE Item-1" INITIALIZE Item-1 CALL "COBDUMP" USING Item-1 PERFORM 100-Init-Item-1 DISPLAY " " DISPLAY "INITIALIZE Item-1 WITH FILLER" MOVE HIGH-VALUES TO Item-1 INITIALIZE Item-1 WITH FILLER CALL "COBDUMP" USING Item-1 PERFORM 100-Init-Item-1 DISPLAY " " DISPLAY "INITIALIZE Item-1 ALL TO VALUE" MOVE HIGH-VALUES TO Item-1 INITIALIZE Item-1 ALPHANUMERIC TO VALUE CALL "COBDUMP" USING Item-1 PERFORM 100-Init-Item-1 DISPLAY " " DISPLAY "INITIALIZE Item-1 REPLACING NUMERIC BY 1" MOVE HIGH-VALUES TO Item-1 INITIALIZE Item-1 REPLACING NUMERIC BY 1 CALL "COBDUMP" USING Item-1 PERFORM 100-Init-Item-1 DISPLAY " " STOP RUN . 100-Init-Item-1. MOVE HIGH-VALUES TO Item-1 .When executed, this program produces the following output:
MOVE HIGH-VALUES TO Item-1 <-Addr-> Byte <---------------- Hexadecimal ----------------> <---- Char ----> ======== ==== =============================================== ================ 00404058 1 FF FF FF FF FF FF FF FF FF ......... INITIALIZE Item-1 <-Addr-> Byte <---------------- Hexadecimal ----------------> <---- Char ----> ======== ==== =============================================== ================ 00404058 1 FF 30 00 20 20 2F 20 30 30 .0. / 00 INITIALIZE Item-1 WITH FILLER <-Addr-> Byte <---------------- Hexadecimal ----------------> <---- Char ----> ======== ==== =============================================== ================ 00404058 1 20 30 00 20 20 2F 20 30 30 0. / 00 INITIALIZE Item-1 ALL TO VALUE <-Addr-> Byte <---------------- Hexadecimal ----------------> <---- Char ----> ======== ==== =============================================== ================ 00404058 1 2A 2A FF 43 5A 5A 20 FF FF **.CZZ .. INITIALIZE Item-1 REPLACING NUMERIC BY 1 <-Addr-> Byte <---------------- Hexadecimal ----------------> <---- Char ----> ======== ==== =============================================== ================ 00404058 1 FF 31 01 FF FF FF FF 31 31 .1.....11
INITIATE
INITIATE Syntax
=======================================================================
INITIATE { report-name-1 }...
~~~~~~~~
=======================================================================
The INITIATE statement starts Report-Writer Control System (RWCS) processing for a report.
Each <report-name-1> must be the name of a report having an
RD(see REPORT SECTION) defined for it.The file in whose
FD(see File/Sort-Description) aREPORT report-name-1clause exists must be open forOUTPUTorEXTENDat the time theINITIATEstatement is executed. See OPEN, for more information on file open modes.The
INITIATEstatement will initialize all of the following for each report named on the statement:All sum counters, if any, will be set to 0
The report’s
LINE-COUNTERspecial register (see Special Registers) will be set to 0The report’s
PAGE-COUNTERspecial register will be set to 1
No report content will actually presented to the report file as a result of a successful
INITIATEstatement — that will not occur until the firstGENERATEstatement (see GENERATE) is executed.
INSPECT
INSPECT Syntax
=======================================================================
INSPECT { literal-1 }
~~~~~~~ { identifier-1 }
{ function-reference-1 }
[ TALLYING { identifier-2 FOR { ALL|LEADING|TRAILING { literal-2 } }
~~~~~~~~ ~~~ { ~~~ ~~~~~~~ ~~~~~~~~ { identifier-3 } }
{ CHARACTERS }
~~~~~~~~~~
[ | { AFTER|BEFORE } INITIAL { literal-3 } | ] }... ]
| ~~~~~ ~~~~~~ { identifier-4 } |
[ REPLACING { { { ALL|FIRST|LEADING|TRAILING { literal-4 } }
~~~~~~~~~ { { ~~~ ~~~~~ ~~~~~~~ ~~~~~~~~ { identifier-5 } }
{ CHARACTERS }
{ ~~~~~~~~~~ }
BY { [ ALL ] literal-5 }
~~ { ~~~ }
{ identifier-6 }
[ | { AFTER|BEFORE } INITIAL { literal-6 } | ] }... ]
| ~~~~~ ~~~~~~ { identifier-7 } |
[ CONVERTING { { literal-7 } TO { literal-8 }
~~~~~~~~~~ { identifier-8 } ~~ { identifier-9 }
[ | { AFTER|BEFORE } INITIAL { literal-9 } | ] ]
| ~~~~~ ~~~~~~ { identifier-10 } |
=======================================================================
The INSPECT statement is used to perform various counting and/or data-alteration operations against strings.
The reserved word
INITIALis optional and may be omitted. The presence or absence of this words has no effect upon the program.If a
CONVERTINGclause is specified, neither theTALLYINGnorREPLACINGclauses may be used.If either the
TALLYINGorREPLACINGclauses are specified, theCONVERTINGclause cannot be used.If both the
TALLYINGandREPLACINGclauses are specified, they must be specified in the order shown.All literals and identifiers must be explicitly or implicitly defined as alphanumeric or alphabetic.
If <function-reference-1> is specified, it must be an invocation of an intrinsic function that returns a string result. Additionally, only the
TALLYINGclause may be specified.If <literal-1> is specified, only the
TALLYINGclause may be specified.Whichever is specified — <literal-1>, <identifier-1> or <function-reference-1> — that item will be referred to in the discussions that follows as the ‘inspect subject’.
The three optional clauses control the operation of this statement as follows:
The
CONVERTINGclause replaces one or more individual characters found in the inspect subject with a different character in much the same manner as is possible with theTRANSFORMstatement (see TRANSFORM).The
REPLACINGclause replaces one or more sub strings located in the inspect subject with a different, but equally-sized replacement sub string. If you need to replace a sub string with another of a different length, consider using either theSUBSTITUTEintrinsic function (see SUBSTITUTE) or theSUBSTITUTE-CASEintrinsic function (see SUBSTITUTE-CASE).The
TALLYINGclause counts the number of occurrences of one or more strings of characters in the inspect subject.
The optional
INITIALclauses may be used to limit the range of characters in the inspect subject that theCONVERTING,REPLACINGorTALLYINGinstruction in which they occur will apply. We call this the ‘target range’ of the inspect subject. The target range is defined as follows:If there is no
INITIALclause specified, the target range is the entire inspect subject.Either a
BEFOREphrase, anAFTERphrase or both may be specified. They may be specified in any order.The starting point of the target range will be the first character following the sub string identified by the
AFTERspecification. The ending point will be the last character immediately preceding the sub string identified by theBEFOREspecification.If no
AFTERis specified, the first character position of the target range will be character position #1 of the inspect subject.If no
BEFOREis specified, the last character position of the target range will be the last character position of the inspect subject.
The following points apply to the use of the
TALLYINGclause:While there will typically be only be a single set of counting instructions on an
INSPECT:INSPECT Character-String TALLYING C-ABC FOR ALL "ABC"There could be multiple counting instructions specified:
INSPECT Character-String TALLYING C-ABC FOR ALL "ABC" C-BCDE FOR ALL "BCDE"When there are multiple instructions, the one specified first will take priority over the one specified second, (and so forth) as the
INSPECTproceeds forward through the inspect subject, character-by-character.With the above example, if the inspect subject were
--ABCDEF----BCDEF--, the final result of the counting would be thatC-ABCwould be incremented by 1 whileC-BCDEwould be incremented only once; although the human eye clearly sees two ‘BCDE’ sequences, theINSPECT ... TALLYINGwould only “see” the second — the first would have been processed by the first (higher-priority) counting instruction.Each set of counting instructions contains the following information:
A target range, specified by the presence of an
AFTER INITIALand/orBEFORE INITIALclause; the rules for specifying target ranges were covered previously.A Target Sub string — this is a sequence of characters to be located somewhere in the inspect subject and counted. Target sub strings may be defined as a literal value (figurative constants are allowed) or by the contents of an identifier. If the target sub string is specified as a figurative constant, it will be assumed to have a length of one (‘
1’) character. The keywords before the literal or identifier control how many target sub strings could be identified from that replacement instruction, as follows:ALL— identifies every possible target sub string that occurs within the target range. There are three occurrences ofALL 'XX'found inaXXabbXXccXXdd.LEADING— identifies only an occurrence of the target sub string found either at the first character position of the target range or immediately following a previously-found occurrence. There are no occurrences ofLEADING 'XX'found inaXXabbXXccXXdd, but there is one occurrence ofLEADING 'a'(the first character).TRAILING— identifies only an occurrence of the target sub string found either at the very end of the target range or toward the end, followed by nothing but other occurrences. There are no occurrences ofLEADING 'XX'found inaXXabbXXccXXdd, but there are two occurrences ofTRAILING 'd'.The
CHARACTERSoption will match any one single character, regardless of what that character is.
<identifier-2> will be incremented by 1 each time the target sub string is found within the target range of the inspect subject. The
INSPECTstatement will not zero-out <identifier-2> at the start of execution of theINSPECT— it is the programmer’s responsibility to ensure that all <identifier-2> data items are properly initialized to the desired starting values prior to execution of theINSPECT.
The following points apply to the use of the
REPLACINGclause:While there will typically be only be a single set of replacement instructions on an
INSPECT:INSPECT Character-String REPLACING ALL "ABC" BY "DEF"There could be multiple replacement instructions:
INSPECT Character-String REPLACING ALL "ABC" BY "DEF" ALL "BCDE" BY "WXYZ"When there are multiple replacement instructions, the one specified first will take priority over the one specified second, (and so forth) as the
INSPECTproceeds forward through the inspect subject, character-by-character.With the above example, if the inspect subject were
--ABCDEF----BCDEF--, the final result of the replacement would be--DEFDEF----WXYZF--.Each set of replacement instructions contains the following information:
A target range, specified by the presence of an
AFTER INITIALand/orBEFORE INITIALclause; the rules for specifying target ranges were covered previously.A Target Sub string — this is a sequence of characters to be located somewhere in the inspect subject and subsequently replaced with a new value. Target sub strings, which are specified before the
BYkeyword, may be defined as a literal value (figurative constants are allowed) or by the contents of an identifier. If the target sub string is specified as a figurative constant, it will be assumed to have a length of one (‘1’) character. The keywords before the literal or identifier control how many target sub strings could be identified from that replacement instruction, as follows:ALL— identifies every possible target sub string that occurs within the target range. There are three occurrences ofALL 'XX'found inaXXabbXXccXXdd.FIRST— the first occurrence of the target sub string found within the target range. TheFIRST 'XX'found inaXXabbXXccXXddwould be the one found between the ‘a’ and ‘b’ characters.LEADING— an occurrence of the target sub string found either at the first character position of the target range or immediately following a previously-found occurrence. There are no occurrences ofLEADING 'XX'found inaXXabbXXccXXdd, but there is one occurrence ofLEADING 'a'(the first character).TRAILING— an occurrence of the target sub string found either at the very end of the target range or toward the end, followed by nothing but other occurrences. There are no occurrences ofLEADING 'XX'found inaXXabbXXccXXdd, but there are two occurrences ofTRAILING 'd'.The
CHARACTERSoption will match any one single character. When you use this option, the replacement sub string (see the next item) must be exactly one character in length.A Replacement Sub string — this is the sequence of characters that should replace the target sub string. Replacement sub strings are specified after the
BYkeyword. They too may be specified as a literal, either with or without anALLprefix (again, figurative constants are allowed) or the value of an identifier. If a figurative constant is coded, theALLkeyword will be assumed, even if it wasn’t specified. Literals withoutALLwill either be truncated or padded with spaces on the right to match the length of the target sub string. Literals withALLor figurative constants will be repeated as necessary to match the length of the target sub string. Identifiers specified as replacement sub strings must be defined with a length equal to that of the target sub string.
When both
REPLACINGandTALLYINGare specified:The
INSPECTstatement will make a single pass through the sequence of characters comprising the inspect subject. As the pointer to the current inspect target character reaches a point where it falls within the explicit or implicit target ranges specified on the operational instructions of the two clauses, the actions specified by those instructions will become eligible to be taken. As the character pointer reaches a point where it falls past the end of target ranges, the instructions belonging to those target ranges will become disabled.At any point in time, there may well be multiple
REPLACINGand/orTALLYINGoperational instructions active. Only one of theTALLYINGand one of theREPLACINGinstructions (if any) can be executed for any one character pointer position. In each case, it will be the first of the instructions in each category that produces a match with its target string specification.When both a
TALLYINGand aREPLACINGinstruction have been selected for execution, theTALLYINGinstruction will be executed first. This guarantees thatTALLYINGwill compute occurrences based upon the initial value of the inspect subject before any replacements occur.
The following points apply to the use of the
CONVERTINGclause:A
CONVERTINGclause performs a series of single-character substitutions against a data item in much the same manner as is possible with theTRANSFORMstatement (see TRANSFORM).Unlike the
TALLYINGandREPLACINGclauses, both of which may have multiple operations specified, there may be only oneCONVERTINGoperation perINSPECT.If the length of <literal-7> or <identifier-8> (the “from” string) exceeds the length of <literal-8> or <identifier-9> (the “to” string), then the “to” string will be assumed to be padded to the right with enough spaces to make it the same length as the “from” string.
If the length of the “from” string is less than the length of the “to” string, then the “to” string will be truncated to the length of the “from” string.
Each character, in turn, within the “from” string will be searched for in the target range of the inspect subject. Each located occurrence will be replaced by the corresponding character of the “to” string.
JSON GENERATE
JSON GENERATE Syntax
=======================================================================
JSON GENERATE identifier-1 FROM identifier-2
~~~~ ~~~~~~~~ ~~~~
[ COUNT IN identifier-3 ]
~~~~~
[ NAME OF {identifier-4 IS literal-1}... ]
~~~~
[ SUPPRESS {identifier-5}... ]
~~~~~~~~
[ ON EXCEPTION imperative-statement-1 ]
~~ ~~~~~~~~~
[ NOT ON EXCEPTION imperative-statement-2 ]
~~~ ~~~~~~~~~
[ END-JSON ]
~~~~~~~~
=======================================================================
The JSON GENERATE statement creates a JSON document based on the structure and content of the input data item. It takes as input a source data item to generate and store the corresponding JSON document in a target data item. Both the source and receive data items must be declared in program’s Data Division. The JSON generated document follows syntax rules described at https://www.rfc-editor.org/info/rfc8259.
Identifier-1 is an alphanumeric data item, it will contain the generated JSON document output. It must be large enough to contain the generated JSON document. Typically, it should be from two to three times the size of identifier-2, depending on the length of the data-name or data-names within identifier-2. If identifier-1 is not large enough, an error condition exists at the end of the JSON GENERATE statement (see XML-CODE).
If identifier-1 is longer than the generated JSON document, only the initial part of identifier-1 changes. The rest of identifier-1 will contain the data that was present before this execution of the JSON GENERATE statement. To avoid referring to that data, either initialize identifier-1 to spaces before the JSON GENERATE statement or specify the COUNT IN phrase.
The element names in the JSON documents generated from identifier-2 are derived from the name of the data item specified by identifier-2 and from any eligible data-names that are subordinate to identifier-2. The following rules apply:
The exact mixed-case spelling of data-names from the data description entry is retained. The spellings from any references to that data item (for example, in an OCCURS DEPENDING ON clause) are not used.
Data-names beginning with a digit are prefixed by an underscore. For example, the data-name 4C becomes JSON name _4C.
FROM.
The group or elementary data item identifier-2 is to be converted to the JSON document. identifier-2 must not be described with the RENAMES clause. The following data items specified by identifier-2 are ignored by the JSON GENERATE statement:
Any unnamed or FILLER data item with its subordinates.
Any elementary data item that assumes a pointer, e.g. USAGE POINTER.
Any data item (with its subordinates) subordinate to identifier-2 that is described with the REDEFINES clause.
Any group item (with its subordinates) subordinate to identifier-2 that contains a non-unique name within the same level.
Any group item that does not contain at least one elementary data item of category alphabetic, alphanumeric, numeric, or index.
The content of each elementary data item within identifier-2 is converted to character format.
Alphabetic, alphanumeric, alphanumeric-edited, external floating-point, and numeric-edited items are not converted.
Fixed-point numeric data items are converted as if they were moved to a numeric-edited item that has:
An explicit decimal point, if the numeric item has at least one decimal position.
The same number of decimal positions as the numeric item.
A leading ‘-’ picture symbol if the data item is signed and has an S in its PICTURE clause.
For COMPUTATIONAL-5 (COMP-5) binary data items, the number of integer positions depends on the number of ‘9’ symbols in the picture character string. If the data item has one to four ‘9’ picture symbols, the number of integer positions is five minus the number of decimal places. If the data item has five to nine ‘9’ picture symbols, the number of integer positions is ten minus the number of decimal places. If the data item has 10 to 18 ‘9’ picture symbols, the number of integer positions is 20 minus the number of decimal places.
All other fixed-point numeric data items will have as many integer positions as the numeric item, but with at least one integer position.
Internal floating-point data items are converted as if they were moved to a data item as follows:
For COMP-1: an external floating-point data item with PICTURE -9.9(8)E+99.
For COMP-2: an external floating-point data item with PICTURE -9.9(17)E+99 (illegal because of the number of digit positions).
Index data items are converted as if they were declared USAGE COMP-5 PICTURE S9(9). After conversion, leading and trailing spaces and leading zeroes are removed, as described under Data trimming.
After conversion, if a data item contains characters that are illegal in JSON, the value in the data item before conversion or trimming is represented in hexadecimal, and an element tag name with the prefix "hex." is substituted for the regular tag name. For example, if data item Customer-Name is found at run time to contain LOW-VALUES, the XML element tag name ‘hex.Customer-Name’ is used instead of the normal ‘Customer-Name’, and the content is represented as a string of pairs of zero digits.
Trailing spaces and leading zeroes are eliminated. Values converted from signed numeric values have their leading space removed if the value is positive. Values converted from numeric items have leading zeroes eliminated (after any initial minus sign). This is up to but not including the digit immediately before the actual or implied decimal point. Trailing zeroes after a decimal point are retained. For example: 012.340 becomes -12.340; 0000.45 becomes 0.45 ; 0013 becomes 13 ; 0000 becomes 0. Character values from alphabetic, alphanumeric data items have either trailing or leading spaces removed, depending on whether the corresponding data items have left or right justification, respectively left being the default. Trailing spaces are removed from values whose corresponding data items do not specify the JUSTIFIED clause. Leading spaces are removed from values whose data items do specify the JUSTIFIED clause. If a character value consists solely of spaces, all spaces are removed but one.
COUNT IN.
Identifier-3 contains the count of generated JSON characters. It must be an integer data item and normally contains a length of the generated JSON document in bytes.
Use the COUNT IN phrase to determine the total number of character positions, in bytes, that were generated. identifier-3 will then contain this information after JSON GENERATE executes. You can use identifier-3 as a reference modification length field to refer to the part of identifier-2 that contains the generated JSON document.
Identifier-1, identifier-2, identifier-3 must not overlap each other.
NAME.
Allows you to supply element and attribute names.
Identifier-4 must reference identifier-2 or one of its subordinate data items. It cannot be a function identifier and cannot be reference modified or subscripted. It must not specify any data item which is ignored by the JSON GENERATE statement. For more information about identifier-2, see the description of identifier-2. If identifier-4 is specified more than once in the NAME phrase, the last specification is used.
Literal-1 must be an alphanumeric literal containing the attribute or element name to be generated in the JSON document corresponding to identifier-4.
SUPPRESS.
Optionally, you can code the SUPPRESS phrase to specify whether individual data items are generated based on whether or not they meet certain criteria. If the SUPPRESS phrase is specified, identifier-1 must be large enough to contain the generated JSON document before any suppression.
With the generic-suppression-phrase, elementary items subordinate to identifier-2 that are not otherwise ignored by JSON GENERATE operations are identified generically for potential suppression.
ON EXCEPTION and NOT ON EXCEPTION.
When an error occurs during JSON document generation, an exception condition exists. An example of this is when identifier-1 is not large enough to contain the generated XML document. In this case, JSON generation stops and the content of the receiver, identifier-1, is undefined. If the COUNT IN phrase was specified, identifier-3 contains the number of character positions that were generated. This can range from zero to the length of identifier-1.
If the ON EXCEPTION phrase is specified, control is transferred to imperative-statement-1. If it is not specified, NOT ON EXCEPTION phrases are ignored, and control is transferred to the end of the JSON GENERATE statement.
At termination of an JSON GENERATE statement, special register JSON-CODE contains either 0, indicating successful completion of JSON generation, or a non-zero error code, indicating that an exception occurred during JSON generation.
If no exception conditions arise during generation of the JSON document, control is passed to imperative-statement-2, if specified, or to the end of the JSON GENERATE statement. If an ON EXCEPTION phrase is specified, it is ignored. Special register JSON-CODE contains a zero after the JSON GENERATE statement has finished executing.
END-JSON.
Is an explicit scope terminator that delimits the scope of JSON GENERATE statement. With END-JSON, conditional JSON GENERATE statements can be nested in other conditional statements. Conditional JSON GENERATE statements specify the ON EXCEPTION or NOT ON EXCEPTION phrase.
The scope of a conditional JSON GENERATE or JSON PARSE statement is terminated by:
An END-JSON phrase at the same level of nesting
A separator period
IDENTIFICATION DIVISION.
PROGRAM-ID. JSONGEN.
ENVIRONMENT DIVISION.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 payload.
03 reference-id pic x(10).
03 model-specific-data .
05 model-id pic x(10).
05 model-values.
10 model-attrib-name pic x(01).
10 model-value pic x(3).
10 model-value-boolean pic x.
88 true-val value 't'.
01 PAYLOAD-JSON pic U(500).
01 JSON-LEN pic 9999.
PROCEDURE DIVISION.
1000-init-data.
move spaces to payload payload-json.
move "abc123" to REFERENCE-ID.
move "model 01" to MODEL-ID.
move "a" to model-attrib-name.
move "A01" to model-value.
move "t" to model-value-boolean.
2000-create-json.
JSON GENERATE PAYLOAD-JSON FROM PAYLOAD
COUNT json-len
SUPPRESS model-value
END-JSON.
9000-ending.
DISPLAY function concatenate("COUNT= " json-len)
display "JSON DOCUMENT = "
display PAYLOAD-JSON
GOBACK.
JSON PARSE
JSON PARSE Syntax
=======================================================================
JSON PARSE identifier-1 INTO identifier-2
~~~~ ~~~~~ ~~~~
[ WITH DETAIL ]
~~~~~~
[ NAME OF {identifier-3 IS literal-1}... ]
~~~~
[ SUPPRESS {identifier-4}... ]
~~~~~~~~
[ ON EXCEPTION imperative-statement-1 ]
~~~~~~~~~
[ NOT ON EXCEPTION imperative-statement-2 ]
~~~ ~~~~~~~~~
[ END-JSON ]
~~~~~~~~
=======================================================================
The JSON PARSE statement starts an event-driven JSON parser, the processing procedure is performed as each component of the JSON document is identified in order.
This statement is not available in the runtime yet and will raise a JSON exception during execution.
MERGE
MERGE Syntax
=======================================================================
MERGE sort-file-1 { ON { ASCENDING } KEY { identifier-1 }... }...
~~~~~ { ~~~~~~~~~ }
{ DESCENDING }
~~~~~~~~~~
[ WITH DUPLICATES IN ORDER ]
~~~~~~~~~~
[ COLLATING SEQUENCE IS alphabet-name-1 ]
~~~~~~~~
USING file-name-1 { file-name-2 }...
~~~~~
{ GIVING { file-name-3 }... }
{ ~~~~~~ }
{ OUTPUT PROCEDURE IS procedure-name-1 [THRU|THROUGH procedure-name-2 ] }
~~~~~~ ~~~~~~~~~ ~~~~ ~~~~~~~
The DUPLICATES clause is syntactically recognized but is otherwise non-functional.
=======================================================================
The MERGE statement merges the contents of two or more files that have each been pre-sorted on a set of specified identical keys.
The reserved words
IN,IS,KEY,ON,ORDER,SEQUENCEandWITHare optional and may be omitted. The presence or absence of these words has no effect upon the program.The reserved words
THRUandTHROUGHare interchangeable.GnuCOBOL always behaves as if the
WITH DUPLICATES IN ORDERclause is specified, even if it isn’t.While any COBOL implementation’s sort or merge facilities guarantee that records with duplicate key values will be in proper sequence with regard to other records with different key values, they generally make no promises as to the resulting relative sequence of records having duplicate key values with one another.
Some COBOL implementations provide this optional clause to force their sort and merge facilities to retain duplicate key-value records in their original input sequence, relative to one another.
The <sort-file-1> named on the
MERGEstatement must be defined using a sort description (SD(see File/Sort-Description)). This file is referred to in the remainder of this discussion as the merge work file.Each <file-name-1>, <file-name-2> and <file-name-3> (if specified) must reference
ORGANIZATION LINE SEQUENTIAL(see ORGANIZATION LINE SEQUENTIAL) orORGANIZATION SEQUENTIAL(see ORGANIZATION SEQUENTIAL) files. These files must be defined using a file description (FD(see File/Sort-Description)).The <identifier-1> … field(s) must be defined as field(s) within a record of <sort-file-1>.
The record descriptions of <file-name-1>, <file-name-2>, <file-name-3> (if any) and <sort-file-1> are assumed to be identical in layout and size. While the actual data names used for fields in these files’ records may differ, the structure of records,
PICTURE(see PICTURE) of fields,USAGE(see USAGE) of fields, size of fields and location of fields within the records should match field-by-field across all files, at least as far as theKEYfields are concerned.A common programming technique when using the
MERGEstatement is to define the records of all files involved as simple elementary items of the form01 record-name PIC X(n).where n is the record size. The only file where records are actually described in detail would then be <sort-file-1>.The following rules apply to the files named on the
USINGclause:None of them may be open at the time the
MERGEis executed.Each of those files is assumed to be already sorted according to the specifications set forth on the
MERGEstatement’sKEYclause.No two of those files may be referenced on a
SAME RECORD AREA(see SAME RECORD AREA),SAME SORT AREAorSAME SORT-MERGE AREAstatement.
The merging process is as follows:
As the
MERGEstatement begins execution, the first record in each of theUSINGfiles is read automatically.As the
MERGEstatement executes, the current record from each of theUSINGfiles is examined and compared to each other according to the rules set forth by theKEYclause and the alphabet (see Alphabet-Name-Clause) specified on theCOLLATING SEQUENCEclause. The record that should be next in sequence will be written to the merge work file and theUSINGfile from which that record came will be read so that its next record is available. As end-of-file conditions are reached onUSINGfiles, those files will be excluded from further processing — processing continues with the remaining files until all the contents of all of them have been exhausted.After the merge work file has been populated, the merged data will be written to each <file-name-3> if the
GIVINGclause was specified, or will be processed by utilizing anOUTPUT PROCEDURE.When
GIVINGis specified, none of the <file-name-3> files can be open at the time theMERGEstatement is executed.When an output procedure is used, the procedure(s) specified on the
OUTPUT PROCEDUREclause will be invoked as if by a proceduralPERFORM(see Procedural PERFORM) statement with noVARYING,TIMESorUNTILoptions specified. Merged records may be read from the merge work file — one at a time — within the output procedure using theRETURN(see RETURN) statement.A
GO TOstatement (see GO TO) that transfers control out of the output procedure will terminate theMERGEstatement but allows the program to continue executing from the point where theGO TOstatement transferred control to. Once an output procedure has been “aborted” using aGO TOit cannot be resumed, and the contents of the merge work file are lost. You may, however, re-execute theMERGEstatement itself. Using aGO TOstatement to prematurely terminate a merge, or re-starting a previously-cancelled merge is not considered good programming style and should be avoided.An output procedure should be terminated in the same way a procedural
PERFORMstatement would be. Usually, this action will be taken once theRETURNstatement indicates that all records in the merge work file have been processed, but termination could occur at any time — via anEXITstatement (see EXIT) — if required.Neither a file-based
SORTstatement (see File SORT) nor anotherMERGEstatement may be executed within the scope of the procedures comprising the output procedure unless those statements utilize a different sort or merge work file.Once the output procedure terminates, or the last <file-name-3> file has been populated with merged data, the output phase — and the
MERGEstatement itself — is complete.
MOVE
Simple MOVE
Simple MOVE Syntax
=======================================================================
MOVE { literal-1 } TO { identifier-2 }...
~~~~ { identifier-1 } ~~
=======================================================================
The Simple MOVE statement moves a specific value to one or more receiving data items.
The
MOVEstatement will replace the contents of one or more receiving data items (<identifier-2>) with a new value — the one specified by <literal-1> or <identifier-1>.Only numeric data can be moved to a numeric or numeric-edited <identifier-2>. A
MOVEinvolving numeric data will perform any necessary format conversions that might be necessary due to differingUSAGE(see USAGE) specifications.The contents of the <identifier-1> data item will not be changed, unless that same data item appears as an <identifier-2>. Note that such situations will cause a warning message to be issued by the compiler, if warning messages are enabled.
MOVE CORRESPONDING
MOVE CORRESPONDING Syntax
=======================================================================
MOVE CORRESPONDING identifier-1 TO { identifier-2 }...
~~~~ ~~~~ ~~
=======================================================================
The MOVE CORRESPONDING statement moves similarly-named items from one group item to another.
The reserved word
CORRESPONDINGmay be abbreviated asCORR.Both <identifier-1> and <identifier-2> must be group items.
See CORRESPONDING, for a discussion of how corresponding matches between two group items are established.
When corresponding matches are established, the effect of a
MOVE CORRESPONDINGon those matches will be as if a series of individualMOVEs were done — one for each match.
MULTIPLY
MULTIPLY BY
MULTIPLY BY Syntax
=======================================================================
MULTIPLY { literal-1 } BY { identifier-2 [ rounded-phrase ] }...
~~~~~~~~ { identifier-1 } ~~
[ ON SIZE ERROR imperative-statement-1 ]
~~~~ ~~~~~
[ NOT ON SIZE ERROR imperative-statement-2 ]
~~~ ~~~~ ~~~~~
[ END-MULTIPLY ]
~~~~~~~~~~~~
=======================================================================
The MULTIPLY BY statement computes the product of one or more data items (<identifier-2>) and either a numeric literal or another data item.
The reserved words
ISandONare optional and may be omitted. The presence or absence of these words has no effect upon the program.Both <identifier-1> and <identifier-2> must be numeric un-edited data items; <literal-1> must be a numeric literal.
The product of <identifier-1> or <literal-1> and each <identifier-2>, in turn, will be computed and moved to each of the <identifier-2> data items, replacing the prior contents.
The value of <identifier-1> is not altered, unless that same data item appears as an <identifier-2>.
The optional
ROUNDED(see ROUNDED) clause available to each <identifier-2> will control how non-integer results will be saved.The optional
ON SIZE ERRORandNOT ON SIZE ERRORclauses may be used to detect and react to the failure or success, respectively, of an attempt to perform a calculation. In this case, failure is defined as being an <identifier-2> with an insufficient number of digit positions available to the left of any implied decimal point. See ON SIZE ERROR + NOT ON SIZE ERROR, for additional information.
MULTIPLY GIVING
MULTIPLY GIVING Syntax
=======================================================================
MULTIPLY { literal-1 } BY { literal-2 }
~~~~~~~~ { identifier-1 } ~~ { identifier-2 }
GIVING { identifier-3 [ rounded-phrase ] }...
~~~~~~
[ ON SIZE ERROR imperative-statement-1 ]
~~~~ ~~~~~
[ NOT ON SIZE ERROR imperative-statement-2 ]
~~~ ~~~~ ~~~~~
[ END-MULTIPLY ]
~~~~~~~~~~~~
=======================================================================
The MULTIPLY GIVING statement computes the product of two literals and/or data items and saves that result in one or more other data items.
The reserved words
ISandONare optional and may be omitted. The presence or absence of these words has no effect upon the program.Both <identifier-1> and <identifier-2> must be numeric un-edited data items; <literal-1> and <literal-2> must be numeric literals.
The product of <identifier-1> or <literal-1> and <identifier-2> or <literal-2> will be computed and moved to each of the <identifier-3> data items, replacing their old contents.
Neither the value of <identifier-1> nor <identifier-2> will be altered, unless either appears as an <identifier-3>.
The optional
ROUNDED(see ROUNDED) clause available to each <identifier-2> will control how non-integer results will be saved.The optional
ON SIZE ERRORandNOT ON SIZE ERRORclauses may be used to detect and react to the failure or success, respectively, of an attempt to perform a calculation. In this case, failure is defined as being an <identifier-2> with an insufficient number of digit positions available to the left of any implied decimal point. See ON SIZE ERROR + NOT ON SIZE ERROR, for additional information.
NEXT SENTENCE
OPEN Syntax
=======================================================================
NEXT SENTENCE
~~~~ ~~~~~~~~
=======================================================================
The NEXT SENTENCE statement transfers execution to the first statement following the current sentence, in other words NEXT SENTENCE transfers control to the first statement following the closest separator period. See Appendix A glossary of Terms for "sentence" definition.
It must be noted that when NEXT SENTENCE is specified with END-IF, control does not pass to the statement following the END-IF. Instead, control passes to the statement after the closest following period.
Another equivalent definition is the following: when NEXT SENTENCE is specified, control passes to an implicit CONTINUE statement immediately preceding the next separator period. This clause is classed as archaic" and in any event there a better ways of logically doing the same function.
Sample program.
ID DIVISION.
PROGRAM-ID. TESTNS.
PROCEDURE DIVISION.
display 'Starting ...........'
NEXT SENTENCE
*> acts as a go to to "the first statement after the next separating period"
display 'skipped 1 ..........' .
display '1st new sentence ...'
display '2nd new sentence ...'
NEXT SENTENCE
*> acts as a go to to "the first statement after the next separating period"
display 'skipped 2 ..........'
display 'skipped 3 ..........' .
display 'Ending .............'
stop run.
OPEN
OPEN Syntax
=======================================================================
OPEN {[ EXCLUSIVE ] { INPUT } [sharing-mode] {file-name-1 [open-options]}... }...
~~~~ { ~~~~~ }
{ OUTPUT }
{ ~~~~~~ }
{ I-O }
{ ~~~ }
{ EXTEND }
~~~~~~
where "sharing-mode" is:
[ SHARING WITH { ALL OTHER } ]
[ ~~~~~~~ { ~~~ } ]
[ { NO OTHER } ]
[ { ~~ } ]
[ { READ ONLY } ]
~~~~ ~~~~
where "open-options" are:
[ [ WITH ] { LOCK } ] [ WITH NO REWIND ]
[ [ FOR ] ~~~~ ] [ ~~ ~~~~~~ ]
[ ] [ REVERSED ]
[ ALLOWING { ALL } ] ~~~~~~~~
[ ~~~~~~~~ { ~~~ } ]
[ { READERS } ]
[ { ~~~~~~~ } ]
[ { UPDATERS } ]
[ { ~~~~~~~ } ]
[ { WRITERS } ]
[ { ~~~~~~~ } ]
[ { NO OTHERS } ]
~~
The NO REWIND, and REVERSED clauses are syntactically recognized but are otherwise non-functional.
=======================================================================
The OPEN statement makes one or more files described in your program available for use.
The reserved words
OTHERandWITHare optional and may be omitted. The presence or absence of these words has no effect upon the program.The
SHARINGandWITH LOCKclauses may not both be specified in the sameOPENstatement.Any file defined in a GnuCOBOL program must be successfully opened before it or any of its record descriptions may be referenced on:
A
CLOSEstatement (see CLOSE)A
DELETEstatement (see DELETE)A
READstatement (see READ)A
REWRITEstatement (see REWRITE)A
STARTstatement (see START)An
UNLOCKstatement (see UNLOCK)A
WRITEstatement (see WRITE)Any attempt to open a file that is already open will fail with a file status of 41 (see File Status Codes).
Any open failure (including status 41) may be trapped using
DECLARATIVES(see DECLARATIVES) or an error procedure established using theCBL_ERROR_PROCbuilt-in system subroutine (see CBL_ERROR_PROC) built-in subroutine or even just checking the status field defined. It is up to the programmer to check for bad statuses and respond accordingly such as issue a CLOSE before dealing with the problem.The
INPUT,OUTPUT,I-OandEXTENDopen modes inform GnuCOBOL of the manner in which you wish to use the file, as follows:INPUT-
You may only read the existing contents of the file — only the
CLOSE,READ,STARTandUNLOCKstatements will be allowed. This enforcement takes place at execution time, not compilation time. OUTPUT-
You may only write new content (which will completely replace any previous file contents) to the file — only the
CLOSE,UNLOCKandWRITEstatements will be allowed. This enforcement takes place at execution time, not compilation time. I-O-
You may perform any operation you wish against the file — all file I/O statements will be allowed.
EXTEND-
You may only write new content (which will be appended after the previously existing file contents) to the file — only the
CLOSE,UNLOCKandWRITEstatements will be allowed. This enforcement takes place at execution time, not compilation time. You cannot extend an empty file; this will not generate a runtime error, but no output will appear in the file.
The
SHARINGclause informs the GnuCOBOL file runtime modules how you are willing to co-exist with any other GnuCOBOL programs that may attempt to open the same file after your program does. See File Sharing, for an explanation of theSHARINGclause.The
WITH LOCKoption will be functional only if your GnuCOBOL build can support it. GnuCOBOL built for MinGW or native Windows will not, because the Unixfcntlprimitive doesn’t exist in those environments. GnuCOBOL built for Cygwin or Unix will.
PERFORM
Procedural PERFORM
Procedural PERFORM Syntax
=======================================================================
PERFORM procedure-name-1 [ THRU|THROUGH procedure-name-2 ]
~~~~~~~ ~~~~ ~~~~~~~
[ { { literal-1 } TIMES } ]
{ { identifier-1 } ~~~~~ }
{ }
{ [ WITH TEST { BEFORE } ] { VARYING-Clause } }
{ ~~~~ { ~~~~~~ } { } }
{ { AFTER } { UNTIL { conditional-expression-1 } }
{ ~~~~~ { ~~~~~ { EXIT } }
{ ~~~~ }
{ FOREVER }
~~~~~~~
=======================================================================
This format of the PERFORM statement is used to transfer control to one or more procedures, which will return control back when complete. Execution of the procedure(s) can be done a single time, multiple times, repeatedly until a condition becomes TRUE or forever (with some way of breaking out of the control of the PERFORM or of halting program execution within the procedure(s)).
The reserved word
WITHis optional and may be omitted. The presence or absence of this word has no effect upon the program.The reserved words
THRUandTHROUGHare interchangeable.The reserved word and phrase
FOREVERandUNTIL EXITare interchangeable.Both <procedure-name-1> and <procedure-name-2> must be procedure division sections or paragraphs defined in the same program as the
PERFORMstatement. If <procedure-name-2> is specified, it must follow <procedure-name-1> in the program’s source code.The perform scope is defined as being the statements within <procedure-name-1>, the statements within <procedure-name-2> and all statements in all procedures defined between them.
<literal-1> must be a numeric literal or a reference to a function that returns a numeric value. The value must be an integer greater than zero.
<identifier-1> must be an elementary un-edited numeric data item with an integer value greater than zero.
Without the
UNTIL,UNTIL EXIT,TIMES, VARYING-Clause (see VARYING) orFOREVERclauses, the code within the perform scope will be executed once, after which control will return to the statement following thePERFORM.The
FOREVERoption will repeatedly execute the code within the perform scope with no conditions defined for termination of the repetition — it will be up to the programmer to include anEXIT SECTIONstatement (see EXIT) orEXIT PARAGRAPHstatement within the procedure(s) being performed that will break out of the loop.The
TIMESoption will repeat the execution of the code within the perform scope a fixed number of times. When thePERFORMstatement begins execution, an internal repeat counter (not accessible to the programmer) will be set to the value of <literal-1> or the value within <identifier-1>.If the counter has a value greater than zero, the statement(s) within the
PERFORMscope will be executed, after which the counter will be decremented by 1 with each repetition. Once that counter reaches zero, repetition will cease and control will fall into the next statement following thePERFORM.If the <identifier-1> option was used, altering the value of that data item within the perform scope will not affect the repetition count.
The
UNTIL conditional-expression-1option will repeat the code within the perform scope until the specified conditional expression evaluates to aTRUEvalue.The optional
WITH TESTclause will control whetherUNTILtesting occursBEFOREthe statements within the perform scope are executed on each iteration (creating the possibility — if <conditional-expression-1> is initiallyTRUE— that the statements within the perform scope will never be executed) orAFTER(guaranteeing the statements within the perform scope will be executed at least once).The default, if this clause is absent, is
WITH TEST BEFORE.This clause may not be coded when the
TIMESclause is used.The optional
VARYING-Clauseis a mechanism that creates an advanced loop-management mechanism complete with one or more numeric data items being automatically incremented (or decremented) on each loop iteration as well as the termination control of anUNTILclause. See VARYING, for the details.
Inline PERFORM
Inline PERFORM Syntax
=======================================================================
PERFORM
~~~~~~~
[ { { literal-1 } TIMES } ]
{ { identifier-1 } ~~~~~ }
{ }
{ [ WITH TEST { BEFORE } ] { VARYING-Clause } }
{ ~~~~ { ~~~~~~ } { } }
{ { AFTER } { UNTIL { conditional-expression-1 } }
{ ~~~~~ { ~~~~~ { EXIT } }
{ ~~~~ }
{ FOREVER }
~~~~~~~
imperative-statement-1
END-PERFORM
~~~~~~~~~~~
=======================================================================
This format of the PERFORM statement is identical in operation to the procedural PERFORM, except for the fact that the statement(s) comprising the perform scope (<imperative-statement-1>) (see Imperative Statement) are now specified in-line with the PERFORM code rather than in procedures located elsewhere within the program.
VARYING
VARYING Syntax
=======================================================================
VARYING identifier-2 FROM { literal-2 } [ BY { literal-3 } ]
~~~~~~~ ~~~~ { identifier-3 } ~~ { identifier-4 }
UNTIL conditional-expression-1
~~~~~
[ AFTER identifier-5 FROM { literal-4 } [ BY { literal-5 } ]
~~~~~ ~~~~ { identifier-6 } ~~ { identifier-7 }
UNTIL conditional-expression-2 ]...
~~~~~
=======================================================================
The VARYING clause, available on both formats of the PERFORM statement, is a looping mechanism that allows for the specification of one or more numeric data items that will be initialized to a programmer-specified value and automatically incremented by another programmer-specified value after each loop iteration.
All identifiers used in a <VARYING-Clause> must be elementary, un-edited numeric data items. All literals must be numeric literals.
The following points describe the sequence of events that take place as a result of the
VARYINGportion of the clause:When the
PERFORMbegins execution, theFROMvalue will be moved to <identifier>.If the
PERFORMspecifies or impliesWITH TEST BEFORE, <conditional-expression-1> will be evaluated and processing of thePERFORMwill halt if the expression evaluates toTRUE. IfWITH TEST BEFOREwas not specified or implied, or if the conditional expression evaluated toFALSE, processing proceeds with step C.The statements within the perform scope will be executed. If a
GO TOexecuted within the perform scope transfers control to a point outside the perform scope, processing of thePERFORMwill halt.When the statements within the perform scope terminate the loop iteration, by one of:
allowing the flow of execution to attempt to fall past the last statement in the perform scope
executing an
EXIT PERFORM CYCLEstatement (see EXIT)executing an
EXIT PARAGRAPHstatement orEXIT SECTIONstatement when there is only one paragraph (or section) in the perform scope ( this option only applies to a proceduralPERFORM)
If
WITH TEST AFTERwas specified, control will return back to thePERFORM, where <conditional-expression-1> will be evaluated, and processing of thePERFORMwill halt if the expression evaluates toTRUE. IfWITH TEST AFTERwas not specified, or if the conditional expression evaluated toFALSE, processing continues with the next step.The
BYvalue, if any, will be added to <identifier-2>. If noBYis specified, it will be treated as ifBY 1had been specified.Return to step C.
Most
VARYING-Clauses have noAFTERspecified. Those that do, however, are establishing a loop-within-a-loop situation where the process described above in steps (‘A’) through (‘F’) will take place from theAFTER, and those six processing steps actually replace step C of theVARYING. This “nesting” process can continue indefinitely, with each additionalAFTER.
An example should really help you see this at work. Observe the following code which defines a two-dimensional (3 row by 4 column) table and a pair of numeric data items to be used to subscript references to each element of the table:
01 PERFORM-DEMO.
05 PD-ROW OCCURS 3 TIMES.
10 PD-COL OCCURS 4 TIMES
15 PD PIC X(1).
01 PD-Col-No PIC 9 COMP.
01 PD-Row-No PIC 9 COMP.
Let’s say the 3x4 “grid” defined by the above structure has these values:
A B C D
E F G H
I J K L
This code will display ABCDEFGHIJKL on the console output window:
PERFORM WITH TEST AFTER
VARYING PD-Row-No FROM 1 BY 1 UNTIL PD-Row-No = 3
AFTER PD-Col-No FROM 1 BY 1 UNTIL PD-Col-No = 4
DISPLAY PD (PD-Row-No, PD-Col-No) WITH NO ADVANCING
END-PERFORM
While this code will display AEIBFJCGKDHL on the console output window:
PERFORM WITH TEST AFTER
VARYING PD-Col-No FROM 1 BY 1 UNTIL PD-Col-No = 4
AFTER PD-Row-No FROM 1 BY 1 UNTIL PD-Row-No = 3
DISPLAY PD (PD-Row-No, PD-Col-No) WITH NO ADVANCING
END-PERFORM
While we’re looking at sample code, this code displays ABCEFG:
PERFORM
VARYING PD-Row-No FROM 1 BY 1 UNTIL PD-Row-No = 3
AFTER PD-Col-No FROM 1 BY 1 UNTIL PD-Col-No = 4
DISPLAY PD (PD-Row-No, PD-Col-No) WITH NO ADVANCING
END-PERFORM
By removing the WITH TEST clause, the statement is now assuming WITH TEST BEFORE. Since testing now happens before the DISPLAY statement gets executed, when PD-Row-No is 3 and PD-Col-No is 4 the DISPLAY statement won’t be executed.
Most COBOL programmers, when using WITH TEST BEFORE explicitly or implicitly have developed the habit of using ‘>’ rather than ‘=’ on UNTIL clauses. This would make the sample code:
PERFORM
VARYING PD-Row-No FROM 1 BY 1 UNTIL PD-Row-No > 3
AFTER PD-Col-No FROM 1 BY 1 UNTIL PD-Col-No > 4
DISPLAY PD (PD-Row-No, PD-Col-No) WITH NO ADVANCING
END-PERFORM
With this change, ABCDEFGHIJKL is once again displayed.
READ
Sequential READ
Sequential READ Syntax
=======================================================================
READ file-name-1 [ { NEXT|PREVIOUS } ] RECORD [ INTO identifier-1 ]
~~~~ { ~~~~ ~~~~~~~~ } ~~~~
[ { IGNORING LOCK } ]
{ ~~~~~~~~ ~~~~ }
{ WITH [ NO ] LOCK }
{ ~~ ~~~~ }
{ WITH KEPT LOCK }
{ ~~~~ ~~~~ }
{ WITH IGNORE LOCK }
{ ~~~~~~ ~~~~ }
{ WITH WAIT }
~~~~
[ AT END imperative-statement-1 ]
~~~
[ NOT AT END imperative-statement-2 ]
~~~ ~~~
[ END-READ ]
~~~~~~~~
=======================================================================
This form of the READ statement retrieves the next (or previous) record from a file.
The reserved words
AT,RECORDandWITHare optional and may be omitted. The presence or absence of these words has no effect upon the program.The <file-name-1> file must have been defined via an
FD(see File/Sort-Description), not anSD.The <file-name-1> file must currently be open for
INPUT(see File OPEN Modes) orI-O.If <file-name-1> is an
ORGANIZATION RELATIVE(see ORGANIZATION RELATIVE) orORGANIZATION INDEXED(see ORGANIZATION INDEXED) file with anACCESS MODE RANDOM, this statement cannot be used.If <file-name-1> was specified as
ACCESS MODE SEQUENTIAL, this is the only format of theREADstatement that is available.If <file-name-1> is an
ORGANIZATION RELATIVE(see ORGANIZATION RELATIVE) orORGANIZATION INDEXED(see ORGANIZATION INDEXED) file withACCESS MODE DYNAMIC, this statement as well as a randomREAD(see Random READ) may be used.The keywords
NEXTandPREVIOUSspecify what “direction of travel” the reading process will take through the file. If neither is specified,NEXTis assumed.The
PREVIOUSoption is available only forORGANIZATION INDEXEDfiles.When reading any sequential (any organization) or relative file, the “next” direction refers to the physical sequence of records in the file. When reading an indexed file, the “next” and “previous” directions refer to the sequence of primary or alternate record key values in the file’s records, regardless of where the records physically occur within the file.
The minimal statement
READ file-name-1is perfectly legal according to both READ formats. For that reason, whenACCESS MODE DYNAMIChas been specified and you want to tell the GnuCOBOL compiler that this minimal statement should be treated as a sequentialREAD, you must add eitherNEXTorPREVIOUSto the statement (otherwise it will be treated as a randomREAD).A successful sequential READ will retrieve the next available record from <file-name-1>, in either a “next” or “previous” direction from the most-recently-read record, depending upon the use of the
NEXTorPREVIOUSoption. The newly-retrieved record data will be saved into the 01-level record structure(s) that immediately follow the file’sFD. If the optionalINTOclause is present, a copy of the just-retrieved record will be automatically moved to <identifier-1>.When an
ORGANIZATION RELATIVEfile has been successfully read, the file’sRELATIVE KEY(see ORGANIZATION RELATIVE) field will be automatically populated with the relative record number (ordinal occurrence number) of the record in the file.The optional
LOCKoptions may be used to manually control access to the retrieved record by other programs while this program is running. See Record Locking, to review the various record locking behaviours.The optional
AT ENDclause, if coded, is used to detect and react to the failure of an attempt to retrieve another record from the file due to an end-of-file (i.e. no more records) condition.The optional
NOT AT ENDclause, if coded, will check for a file status value of 00. See File Status Codes, for additional information.
Random READ
Random READ Syntax
=======================================================================
READ file-name-1 RECORD [ INTO identifier-1 ]
~~~~ ~~~~
[ { IGNORING LOCK } ]
{ ~~~~~~~~ ~~~~ }
{ WITH [ NO ] LOCK }
{ ~~ ~~~~ }
{ WITH KEPT LOCK }
{ ~~~~ ~~~~ }
{ WITH IGNORE LOCK }
{ ~~~~~~ ~~~~ }
{ WITH WAIT }
~~~~
[ KEY IS identifier-2 ]
~~~
[ INVALID KEY imperative-statement-1 ]
~~~~~~~
[ NOT INVALID KEY imperative-statement-2 ]
~~~ ~~~~~~~
[ END-READ ]
~~~~~~~~
=======================================================================
This form of the READ statement retrieves an arbitrary record from an ORGANIZATION RELATIVE (see ORGANIZATION RELATIVE) or ORGANIZATION INDEXED (see ORGANIZATION INDEXED) file.
The reserved words
IS,KEY(on theINVALIDandNOT INVALIDclauses),RECORDandWITHare optional and may be omitted. The presence or absence of these words has no effect upon the program.The <file-name-1> file must have been defined via an
FD(see File/Sort-Description), not anSD.The <file-name-1> file must currently be open for
INPUT(see File OPEN Modes) orI-O.If the
ACCESS MODEof <file-name-1> isSEQUENTIAL, or theORGANIZATIONof the file is any form of sequential, this format of theREADstatement cannot be used.If the
ACCESS MODEof <file-name-1> isRANDOM, this is the only format of theREADstatement that is available.If <file-name-1> is an
ORGANIZATION RELATIVE(see ORGANIZATION RELATIVE) orORGANIZATION INDEXED(see ORGANIZATION INDEXED) file withACCESS MODE DYNAMIC, this statement as well as a sequentialREAD(see Sequential READ) may be used.The minimal statement
READ file-name-1is perfectly legal according to both READ formats. For that reason, whenACCESS MODE DYNAMIChas been specified and you want to tell the GnuCOBOL compiler that this minimal statement should be treated as a randomREAD, you must omit theNEXTorPREVIOUSavailable to the sequential format of theREADstatement to ensure the statement will be treated as a randomREAD.The optional
KEYclause tells the compiler how a record is to be located in the file.If the
KEYclause is absent, and the file isORGANIZATION RELATIVE-
the contents of the field declared as the file’s
RELATIVE KEYwill be used to identify a record ORGANIZATION INDEXED-
the contents of the field declared as the file’s
RECORD KEYwill be used to identify a record.
If the
KEYclause is specified, and the file isORGANIZATION RELATIVE-
the contents of <identifier-2> will be used as the relative record number of the record to be accessed. <identifier-2> need not be the
RELATIVE KEY(see ORGANIZATION RELATIVE) field of the file (although it could be if you wish). ORGANIZATION INDEXED-
<identifier-2> must be the
RECORD KEY(see ORGANIZATION INDEXED) or one of the file’sALTERNATE RECORD KEYfields (if any). The current contents of that field will identify the record to be accessed. If an alternate record key is used, and that key allows duplicate values, the record accessed will be the first one having that key value.
Once read from the file, the newly-retrieved record data will be saved into the 01-level record structure(s) that immediately follow the file’s
FD. If the optionalINTOclause is present, a copy of the just-retrieved record will be automatically moved to <identifier-1>.When an
ORGANIZATION RELATIVEfile has been successfully read, the file’sRELATIVE KEY(see ORGANIZATION RELATIVE) field will be automatically populated with the relative record number (ordinal occurrence number) of the record in the file.The optional
LOCKoptions may be used to manually control access to the retrieved record by other programs while this program is running. See Record Locking, to review the various record locking behaviours.The optional
INVALID KEYandNOT INVALID KEYclauses may be used to detect and react to the failure or success, respectively, by detecting non-zero (typically 23 = key not found = record not found) and 00 file status codes, respectively. See File Status Codes, for additional information.
READY TRACE
READY TRACE Syntax
=======================================================================
READY TRACE
~~~~~ ~~~~~
=======================================================================
The READY TRACE statement turns procedure or procedure-and-statement tracing on.
In order for this statement to be functional, tracing code must have been generated into the compiled program using either the
-ftraceswitch (procedures only) or-ftraceallswitch (procedures and statements).Tracing may be turned off at any point by executing the
RESET TRACEstatement (see RESET TRACE).The
COB_SET_TRACErun-time environment variable (see Run Time Environment Variables) provides another way to control tracing. If this environment variable is set to a value of ‘Y’ prior to the start of program execution, tracing starts at the point the program begins execution, as ifREADY TRACEwere the first executed statement.
RELEASE
RELEASE Syntax
=======================================================================
RELEASE record-name-1 [ FROM { literal-1 } ]
~~~~~~~ ~~~~ { identifier-1 }
=======================================================================
The RELEASE statement adds a new record to a sort work file.
This statement is valid only within the
INPUT PROCEDUREof a file-basedSORTstatement (see File SORT).The specified <record-name-1> must be a record defined to the sort description (
SD(see File/Sort-Description)) of the sort work file being processed by the current sort.The optional
FROMclause will cause <literal-1> or <identifier-1> to be automatically moved into <record-name-1> prior to writing <record-name-1>’s contents to the <file-name-1>. If this clause is not specified, it is the programmer’s responsibility to populate <record-name-1> with the desired data prior to executing theRELEASE.
RESET TRACE
RESET TRACE Syntax
=======================================================================
RESET TRACE
~~~~~ ~~~~~
=======================================================================
The RESET TRACE statement turns procedure or procedure-and-statement tracing off.
By default, procedure and procedure-and-statement tracing is off as programs begin execution. The
READY TRACEstatement (see READY TRACE) can be used to turn tracing on.In order for this statement to be functional, tracing code must have been generated into the compiled program using either the
-ftraceswitch (procedures only) or-ftraceallswitch (procedures and statements).The
COB_SET_TRACErun-time environment variable (see Run Time Environment Variables) provides another way to control tracing. If this environment variable is set to a value of ‘Y’ prior to the start of program execution, tracing started at the point the program begins execution, as ifREADY TRACEwere the first executed statement. TheRESET TRACEstatement, if executed, will then turn off tracing.
RETURN
RETURN Syntax
=======================================================================
RETURN sort-file-name-1 RECORD
~~~~~~
[ INTO identifier-1 ]
~~~~
AT END imperative-statement-1
~~~
[ NOT AT END imperative-statement-2 ]
~~~ ~~~
[ END-RETURN ]
~~~~~~~~~~
=======================================================================
The RETURN statement reads a record from a sort or merge work file.
The reserved words
ATandRECORDare optional and may be omitted. The presence or absence of these words has no effect upon the program.The
RETURNstatement is valid only within theOUTPUT PROCEDUREof a file-basedSORT(see File SORT) or aMERGEstatement (see MERGE) statement.The <sort-file-name-1> file must be a sort- or merge work file defined with a
SD(see File/Sort-Description), not anFD.A successful
RETURNwill retrieve the next available record from <sort-file-name-1>. The newly-retrieved record data will be saved into the 01-level record structure(s) that immediately follow the file’s SD. If the optionalINTOclause is present, a copy of the just-retrieved record will be automatically moved to <identifier-1>.The mandatory
AT ENDclause is used to detect and react to the failure of an attempt to retrieve another record from the file due to an end-of-file (i.e. no more records) condition.The optional
NOT AT ENDclause, if coded, will check checking for a file status value of 00. See File Status Codes, for additional information.
REWRITE
REWRITE Syntax
=======================================================================
REWRITE { record-name-1 [ FROM { identifier-1 } ] }
~~~~~~~ { [ ~~~~ { literal-1 } ] }
{ }
{ FILE file-name-1 FROM { identifier-1 } }
{ ~~~~ ~~~~ { literal-1 } }
[ WITH [ NO ] LOCK ]
~~ ~~~~
[ INVALID KEY imperative-statement-1 ]
~~~~~~~
[ NOT INVALID KEY imperative-statement-2 ]
~~~ ~~~~~~~
[ END-REWRITE ]
=======================================================================
The REWRITE statement replaces a logical record on a disk file.
The reserved words
KEYandWITHare optional and may be omitted. The presence or absence of these words has no effect upon the program.The <record-name-1> specified on the statement must be defined as an 01-level record subordinate to the File Description (
FD(see File/Sort-Description)) of a file that is currently open forI-O(see File OPEN Modes).The optional
FROMclause will cause <literal-1> or <identifier-1> to be automatically moved into <record-name-1> prior to writing <record-name-1>’s contents to the <file-name-1>. If this clause is not specified, it is the programmer’s responsibility to populate <record-name-1> with the desired data prior to executing theREWRITE.This statement may not be used with
ORGANIZATION LINE SEQUENTIAL(see ORGANIZATION LINE SEQUENTIAL) files.Rewriting a record does not cause the contents of the file to be physically updated until the next block of the file is read, a
COMMIT(see COMMIT) orUNLOCKstatement (see UNLOCK) is issued or that file is closed.If the file has
ORGANIZATION SEQUENTIAL(see ORGANIZATION SEQUENTIAL):The record to be rewritten will be the one retrieved by the most-recently executed
READ(see READ) of the file.If the
FDof the file contains theRECORD CONTAINSorRECORD IS VARYINGclause, and that clause allows the record size to vary, the size of <record-name-1> cannot be altered.
If the file has
ORGANIZATION RELATIVE(see ORGANIZATION RELATIVE) orORGANIZATION INDEXED(see ORGANIZATION INDEXED):If the file has
ACCESS MODE SEQUENTIAL, the record to be rewritten will be the one retrieved by the most-recently executedREADof the file. If the file hasACCESS MODE RANDOMorACCESS MODE DYNAMIC, noREADis required before a record may be rewritten — theRELATIVE KEYorRECORD KEYdefinition for the file, respectively, will specify the record to be updated.If the
FDof the file contains theRECORD CONTAINSorRECORD IS VARYINGclause, and that clause allows the record size to vary, the size can be altered.
The optional
LOCKoptions may be used to manually control access to the re-written record by other programs while this program is running. See Record Locking, to review the various record locking behaviours.The optional
INVALID KEYandNOT INVALID KEYclauses may be used to detect and react to the failure or success, respectively, by detecting non-zero (typically 23 = key not found = record not found) and 00 file status codes, respectively. See File Status Codes, for additional information.
ROLLBACK
ROLLBACK Syntax
=======================================================================
ROLLBACK
~~~~~~~~
=======================================================================
The ROLLBACK statement has the same effect as if an UNLOCK statement (see UNLOCK) were executed against every open file in the program.
All locks currently being held for all open files will be released.
See Record Locking, to review the various record locking behaviours.
SEARCH
SEARCH Serial
SEARCH Syntax
=======================================================================
SEARCH identifier-1 [ VARYING { identifier-2 } ]
~~~~~~ ~~~~~~~ { index-name-1 }
[ AT END imperative-statement-1 ]
~~~
{ WHEN conditional-expression-1 imperative-statement-2 }...
~~~~
[ END-SEARCH ]
~~~~~~~~~~
=======================================================================
The SEARCH statement is used to sequentially search a table, stopping either once a specific value is located within the table or when the table has been completely searched.
The reserved word
ATis optional and may be omitted. The presence or absence of this word has no effect upon the program.The searching process will be controlled through a Search Index — a data item with a
USAGE(see USAGE) ofINDEX. The search index is either the <index-name-1> identifier specified on theVARYINGclause or — if noVARYINGis specified — theUSAGE INDEXdata item implicitly created by anINDEXED BY(see OCCURS) clause in the table’s definition.At the time the
SEARCHstatement is executed, the current value of the search index data item will define the starting position in the table where the searching process will begin. Typically, one initializes that index to a value of 1 before starting theSEARCHviaSET search-index TO 1.Each of the <conditional-expression-n>s on the
WHENclause(s) should involve a data element within the table, subscripted using the search index.The searching process is as follows:
Each <conditional-expression-n> will be evaluated, in turn, until either one evaluates to a value of
TRUEor all have evaluated toFALSE.The <imperative-statement-n> (see Imperative Statement) specified on the
WHENclause whose <conditional-expression-n> evaluated toTRUEwill be executed; after that, the search will be considered complete and control will fall into the first executable statement following theSEARCH.If all <conditional-expression-n>s evaluated to FALSE:
The search index will be incremented by 1
If the search index now has a value greater than the number of entries in the table, the search is considered to have failed and the <imperative-statement-1> on the optional
AT ENDclause, if any, will be executed. After that, control will fall into the first executable statement following theSEARCH.If the search index now has a value less than or equal to the number of entries in the table, search processing returns back to step A.
SEARCH ALL (Binary)
SEARCH ALL Syntax
=======================================================================
SEARCH ALL identifier-1
~~~~~~ ~~~
[ AT END imperative-statement-1 ]
~~~
WHEN { data-name-1 IS EQUALS|= TO { identifier-2 }
~~~~ { ~~~~~ { literal-1 }
{ { arithmetic-expression-1 }
{ condition-name-1 }
[ AND { data-name-2 IS EQUALS|= TO { identifier-3 } ]...
~~~~ { ~~~~~ { literal-2 }
{ { arithmetic-expression-2 }
{ condition-name-2 }
imperative-statement-2
[ END-SEARCH ]
=======================================================================
The SEARCH ALL statement performs a binary, or half-interval, search against a sorted table. This is generally significantly faster than performing a sequential SEARCH of a table, especially if the table contains a large number of entries.
The reserved word
ATis optional and may be omitted. The presence or absence of this word has no effect upon the program.To be eligible for searching via
SEARCH ALL:The
OCCURSclause of <table-name-1> must contain the following elements:An
INDEXED BYentry to define an implicit search index data item with aUSAGE(see USAGE) ofINDEX.An
ASCENDING KEYorDESCENDING KEYclause to specify the field within the table by which all entries in the table are sorted.
Just because the table has one or more
KEYclauses doesn’t mean the data is actually in that sequence in the table — the actual sequence of the data must agree with the KEY clause(s)! A table-basedSORT(see Table SORT) can prove very useful in this regard.No two records in the table may have the same
KEYfield values. If the table has multipleKEYdefinitions, then no two records in the table may have the same combination ofKEYfield values.
If rule A is violated, the compiler will reject the
SEARCH ALL. If rules B and/or C are violated, there will be no message issued by the compiler, but the run-time results of aSEARCH ALLagainst the table will probably be incorrect.The <conditional-expression-1> should involve the
KEYfield(s), using the search index (the table’sINDEXED BYindex name) as a subscript.The function of the single, mandatory,
WHENclause is to compare the key field(s) of the table, as indexed by the search index data item, against whatever literal and/or identifier values you are comparing the key field(s) to in the <conditional-expression-1> in order to locate the desired entry in the table. The search index will be automatically varied in a manner designed to require the minimum number of tests.The internal processing of the SEARCH ALL statement begins by setting internal “first” and “last” pointers to the 1st and last entry locations of the table. Processing then proceeds as follows:
The entry half-way between “first” and “last” is identified. We’ll call this the “current” entry, and will set its table entry location into <index-name-1>.
The <conditional-expression-1> is evaluated. This comparison of the key(s) against the target literal/identifier values will have one of three possible outcomes:
If the key(s) and value(s) match, <imperative-statement-2> (see Imperative Statement) is executed, after which control falls through into the next statement following the
SEARCH ALL.If the key(s) are LESS THAN the value(s), then the table entry being searched for can only occur in the “current” to “last” range of the table, so a new “first” pointer value is set (it will be set to the “current” pointer).
If the key(s) are GREATER THAN the value(s), then the table entry being searched for can only occur in the “first” to “current” range of the table, so a new “last” pointer value is set (it will be set to the “current” pointer).
If the new “first” and “last” pointers are different than the old “first” and “last” pointers, there’s more left to be searched, so return to step A and continue.
If the new “first” and “last” pointers are the same as the old “first” and “last” pointers, the table has been exhausted and the entry being searched for cannot be found; <imperative-statement-1> is executed, after which control falls through into the next statement following the
SEARCH ALL. If there is noAT ENDclause coded, control simply falls into the next statement following theSEARCH ALL.
The net effect of the above algorithm is that only a fraction of the number of elements in the table need ever be tested in order to decide whether or not a particular entry exists. This is because the half the remaining entries in the table are discarded each time an entry is checked.
Computer scientists will compare the two techniques implemented by the
SEARCHandSEARCH ALLstatements as follows:When searching a table with N entries, a sequential search will need an average of N/2 tests and a worst case of N tests in order to find an entry and N tests to identify that an entry doesn’t exist.
When searching a table with N entries, a binary search will need a worst-case of log2(N) tests in order to find an entry and log2(N) tests to identify that an entry doesn’t exist (N = the number of entries in the table), where log2 is the base-2 logarithm function.
Here’s a more practical view of the difference. Let’s say that a table has 1,000 entries in it. With a sequential search, on average, you’ll have to check 500 of them to find an entry and you’ll have to look at all 1,000 of them to find that an entry doesn’t exist.
With a binary search, express the number of entries as a binary number (1,000 = 1111101000), count the number of digits in the result (which is, essentially, what a logarithm is, when rounded up to the next integer — the number of digits a decimal number would have if expressed in the logarithm’s number base). In this case, we end up with 10 — that is the worst-case number of tests required to find an entry or to identify that it doesn’t exist. That’s quite an improvement!
SET
SET ENVIRONMENT
SET ENVIRONMENT Syntax
=======================================================================
SET ENVIRONMENT { literal-1 } TO { literal-2 }
~~~ ~~~~~~~~~~~ { identifier-1 } ~~ { identifier-2 }
=======================================================================
The SET ENVIRONMENT statement provides a straight-forward means of setting environment values from within a program.
The value of <literal-1> or <identifier-1> specifies the name of the environment variable to set.
The value of <literal-2> or <identifier-2> specifies the value to be assigned to the environment variable.
SET ENVIRONMENT is especially useful for managing the configuration variables listed in chapter 10.2.3 Run Time Environment Variables and in particular the variables in chapter 10.2.3.5 Screen I/O.
As an example, use SET ENVIRONMENT ‘COB_HIDE_CURSOR’ TO ‘TRUE’ to make the cursor invisible when doing a DISPLAY or an ACCEPT.
Environment variables created or changed from within GnuCOBOL programs will be available to any sub-shell processes spawned by that program (i.e.
CALL "SYSTEM") but will not be known to the shell or console window that started the GnuCOBOL program.
This is a much simpler and more readable means of setting environment variables than by using the DISPLAY UPON ENVIRONMENT statement (see DISPLAY UPON ENVIRONMENT). For example, these two code sequences produce identical results:
DISPLAY "VARNAME" UPON ENVIRONMENT-NAME
DISPLAY "VALUE" UPON ENVIRONMENT-VALUE
SET ENVIRONMENT "VARNAME" TO "VALUE"
SET Program-Pointer
SET Program-Pointer Syntax
=======================================================================
SET program-pointer-1 TO ENTRY { literal-1 }
~~~ ~~ ~~~~~ { identifier-1 }
=======================================================================
The SET Program-Pointer statement allows you to retrieve the address of a procedure division code module — specifically the PROGRAM-ID, FUNCTION-ID or an entry-point established via the ENTRY statement (see ENTRY).
The
USAGE(see USAGE) of <program-pointer-1> must bePROGRAM-POINTER.The <literal-1> or <identifier-1> value specified must name a primary entry-point name (
PROGRAM-IDof a subroutine orFUNCTION-IDof a user-defined function) or an alternate entry-point defined via anENTRYstatement within a subprogram.Once the address of a procedure division code area has been acquired in this way, the address could be passed to a subroutine (usually written in C) for whatever use it needs it for. For examples of
PROGRAM-POINTERs at work, see the discussions of theCBL_ERROR_PROCbuilt-in system subroutine (see CBL_ERROR_PROC) andCBL_EXIT_PROCbuilt-in system subroutine (see CBL_EXIT_PROC).
Example of use:
>>SOURCE FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. TESTPROCEDUREPOINTER.
*> this program CALL a SUBprogram using procedure-pointer (and an EXTERNAL field)
*> the SUBprogram creates a line sequential file with data received from EXTERNAL field
*> Programs can be compiled in one of two ways:
*> compiled together (putting the callee (nested or not) in the same source as the caller)
*> compiled separately (the caller as .exe and the called as .dll in windows).
DATA DIVISION.
WORKING-STORAGE SECTION.
01 PGMSUB-PTR PROCEDURE-POINTER.
01 PGMSUB-PGM pic X(8) value 'PGMSUB'.
01 wCOMMON-AREA EXTERNAL.
05 wCOMMAND pic X(05).
05 wDATA.
07 wFILLER1 pic X(20).
07 wCOUNT pic 9(06).
07 wFILLER2 pic X(74).
PROCEDURE DIVISION.
display space display 'PGMMAIN - START OF MAIN PROGRAM.'
move zero to wCOUNT
set PGMSUB-PTR to entry PGMSUB-PGM
move 'OPEN ' to wCOMMAND
call PGMSUB-PTR
move 'WRITE' to wCOMMAND
perform until wCOUNT >= 13
compute wCOUNT = wCOUNT + 1
move ' Record Num ......: ' to wFILLER1
move space to wFILLER2
call PGMSUB-PTR
end-perform
move 'CLOSE' to wCOMMAND
call PGMSUB-PTR
display space display 'PGMMAIN - END OF MAIN PROGRAM.'
accept omitted
STOP RUN.
END PROGRAM TESTPROCEDUREPOINTER.
IDENTIFICATION DIVISION.
PROGRAM-ID. PGMSUB.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT PGMSUB-FILE ASSIGN TO 'PGMSUB.TXT'
ORGANIZATION IS LINE SEQUENTIAL
ACCESS MODE IS SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD PGMSUB-FILE.
01 PGMSUB-REC PIC X(80).
WORKING-STORAGE SECTION.
01 wCOMMON-AREA EXTERNAL.
05 wCOMMAND pic X(5).
05 wDATA.
07 wFILLER1 pic X(20).
07 wCOUNT pic 9(06).
07 wFILLER2 pic X(74).
PROCEDURE DIVISION.
evaluate wCOMMAND
when 'OPEN ' Open Output PGMSUB-FILE
display space display 'at time: ' Function CURRENT-DATE(09:08) ' PGMSUB - open '
when 'WRITE' Write PGMSUB-REC from wDATA
display 'at time: ' Function CURRENT-DATE(09:08) ' PGMSUB - write ' wDATA (01:40)
when 'CLOSE' Close PGMSUB-FILE
display 'at time: ' Function CURRENT-DATE(09:08) ' PGMSUB - close '
end-evaluate
GOBACK.
SET ADDRESS
SET ADDRESS Syntax
=======================================================================
SET [ ADDRESS OF ] { pointer-name-1 }... TO { [ ADDRESS OF ] { pointer-name-2 } }
~~~ ~~~~~~~ { identifier-1 } ~~ { ~~~~~~~ { identifier-2 } }
{ NULLS }
~~~~
=======================================================================
The SET ADDRESS statement can be used to work with the addresses of data items rather than their contents.
When the
ADDRESS OFclause is used before theTOyou will be using this statement to alter the address of a linkage section orBASED(see BASED) data item. Without that clause you will be assigning an address to one or more data items whoseUSAGE(see USAGE) isPOINTER.When the
ADDRESS OFclause is used after theTO, this statement will be identifying the address of <identifier-2> as the address to be assigned to <identifier-1> or stored in <pointer-name-1>.If the
ADDRESS OFclause is absent after theTO, the contents of <pointer-name-2> will serve as the address to be assigned.
SET Index
SET Index Syntax
=======================================================================
SET index-name-1 TO { literal-1 }
~~~ ~~ { identifier-2 }
=======================================================================
This statement assigns a value to a USAGE INDEX data item.
- Either the
USAGE(see USAGE) of <index-name-1> should beINDEX, or <index-name-1> must be identified in a tableINDEXED BYclause.
SET UP/DOWN
SET UP/DOWN Syntax
=======================================================================
SET { identifier-1 }... { UP } BY [ LENGTH OF ] { integer-1 }
~~~ { ~~ } ~~ ~~~~~~ ~~ { identifier-2 }
{ DOWN }
~~~~
=======================================================================
Use this statement to increment or decrement the value of an index or pointer by a specified amount.
The
USAGE(see USAGE) of <identifier-1> must beINDEX,POINTERorPROGRAM-POINTER.The typical usage when <identifier-1> is a
USAGE INDEXdata item is to increment its valueUPorDOWNby 1, since an index is usually being used to sequentially walk through the elements of a table.
SET Condition Name
SET Condition Name Syntax
=======================================================================
SET { { condition-name-1 }... TO { TRUE } }...
~~~ ~~ { ~~~~ }
{ FALSE }
~~~~~
=======================================================================
The SET Condition Name statement provides one method of specifying the TRUE / FALSE value of a level-88 condition name.
By setting the specified <condition-name-1>(s) to a
TRUEorFALSEvalue, you will actually be assigning a value to the parent data item(s) to which the condition name data item(s) is(are) subordinate to.When specifying
TRUE, the value assigned to each parent data item will be the first value specified on the condition name’sVALUEclause.When specifying
FALSE, the value assigned to each parent data item will be the value specified for theFALSEclause of the condition name’s definition; if any <condition-name-1> occurrence lacks aFALSEclause, theSETstatement will be rejected by the compiler.
SET Switch
SET Switch Syntax
=======================================================================
SET { { mnemonic-name-1 }... TO { ON } } ...
~~~ ~~ { ~~ }
{ OFF }
~~~
=======================================================================
This form of the SET statement is used to turn switches on or off.
Switches are defined using the
SPECIAL-NAMES(see SPECIAL-NAMES) paragraph.Switches may be tested via the
IFstatement (see IF) and a Switch-Status Condition. See Switch-Status Conditions, for more information.
SET ATTRIBUTE
SET ATTRIBUTE Syntax
=======================================================================
SET identifier-1 ATTRIBUTE { { BELL | BEEP } { ON } } ...
~~~ ~~~~~~~~~ { ~~~~ ~~~~ } { ~~ }
{ BLINK } { OFF }
{ ~~~~~ } ~~~
{ HIGHLIGHT }
{ ~~~~~~~~~ }
{ LEFTLINE }
{ ~~~~~~~~ }
{ LOWLIGHT }
{ ~~~~~~~~ }
{ OVERLINE }
{ ~~~~~~~~ }
{ REVERSE-VIDEO }
{ ~~~~~~~~~~~~~ }
{ UNDERLINE }
~~~~~~~~~
=======================================================================
The SET ATTRIBUTE statement may be used to modify one or more attributes of a screen section data item at run-time.
When making an attribute change to <identifier-1>, the change will not become visible on the screen until the screen section data item containing <identifier-1> is next accepted (if <identifier-1> is an input field) or is next displayed (if <identifier-1> is not an input field).
The attributes shown in the syntax diagram are the only ones that may be altered by this statement. See Data Description Clauses, for information on their usage.
SET LAST EXCEPTION
SET ATTRIBUTE Syntax
=======================================================================
SET LAST EXCEPTION TO OFF
~~~ ~~~~ ~~~~~~~~~ ~~ ~~~
=======================================================================
The SET LAST EXCEPTION statement will set the last program exception status to indicate no exception.
The predefined object reference EXCEPTION-OBJECT is set to null, and the last exception status is set to indicate no exception.
This action resets the global exception object completely (FUNCTION EXCEPTION-{FILE, LOCATION, STATEMENT, STATUS } ), and will not show anything afterwards), no matter what the last exception was (such as a divide by zero). Use with care.
SET Indentifier
SET Indentifier Syntax
=======================================================================
SET { identifier-1 }... TO { identifier-2 }
~~~ ~~ { integer-1 }
{ literal-1 }
=======================================================================
The SET Identifier statement will set the the specified identifier.
Example of use:
IDENTIFICATION DIVISION.
PROGRAM-ID. SETSAMPLE.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 BLACK PIC 99 VALUE 00.
01 GREEN PIC 99 VALUE 02.
01 BG-COLOR PIC 99.
01 FG-COLOR PIC 99.
01 wABC PIC XXX.
PROCEDURE DIVISION.
SET BG-COLOR FG-COLOR TO GREEN
SET wABC TO 'ABC'
STOP RUN.
SET FCD and KEY DEFINITION BLOCK
SET FCD and KEY DEFINITION BLOCK Syntax
=======================================================================
SET ADDRESS OF { identifier-1 }... TO ADDRESS OF { FH--FCD } OF indexedfilename
~~~ ~~~~~~~ ~~ ~~ ~~~~~~~ ~~ { ~~~~~~~ } ~~
{ FH--KEYDEF }
~~~~~~~~~~
=======================================================================
When normal I/O operations (OPEN, READ ...) in a GnuCOBOL program, a FILE CONTROL DESCRIPTION (FCD) is created for each file. To access this FCD, set up a FCD definition in the Linkage Section of your program. An example FCD COBOL definition is supplied in a file called xfhfcd3.cpy. This definition (that takes up no physical memory) can then be mapped onto the FCD you want to read or alter using the following SET statement in your program:
SET ADDRESS OF { identifier-1 } TO ADDRESS OF FH--FCD OF indexedfile
Where the parameters are: a. identifier-1 The name of the FCD definition in the Linkage Section of your program; b. FH–FCD OF namefile (note the double hyphen). The pointer special register automatically allocated to the file with FD-name: indexedfile. Following this SET operation, the data items defined in the Linkage Section group item identifier-1 become the fields of the FCD of the file referenced in the SET statement.
Similarly, you can access the Key Definition Block by:
SET ADDRESS OF { identifier-2 } TO ADDRESS OF FH--KEYDEF OF indexedfile
Where the parameters are: a. identifier-2 the name of the key definition Block in the Linkage Section of your program; b. FH—KEYDEF of indexedfile (note the double hyphen) the pointer special register automatically allocated to the file with FD-name indexfile to point to its Key Definition Block.
See also EXTFH in this document and FH–FCD and FH–KEYDEF into the NEWS file.
SET TO SIZE OF
SET TO SIZE OF Syntax
=======================================================================
SET {identifier-1}... TO SIZE OF {identifier-2 | literal-1 }
~~~ ~~~~
=======================================================================
See example program.
ID DIVISION.
PROGRAM-ID. TESTSET.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 wSIGNED-LONG SIGNED-LONG.
01 wSIZE1 PIC 99.
01 wSIZE2 PIC 99.
PROCEDURE DIVISION.
SET wSIZE1 wSIZE2 TO SIZE OF wSIGNED-LONG.
DISPLAY wSIZE1 ' ' wSIZE2.
SET wSIZE1 wSIZE2 TO SIZE OF '1234567890'.
DISPLAY wSIZE1 ' ' wSIZE2.
STOP RUN.
SET LOCALE
SET LOCALE Syntax
=======================================================================
Format 1. SET LOCALE
SET LOCALE { LC-ALL } TO { identifier-1 }
{ LC_COLLATE } { locale-name }
{ LC_CTYPE } { USER-DEFAULT }
{ LC_MESSAGES } { SYSTEM-DEFAULT }
{ LC_MONETARY }
{ LC_NUMERIC }
{ LC_TIME }
{ USER-DEFAULT }
Format 2. SET to save LOCALE
SET identifier-1 TO LOCALE { LC-ALL }
~~~~~~~~~~~~ ~~~~~~ { ~~~~~~ }
{ USER-DEFAULT }
{ ~~~~~~~~~~~~ }
=======================================================================
Use the set locale function to set, change, or query some or all of the current program locale information
LC_ALL stores all information, it is a way to backup and restore all locale settings fast
SYSTEM-DEFAULT is effectively LC_ALL after runtime initialization.
USER-DEFAULT is similar, but it is a runtime-wide way to store / reset a given setup, the initial value is SYSTEM-DEFAULT, but that may be changed with the second format.
For the first format: identifier or locale-name shall be specified in the TO phrase.
Identifier-1 has to be of category data-pointer.
Locale-name is setup in LOCALE clause of SPECIAL-NAMES paragraph.
If TO identifier-1 has invalid content (It only checks for NULL), it raises EC-LOCALE-INVALID-PTR, if the locale is not available (or just no valid locale according to the system), EC-LOCALE-MISSING is raised (that also applies to locale-name)
Warning: This has not yet been implemented (as of 1 November 2025).
SORT
File SORT
File-Based SORT Syntax
=======================================================================
SORT sort-file-1 { ON { ASCENDING } KEY { identifier-1 }... }...
~~~~ { ~~~~~~~~~ }
{ DESCENDING }
~~~~~~~~~~
[ WITH DUPLICATES IN ORDER ]
~~~~~~~~~~
[ COLLATING SEQUENCE IS alphabet-name-1 ]
~~~~~~~~~
{ USING { file-name-1 }... }
{ ~~~~~ }
{ INPUT PROCEDURE IS procedure-name-1 [ THRU|THROUGH procedure-name-2 ] }
~~~~~ ~~~~~~~~~ ~~~~ ~~~~~~~
{ GIVING { file-name-2 }... }
{ ~~~~~~ }
{ OUTPUT PROCEDURE IS procedure-name-3 [ THRU|THROUGH procedure-name-4 ] }
~~~~~~ ~~~~~~~~~ ~~~~ ~~~~~~~
The DUPLICATES clause is syntactically recognized but is otherwise non-functional.
=======================================================================
This format of the SORT statement is designed to sort large volumes of data according to one or more key fields.
The reserved words
IN,IS,KEY,ON,ORDER,SEQUENCEandWITHare optional and may be omitted. The presence or absence of these words has no effect upon the program.The reserved words
THRUandTHROUGHare interchangeable.GnuCOBOL always behaves as if the
WITH DUPLICATES IN ORDERclause is specified, even if it isn’t.While any COBOL implementation’s sort or merge facilities guarantee that records with duplicate key values will be in proper sequence with regard to other records with different key values, they generally make no promises as to the resulting relative sequence of records having duplicate key values with one another.
Some COBOL implementations provide this optional clause to force their sort and merge facilities to retain duplicate key-value records in their original input sequence, relative to one another.
The <sort-file-1> named on the
SORTstatement must be defined using a sort description (SD(see File/Sort-Description)). This file is referred to in the remainder of this discussion as the sort work file.If specified, <file-name-1> and <file-name-2> must reference
ORGANIZATION LINE SEQUENTIAL(see ORGANIZATION LINE SEQUENTIAL) orORGANIZATION SEQUENTIAL(see ORGANIZATION SEQUENTIAL) files. These files must be defined using a file description (FD(see File/Sort-Description)). The same file(s) may be used for <file-name-1> and <file-name-2>.The <identifier-1> … field(s) must be defined as field(s) within a record of <sort-file-1>.
A sort work file is never opened or closed.
The sorting process works in three stages — the Input Stage, the Sort Stage and the Output Stage.
The following points pertain to the Input Stage:
The data to be sorted is loaded into the sort work file either by copying the entire contents of the file(s) named on the
USINGclause (done automatically by the sort) or by utilizing an input procedure.When
USINGis specified, none of the <file-name-1> files may be open at the time theSORTstatement is executed.When an input procedure is used, the procedure(s) specified on the
INPUT PROCEDUREclause will be invoked as if by a proceduralPERFORMstatement (see Procedural PERFORM) with noVARYING,TIMESorUNTILoptions specified. Records will be loaded into the sort work file — one at a time — within the input procedure using theRELEASEstatement (see RELEASE). This, by the way, is how you could sort the contents of relative or indexed files.A
GO TOstatement (see GO TO) that transfers control out of the input procedure will terminate theSORTstatement but allows the program to continue executing from the point where theGO TOstatement transferred control to. Once an input procedure has been “aborted” using aGO TOit cannot be resumed, and the contents of the sort work file are lost. You may, however, re-execute theSORTstatement itself.1An input procedure should be terminated in the same way a procedural
PERFORMstatement would be.Neither a another file-based
SORTstatement nor aMERGEstatement may be executed within the input procedure unless those statements utilize a different sort or merge work file.Once the input procedure terminates, the input phase is complete.
As data is loaded into the sort work file, it is actually being buffered in dynamically-allocated memory. Only if the amount of data to be sorted exceeds the amount of available sort memory (128 MB) will actual disk files be allocated and utilized. There is a
COB_SORT_MEMORYrun-time environment variable (see Run Time Environment Variables) that you may use to allocate more or less memory to the sorting process.
The following points pertain to the Sort Stage:
The sort will take place by arranging the data records in the sequence defined by the
KEYspecification(s) on theSORTstatement according to theCOLLATING SEQUENCEspecified on theSORT(if any) or — if none was defined — thePROGRAM COLLATING SEQUENCE(see OBJECT-COMPUTER). Keys may be any supported data type andUSAGE(see USAGE) except for level-78 or level-88 data items.For example, let’s assume we’re sorting a series of financial transactions. The SORT statement might look like this:
SORT Sort-File ASCENDING KEY Transaction-Date ASCENDING KEY Account-Number DESCENDING KEY Transaction-AmountThe effect of this statement will be to sort all transactions into ascending order of the date the transaction took place (oldest first, newest last). Unless the business running this program is going out of business, there are most-likely many transactions for any given date. Therefore, within each grouping of transactions all with the same date, transactions will be sub-sorted into ascending sequence of the account number the transactions apply to. Since it’s quite possible there might be multiple transactions for an account on any given date, a third level sub-sort will arrange all transactions for the same account on the same date into descending sequence of the actual amount of the transaction (largest first, smallest last). If two or more transactions of $100.00 were recorded for account #12345 on the 31st of August 2009, those transactions will be retained in the order in which they were loaded into the sort work file.
Should disk work files be necessary due to the amount of data being sorted, they will be automatically allocated to disk in a folder defined by the
TMPDIRrun-time environment variable,TMPrun-time environment variable orTEMPrun-time environment variable run-time environment variables (see Run Time Environment Variables) (checked for existence in that sequence). These disk files will be automatically purged uponSORTtermination or program execution termination (normal or otherwise).
The following points pertain to the Output Stage:
Once the sort stage is complete, a copy of the sorted data will be written to each <file-name-2> if the
GIVINGclause was specified. None of the <file-name-2> files can be open at the time the sort is executed.When an output procedure is used, the procedure(s) specified on the
OUTPUT PROCEDUREclause will be invoked as if by a proceduralPERFORMstatement (see Procedural PERFORM) with noVARYING,TIMESorUNTILoptions specified. Records will be retrieved from the sort work file — one at a time — within the output procedure using theRETURNstatement (see RETURN).A
GO TOstatement (see GO TO) that transfers control out of the output procedure will terminate theSORTstatement but allows the program to continue executing from the point where theGO TOstatement transferred control to. Once an output procedure has been “aborted” using aGO TOit cannot be resumed, and the contents of the sort work file are lost. You may, however, re-execute theSORTstatement itself. USING AGO TOstatement2An output procedure should be terminated in the same way a procedural
PERFORMstatement would be.Neither a another file-based
SORTstatement nor aMERGEstatement may be executed within the output procedure unless those statements utilize a different sort or merge work file.Once the output procedure terminates, the sort is complete.
Table SORT
Table SORT Syntax
=======================================================================
SORT table-name-1 { ON { ASCENDING } KEY identifier-1... }...
~~~~ { ~~~~~~~~~ }
{ DESCENDING }
~~~~~~~~~~
[ WITH DUPLICATES IN ORDER ]
~~~~~~~~~~
[ COLLATING SEQUENCE IS alphabet-name-1 ]
~~~~~~~~~
The DUPLICATES clause is syntactically recognized but is otherwise non-functional.
=======================================================================
This format of the SORT statement sorts relatively small quantities of data — namely data contained in a data division table — according to one or more key fields.
The reserved words
IN,IS,KEY,ON,ORDER,SEQUENCEandWITHare optional and may be omitted. The presence or absence of these words has no effect upon the program.GnuCOBOL always behaves as if the
WITH DUPLICATES IN ORDERclause is specified, even if it isn’t.While any COBOL implementation’s sort or merge facilities guarantee that records with duplicate key values will be in proper sequence with regard to other records with different key values, they generally make no promises as to the resulting relative sequence of records having duplicate key values with one another.
Some COBOL implementations provide this optional clause to force their sort and merge facilities to retain duplicate key-value records in their original input sequence, relative to one another.
The <table-name-1> data item must be a table defined in any data division section except the report or screen sections.
The data within <table-name-1> will be sorted in-place (i.e. no sort file is required).
The sort will take place by rearranging the data in <table-name-1> into the sequence defined by the
KEYspecification(s) on theSORTstatement, according to theCOLLATING SEQUENCEspecified on theSORT(if any) or — if none was defined — thePROGRAM COLLATING SEQUENCE(see OBJECT-COMPUTER). Keys may be any supported data type andUSAGE(see USAGE) except for level-78 or level-88 data items.If you are sorting <table-name-1> for the purpose of preparing the table for use with a
SEARCHstatement (see SEARCH) (to use a binary search withSEARCH ALL), care must be taken that theKEYspecifications on theSORTagree with those in the table’s definition.Although the specification of one or more
KEYclauses is optional, currently, a table sort with noKEYspecification(s) made on theSORTstatement is unsupported by GnuCOBOL and will be rejected by the compiler.
START
START Syntax
=======================================================================
START file-name-1
~~~~~
[ { FIRST } ]
{ ~~~~~ }
{ }
{ KEY IS { EQUALS TO } identifier-1 }
{ ~~~ { ~~~~~ } }
{ { = } }
{ { } }
{ { [ NOT ] LESS THAN } }
{ { ~~~ ~~~~ } }
{ { [ NOT ] < } }
{ { ~~~ } }
{ { [ NOT ] LESS THAN OR EQUALS TO } }
{ { ~~~ ~~~~ ~~ ~~~~~ } }
{ { [ NOT ] <= } }
{ { ~~~ } }
{ { [ NOT ] GREATER THAN } }
{ { ~~~ ~~~~~~~ } }
{ { [ NOT ] > } }
{ { ~~~ } }
{ { [ NOT ] GREATER THAN OR EQUALS TO } }
{ { ~~~ ~~~~~~~ ~~ ~~~~~ } }
{ { [ NOT ] >= } }
{ ~~~ }
{ [ WITH { SIZE } { literal-1 } ] }
{ [ { ~~~~ } { identifier-2 } ] }
{ [ { LENGTH } { arithmetic-expression-1 } ] }
{ ~~~~~~ }
{ }
{ LAST }
~~~~
[ INVALID KEY imperative-statement-1 ]
~~~~~~~
[ NOT INVALID KEY imperative-statement-2 ]
~~~ ~~~~~~~
[ END-START ]
~~~~~~~~~
=======================================================================
The START statement defines the logical starting point within a relative or indexed file for subsequent sequential read operations. It positions an internal logical record pointer to a particular record in the file, but does not actually transfer any of that record’s data into the record buffer.
The reserved words
IS,THANandTOare optional and may be omitted. The presence or absence of these words has no effect upon the program.To use this statement, <file-name-1> must be an
ORGANIZATION RELATIVE(see ORGANIZATION RELATIVE) orORGANIZATION INDEXED(see ORGANIZATION INDEXED) file that must have been defined with anACCESS MODE DYNAMICorACCESS MODE SEQUENTIALin itsSELECTstatement (see SELECT).At the time this statement is executed, <file-name-1> must be open in either
INPUTorI-O(see File OPEN Modes) mode.If <file-name-1> is a relative file, <identifier-1> must be the defined
RELATIVE KEYof the file.If <file-name-1> is an indexed file, <identifier-1> must be the defined
RECORD KEYof the file or any of theALTERNATE RECORD KEYfields for the file.If no
FIRST,LASTorKEYclause is specified,KEY IS EQUAL TO xxxwill be assumed, wherexxxis the definedRELATIVE KEYof (if <file-name-1> is a relative file) or the definedRECORD KEY(if <file-name-1> is an indexed file).After successful execution of a
STARTstatement, the internal logical record pointer into the <file-name-1> data will be positioned to the record which satisfied the actual or impliedFIRST,LASTorKEYclause specification, as follows:FIRST-
the logical record pointer will point to the first record in the file.
LAST-
the logical record pointer will point to the last record in the file.
KEY-
(specified or implied), and the relation used is. Warning: Later versions of the compiler may well not use implied, so always specify it and it makes the code easier to read any way.
SIZE-
WITH
SIZEorLENGTHarithmetic-expression specifies the number of characters in the key to be used in the positioning process. LENGTH-
WITH
LENGTHorSIZEarithmetic-expression specifies the number of characters in the key to be used in the positioning process.SIZEandLENGTHare interchangeable and mean exactly the same.EQUAL TO,GREATER THANorGREATER THAN OR EQUAL TO(or equivalent)-
the logical record pointer will be specified to the first record satisfying the relation condition; to identify this record. The file’s contents are searched in a first-to-last (in sequence of the key implied by the
KEYclause), provided the relation is LESS THAN,LESS THAN OR EQUAL TOorNOT GREATER THAN(or equivalent)-
the logical record pointer will be specified to the last record satisfying the relation condition; to identify this record. The file’s contents are searched in a last-to-first (in sequence of the key implied by the
KEYclause)
The next sequential
READstatement will read the record that is pointed to by the logical record pointer.The optional
INVALID KEYandNOT INVALID KEYclauses may be used to detect and react to the failure or success, respectively, by detecting non-zero (typically 23 = key not found = record not found) and 00 file status codes, respectively. See File Status Codes, for additional information.
STOP
STOP Syntax
=======================================================================
STOP { RUN [ { RETURNING|GIVING { literal-1 } } ] }
~~~~ { ~~~ [ { ~~~~~~~~~ ~~~~~~ { identifier-1 } } ] }
{ [ { } ] }
{ [ { WITH { ERROR } STATUS [ { literal-2 } ] } ] }
{ [ { { ~~~~~ } [ { identifier-2 } ] } ] }
{ [ { { NORMAL } } ] }
{ [ { ~~~~~~ } ] }
{ [ { } ] }
{ [ { literal-4|identifier-4 } ] }
{ }
{ literal-3|identifier-3 }
{ ERROR }
~~~~~
=======================================================================
The STOP statement suspends program execution. Some options will allow program execution to resume while others return control to the operating system.
The reserved words
STATUSandWITHare optional and may be omitted. The presence or absence of these words has no effect upon the program.The reserved words
RETURNINGandGIVINGare interchangeable.The
RUNclause halts the program without displaying any special message to that effect.The <literal-3>, <literal-4>, <identifier-3> and <identifier-4> clause displays the specified text on the
SYSOUT/STDOUTdevice, waits for the user to press the Enter key and then — once the key has been pressed — allows the program to continue execution.The optional
RETURNINGclause provides the opportunity to return a numeric value to the operating system (an exit status). The manner in which the exit status may be interrogated by the operating system varies, but Windows can use%ERRORLEVEL%to query the exit status while Unix shells such as sh, bash and ksh can query the exit status as$?. Other Unix shells may have different ways to access return code values.The
STATUSclause provides another means of returning an exit status. Using theSTATUSclause is functionally equivalent to using theRETURNINGclause.Using the
STATUSclause without a <literal-2> or <identifier-2> will return an exit status of 0 if theNORMALkeyword is used or a 1 ifERRORwas specified.Your program will always return an exit status, even if no
RETURNINGorSTATUSclause is specified. In the absence of the use of these clauses, the value in theRETURN-CODEspecial register (see Special Registers) at the time theSTOPstatement is executed will be used as the exit status.Any programmer-defined exit procedure (established via the
CBL_EXIT_PROCbuilt-in system subroutine (see CBL_EXIT_PROC)) will be executed bySTOP RUN, but not bySTOP literal-3.Valid return code values can be in the range -2147483648 to +2147483647.
The three code snippets below are all equivalent. They show different ways in which a GnuCOBOL program may be coded to pass an exit status value of 16 back to the operating system and then halt.
STOP RUN RETURNING 16MOVE 16 TO RETURN-CODE STOP RUNSTOP RUN WITH ERROR STATUS 16
STOP ERROR is a dialect specific way to abort the runtime.
Used in hard, non-recoverable error cases, for example when you pre-catch runtime exceptions "that should never happen" yourself, or for example if an API/socket/whatever endpoint does not exist/is not reachable. Depending on compile-time flags and runtime options you get the "common" abort handling (possibly creation of dump file, creation of core-dump, stop within GDB, stack-trace output, ...) and also error procedures registered with CBL_ERROR_PROC.
This is one of the dialect specific. -fstop-error-statement is set to "unconformable" for anything but GCOS. You can override that with -fstop-error-statement=ok.
See also CALL "CBL_RUNTIME_ERROR" routine.
STRING
STRING Syntax
=======================================================================
STRING { { literal-1 }... [ DELIMITED BY { SIZE } ] }...
~~~~~~ { identifier-1 } ~~~~~~~~~ { ~~~~ }
{ literal-2 }
{ identifier-2 }
INTO identifier-3 [ WITH POINTER identifier-4 ]
~~~~ ~~~~~~~
[ ON OVERFLOW imperative-statement-1 ]
~~~~~~~~
[ NOT ON OVERFLOW imperative-statement-2 ]
~~~ ~~~~~~~~
[ END-STRING ]
~~~~~~~~~~
=======================================================================
The STRING statement is used to concatenate all or a part of one or more strings together, forming a new string.
The reserved words
BY,ONandWITHare optional and may be omitted. The presence or absence of these words has no effect upon the program.All literals and identifiers (except for <identifier-4>) must be explicitly or implicitly defined with a
USAGE(see USAGE) ofDISPLAY. Any of the identifiers may be group items.The
POINTERdata item — <identifier-4> — must be a non-edited elementary integer numeric data item with a value greater than zero.Each <literal-1> / <identifier-1> will be referred to as a source item. The receiving data item is <identifier-3>.
The
STRINGstatement’s processing is based upon a current character pointer. The initial value of the current character pointer will be the value of <identifier-4> at the time theSTRINGstatement began execution. If noPOINTERclause is coded, a value of 1 (meaning “the 1st character position”) will be assumed for the current character pointer’s initial value.For each source item, the contents of the sending item will be copied — character-by-character — into <identifier-3> at the character position specified by the current character pointer. After each character is copied, the current character pointer will be incremented by 1 so that it points to the position within <identifier-3> where the next character should be copied.
The
DELIMITED BYclause specifies how much of each source item will be copied into <identifier-3>.DELIMITED BY SIZE(the default if noDELIMITED BYclause is specified) causes the entire contents of the source item to be copied into <identifier-3>.Using
DELIMITED BY literal-2orDELIMITED BY identifier-2causes only the contents of the source item up to but not including the character sequence specified by the literal or identifier to be copied.STRINGprocessing will cease when one of the following occurs:The initial value of the current character pointer is less than 1 or greater than the number of characters in <identifier-3>, or…
The value of the current character pointer exceeds the size of <identifier-3> at the point the STRING statement wants to copy a character into <identifier-3>, or…
All sending items have been fully processed
If event A occurs, <identifier-3> will remain unchanged.
The occurrence of either event A or B triggers what is referred to as an overflow condition.
The <identifier-3>) is neither automatically initialized (to spaces or any other value) at the start of a
STRINGstatement nor will it be space-filled should the total number of sending item characters copied into it be less than its size. You may explicitly initialize <identifier-3> yourself via theINITIALIZE(see INITIALIZE) orMOVE(see MOVE) statements before executing theSTRINGif you wish.The optional
ON OVERFLOWandNOT ON OVERFLOWclauses may be used to detect and react to the occurrence or not, respectively, of an overflow condition. See ON OVERFLOW + NOT ON OVERFLOW, for additional information.
SUBTRACT
SUBTRACT FROM
SUBTRACT FROM Syntax
=======================================================================
SUBTRACT { identifier-1 }... FROM { identifier-2 [ rounded-phrase ] }...
~~~~~~~~ { literal-1 } ~~~~
[ ON SIZE ERROR imperative-statement-1 ]
~~~~ ~~~~~
[ NOT ON SIZE ERROR imperative-statement-2 ]
~~~ ~~~~ ~~~~~
[ END-SUBTRACT ]
~~~~~~~~~~~~
=======================================================================
This format of the SUBTRACT statement generates the arithmetic sum of all arguments that appear before the FROM (<identifier-1> or <literal-1>) and subtracts that sum from each <identifier-2>.
The reserved words
ISandONare optional and may be omitted. The presence or absence of these words has no effect upon the program.Both <identifier-1> and <identifier-2> must be numeric unedited data items.
<literal-1> must be a numeric literal.
The optional
ROUNDED(see ROUNDED) clause available to each <identifier-2> will control how non-integer results will be saved.The optional
ON SIZE ERRORandNOT ON SIZE ERRORclauses may be used to detect and react to the failure or success, respectively, of an attempt to perform a calculation. In this case, failure is defined as being an <identifier-2> with an insufficient number of digit positions available to the left of any implied decimal point. See ON SIZE ERROR + NOT ON SIZE ERROR, for additional information.
SUBTRACT GIVING
SUBTRACT GIVING Syntax
=======================================================================
SUBTRACT { identifier-1 }... FROM { identifier-2 }
~~~~~~~~ { literal-1 } ~~~~ { literal-2 }
GIVING { identifier-3 [ rounded-phrase ] }...
~~~~~~
[ ON SIZE ERROR imperative-statement-1 ]
~~~~ ~~~~~
[ NOT ON SIZE ERROR imperative-statement-2 ]
~~~ ~~~~ ~~~~~
[ END-SUBTRACT ]
~~~~~~~~~~~~
=======================================================================
The SUBTRACT GIVING statement generates the arithmetic sum of all arguments that appear before the FROM (<identifier-1> or <literal-1>), subtracts that sum from the contents of <identifier-2> and then replaces the contents of the identifiers listed after the GIVING (<identifier-3>) with that result.
The reserved words
ISandONare optional and may be omitted. The presence or absence of these words has no effect upon the program.Both <identifier-1> and <identifier-2> must be numeric unedited data items.
<literal-1> must be a numeric literal.
<identifier-3> must be a numeric (edited or unedited) data item.
The optional
ROUNDED(see ROUNDED) clause available to each <identifier-3> will control how non-integer results will be saved.The optional
ON SIZE ERRORandNOT ON SIZE ERRORclauses may be used to detect and react to the failure or success, respectively, of an attempt to perform a calculation. In this case, failure is defined as being an <identifier-3> with an insufficient number of digit positions available to the left of any implied decimal point. See ON SIZE ERROR + NOT ON SIZE ERROR, for additional information.
SUBTRACT CORRESPONDING
SUBTRACT CORRESPONDING Syntax
=======================================================================
SUBTRACT CORRESPONDING identifier-1 FROM identifier-2 [ rounded-phrase ]
~~~~~~~~ ~~~~ ~~~~
[ ON SIZE ERROR imperative-statement-1 ]
~~~~ ~~~~~
[ NOT ON SIZE ERROR imperative-statement-2 ]
~~~ ~~~~ ~~~~~
[ END-SUBTRACT ]
~~~~~~~~~~~~
=======================================================================
The SUBTRACT CORRESPONDING statement generates code equivalent to individual SUBTRACT FROM statements for corresponding matches of data items found subordinate to the two identifiers.
The reserved words
ISandONare optional and may be omitted. The presence or absence of these words has no effect upon the program.Both <identifier-1> and <identifier-2> must be group items.
See CORRESPONDING, for information on how corresponding matches will be found between <identifier-1> and <identifier-2>.
The optional
ROUNDED(see ROUNDED) clause available to each <identifier-2> will control how non-integer results will be saved.The optional
ON SIZE ERRORandNOT ON SIZE ERRORclauses may be used to detect and react to the failure or success, respectively, of an attempt to perform a calculation. In this case, failure is defined as being an <identifier-2> with an insufficient number of digit positions available to the left of any implied decimal point. See ON SIZE ERROR + NOT ON SIZE ERROR, for additional information.
SUPPRESS
SUPPRESS Syntax
=======================================================================
SUPPRESS PRINTING
~~~~~~~~
=======================================================================
The SUPPRESS statement causes the presentation of a report group to be suppressed.
The reserved word
PRINTINGis optional and may be omitted. The presence or absence of this word has no effect upon the program.This statement may only appear within a
USE BEFORE REPORTINGprocedure (inDECLARATIVES(see DECLARATIVES)).SUPPRESSonly prevents the presentation of the report group within whoseUSE BEFORE REPORTINGprocedure the statement occurs.This statement must be executed each time presentation of the report group is to be suppressed.
When a report group’s presentation is suppressed, none of the following operations for the report will take place:
Actual presentation of the report group in question.
Processing of any
LINE(see LINE) clauses within the report group in question.Processing of the
NEXT GROUP(see NEXT GROUP) clause (if any) within the report group in question.Any modification to the
LINE-COUNTERspecial register (see Special Registers).Any modification to the
PAGE-COUNTERspecial register.
TERMINATE
TERMINATE Syntax
=======================================================================
INITIATE { report-name-1 }...
~~~~~~~~
=======================================================================
The TERMINATE statement causes the processing of the specified report(s) to be completed.
Each <report-name-1> must be the name of a report having an
RD(see REPORT SECTION) defined for it.The specified report name(s) must be currently initiated (via
INITIATE(see INITIATE)) and cannot yet have been terminated.The
TERMINATEstatement will present eachCONTROL FOOTING(if any), in reverse sequence of the control hierarchy, starting with the most minor up toFINAL(if any). During the presentation of these groups and the processing of anyUSE BEFORE REPORTINGprocedures for those groups, the prior set of control data item values will be available, as though a control break had been detected at the most major control data name.During the presentation of the
CONTROL FOOTINGgroups, any necessaryPAGE FOOTINGandPAGE HEADINGgroups will be presented as well.Finally,the
REPORT FOOTINGgroup, if any, will be presented.If an
INITIATEis followed by aTERMINATEwith no interveningGENERATE(see GENERATE) statements (all pertaining to the same report, of course), no report groups will be presented to the output file.
TRANSFORM
TRANSFORM Syntax
=======================================================================
TRANSFORM identifier-1 CHARACTERS FROM { literal-1 } TO { literal-2 }
~~~~~~~~~ ~~~~ { identifier-2 } ~~ { identifier-3 }
=======================================================================
The TRANSFORM statement scans a data item performing a series of mono-alphabetic substitutions, defined by the arguments before and after the TO clause.
Both <literal-1> and/or <literal-2> must be alphanumeric literals.
All of <identifier-1>, <identifier-2> and <identifier-3> must either be group items or alphanumeric data items. Numeric data items with a
USAGE(see USAGE) ofDISPLAYare accepted, but will generate warning messages from the compiler.The
TRANSFORMstatement will replace characters within <identifier-1> that are found in the string specified before theTOkeyword with the corresponding characters from the string specified after theTOkeyword.Usage of word CHARACTERS has no effect on operations other than for appearance.
This statement exists within GnuCOBOL to provide compatibility with COBOL programs written to pre-1985 standards. The
TRANSFORMstatement was made obsolete in the 1985 standard of COBOL, having been replaced by theCONVERTINGclause of theINSPECTstatement (see INSPECT). New programs should be coded to useINSPECT CONVERTINGrather thanTRANSFORM.
UNLOCK
UNLOCK Syntax
=======================================================================
UNLOCK filename-1 RECORD|RECORDS
~~~~~~
=======================================================================
This statement synchronizes any as-yet unwritten file I/O buffers to the specified file (if any) and releases any record locks held for records belonging to <file-name-1>.
The reserved words
RECORDandRECORDSare optional and may be omitted. The presence or absence of these words has no effect upon the program.If <file-name-1> is a Sort/Merge work file, no action will be taken.
Not all GnuCOBOL implementations support locking. Whether they do or not depends upon the operating system they were built for and the build options that were used when GnuCOBOL was generated. When a program using one of those GnuCOBOL implementations issues an UNLOCK, it will ignored. There will be no compiler message issued. Buffer syncing, if needed, will still occur.
For GnuCOBOL UNLOCK is implied in GnuCOBOL on file close so there’s no use to do it afterwards. A CLOSE will always trigger syncing the file to disk, too.
Doing UNLOCK before a close, will explicit unlock any records with a lock when running on INDEXED files, for other files it will release any locks on the file if it wasn’t opened for exclusive locking and will trigger syncing to disk (not done for any INDEXED file).
When using Linux and for that matter most *nix platforms, the system maintains it’s own cache and buffers for file processing so there can and most likely will be a short delay before all data is written out to disk.
See Record Locking, for additional information on record locking.
UNSTRING
UNSTRING Syntax
=======================================================================
UNSTRING { literal-0 }
~~~~~~~~ { identifier-1 }
[ DELIMITED BY [ ALL ] { literal-1 } [ OR [ ALL ] { literal-2 } ]... ]
~~~~~~~~~ ~~~ { identifier-2 } ~~ ~~~ { identifier-3 }
INTO { identifier-4 [ DELIMITER IN identifier-5 ] [ COUNT IN identifier-6 ] }...
~~~~ ~~~~~~~~~ ~~~~~
[ WITH POINTER identifier-7 ]
~~~~~~~
[ TALLYING IN identifier-8 ]
~~~~~~~~
[ ON OVERFLOW imperative-statement-1 ]
~~~~~~~~
[ NOT ON OVERFLOW imperative-statement-2 ]
~~~ ~~~~~~~~
[ END-UNSTRING ]
~~~~~~~~~~~~
=======================================================================
The UNSTRING statement parses a string, extracting any number of sub strings from it.
The reserved words
BY,INandONare optional and may be omitted. The presence or absence of these words has no effect upon the program.<identifier-1> through <identifier-5> must be explicitly or implicitly defined with a
USAGE(see USAGE) ofDISPLAY. Any of those identifiers may be group items.Both <literal-1> and <literal-2> must be alphanumeric literals.
Each of <identifier-6>, <identifier-7> and <identifier-8> must be elementary non-edited integer numeric items.
At the time the
UNSTRINGstatement begins execution, <identifier-7> must have a value greater than 0.<identifier-1> will be referred to as the source string and each <identifier-4> will be referred to as a destination field in the following discussions.
The
UNSTRINGstatement’s processing is based upon a current character pointer, the initial value of which will be the value of <identifier-7> at the time theUNSTRINGstatement began execution. If noPOINTERclause is coded, a value of 1 (meaning “the 1st character position”) will be assumed for the current character pointer’s initial value.The source string will be parsed into sub strings starting from the current character pointer position. Sub strings are identified by using the various delimiter strings specified on the
DELIMITED BYclause as inter-sub string separators.Using the
ALLoption allows a delimiter sequence to be an arbitrarily long sequence of occurrences of the delimiter literal whereas its absence treats each occurrence as a separate delimiter. When multiple delimiters are specified, they will be looked for in the source string in the sequence in which they are coded.Two consecutive delimiter sequences will identify a null sub string.
Identified sub strings will be moved into each destination field in the sequence they are identified; values moved into a destination field will be truncated if the sub string length exceeds the destination field length, or padded with spaces if the destination field length exceeds the sub string length. Both truncation and padding will be controlled by the presence or absence of a
JUSTIFIED(see JUSTIFIED) clause on the destination field.Each destination field may have an optional
DELIMITERclause. If aDELIMITERclause is specified, <identifier-5> will have the delimiter character string used to identify the sub string for the destination field moved into it. If a destination field was not altered (because an insufficient number of sub strings were identified), <identifier-5> for that destination field will also be unchanged.Each destination field may have an optional
COUNTclause. If aCOUNTclause is specified, <identifier-6> will have the size of the sub string (in characters) for the destination field moved into it. If a destination field was not altered (because an insufficient number of sub strings were identified), <identifier-6> for that destination field will also be unchanged. The COUNT/identifier-6 will be greater than the size of the destination field when the sub string length exceeds the destination field length. This condition is not detected by the ON OVERFLOW clause.If a
TALLYINGclause is coded, <identifier-8> will be incremented by 1 each time a destination field is populated.None of <identifier-4>, <identifier-5>, <identifier-6>, <identifier-7> or <identifier-8> are initialized by the
UNSTRINGstatement. You need to do that yourself via aMOVE(see MOVE) orINITIALIZEstatement (see INITIALIZE).UNSTRINGprocessing will cease when one of the following occurs:The initial value of the current character pointer is less than 1 or greater than the number of character positions in <identifier-1>, or…
All destination fields have been fully processed
If event A occurs, none of the destination field contents (or the contents of their
DELIMITERor <COUNT> identifiers) will be changed.An overflow condition exists if either event A occurs, or if event B occurs with at least one character position in <identifier-1> not having been processed.
The optional
ON OVERFLOWandNOT ON OVERFLOWclauses may be used to detect and react to the occurrence or not, respectively, of an overflow condition. See ON OVERFLOW + NOT ON OVERFLOW, for additional information.
The following sample program illustrates the UNSTRING statement statement.
IDENTIFICATION DIVISION.
PROGRAM-ID. DEMOUNSTRING.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Full-Name PIC X(40).
01 Parsed-Info.
05 Last-Name PIC X(15).
05 First-Name PIC X(15).
05 MI PIC X(1).
05 Delim-LN PIC X(1).
05 Delim-FN PIC X(1).
05 Delim-MI PIC X(1).
05 Count-LN BINARY-CHAR.
05 Count-FN BINARY-CHAR.
05 Count-MI BINARY-CHAR.
05 Tallying-Ctr BINARY-CHAR.
PROCEDURE DIVISION.
PERFORM UNTIL EXIT
DISPLAY "Enter Full Name (null quits):" WITH NO ADVANCING
ACCEPT Full-Name
IF Full-Name = SPACES
EXIT PERFORM
END-IF
INITIALIZE Parsed-Info
UNSTRING Full-Name DELIMITED BY ", " OR "," OR ALL SPACES
INTO Last-Name DELIMITER IN Delim-LN COUNT IN Count-LN
First-Name DELIMITER IN Delim-FN COUNT IN Count-FN
MI DELIMITER IN Delim-MI COUNT IN Count-MI
TALLYING Tallying-Ctr
DISPLAY "First-Name=" First-Name " Delim='" Delim-FN "' Count=" Count-FN
DISPLAY "MI =" MI " Delim='" Delim-MI "' Count=" Count-MI
DISPLAY "Last-Name =" Last-Name " Delim='" Delim-LN "' Count=" Count-LN
DISPLAY "Tally= " Tallying-Ctr
END-PERFORM
DISPLAY "Bye!"
STOP RUN .
The following is sample output from the program:
Enter Full Name (null quits):Cutler, Gary L
First-Name=Gary Delim=' ' Count=+004
MI =L Delim=' ' Count=+001
Last-Name =Cutler Delim=',' Count=+006
Tally= +003
Enter Full Name (null quits):Snoddgrass,Throckmorton,P
First-Name=Throckmorton Delim=',' Count=+012
MI =P Delim=' ' Count=+001
Last-Name =Snoddgrass Delim=',' Count=+010
Tally= +003
Enter Full Name (null quits):Munster Herman
First-Name=Herman Delim=' ' Count=+006
MI = Delim=' ' Count=+000
Last-Name =Munster Delim=' ' Count=+007
Tally= +002
Enter Full Name (null quits):
Bye!
WRITE
WRITE Syntax
=======================================================================
Format 1. For Sequential and Line Sequential files:
WRITE { record-name-1 [ FROM { identifier-1 } ] }
~~~~~ { [ ~~~~ { literal-1 } ] }
{ }
{ FILE file-name-1 FROM { identifier-1 } }
{ ~~~~ ~~~~ { literal-1 } }
[ { BEFORE } ADVANCING { { literal-2 } LINE|LINES } ]
[ { ~~~~~~ } { { identifier-2 } } ]
[ { AFTER } { PAGE } ]
[ ~~~~~ { ~~~~ } ]
[ { mnemonic-name-1 } ]
[ WITH [ NO ] LOCK ]
~~ ~~~~
[ AT END-OF-PAGE|EOP imperative-statement-1 ]
~~~~~~~~~~~ ~~~
[ NOT AT END-OF-PAGE|EOP imperative-statement-2 ]
~~~ ~~~~~~~~~~~ ~~~
[ END-WRITE ]
~~~~~~~~~
Format 2. For Indexed and Relative files:
WRITE { record-name-1 [ FROM { identifier-1 } ] }
~~~~~ { [ ~~~~ { literal-1 } ] }
{ }
{ FILE file-name-1 FROM { identifier-1 } }
{ ~~~~ ~~~~ { literal-1 } }
[ WITH [ NO ] LOCK ]
~~ ~~~~
[ INVALID KEY imperative-statement-3 ]
~~~~~~~
[ NOT INVALID KEY imperative-statement-4 ]
~~~ ~~~~~~~
[ END-WRITE ]
~~~~~~~~~
=======================================================================
The WRITE statement writes a new record to an open file.
The reserved words
ADVANCING,AT,KEY,LINE,LINESandWITHare optional and may be omitted. The presence or absence of these words has no effect upon the program.The reserved words
END-OF-PAGEandEOPare interchangeable.The <record-name-1> specified on the statement must be defined as an 01-level record subordinate to the File Description (
FD(see File/Sort-Description)) of a file that is currently open forOUTPUT(see File OPEN Modes),EXTENDorI-O.The optional
FROMclause will cause <literal-1> or <identifier-1> to be automatically moved into <record-name-1> prior to writing <record-name-1>’s contents to the appropriate file. If this clause is not specified, it is the programmer’s responsibility to populate <record-name-1> with the desired data prior to executing theWRITE.The optional
LOCKoptions may be used to manually control access to the just-written record by other programs while this program is running. See Record Locking, to review the various record locking behaviour.The optional
INVALID KEYandNOT INVALID KEYclauses may be used when writing to relative or indexed files to detect and react to the failure (non-zero file status code) or success (00 file status code), respectively, of the statement. See File Status Codes, for additional information.When
WRITEis used against anORGANIZATION LINE SEQUENTIAL(see ORGANIZATION LINE SEQUENTIAL) file, with or without theLINE ADVANCING(see LINE ADVANCING) option, an end-of-record delimiter character sequence will be written to the file to signify where one record ends and the next record begins. This delimiter sequence will be either of the following:A line-terminator sequence consisting of an ASCII carriage-return/line-feed character sequence (
X'0D0A') if you are running a MinGW or native Windows build of GnuCOBOLA line-terminator sequence consisting of an ASCII line-feed character (
X'0A') if you are running a Cygwin, Linux, Unix or OSX build of GnuCOBOL
The following points pertain to the use (or not) of the
ADVANCINGclause:Using this clause with any organization other than
ORGANIZATION LINE SEQUENTIALwill either be rejected outright by the compiler (relative or indexed files) or may introduce unwanted characters into the file (ORGANIZATION SEQUENTIAL(see ORGANIZATION SEQUENTIAL)).If no
ADVANCINGclause is specified on aWRITEto a line-advancing file,AFTER ADVANCING 1 LINEwill be assumed; on other than line-advancing files,BEFORE ADVANCING 1 LINEwill be assumed.When
BEFORE ADVANCINGis used (or implied), the record is written to the file before theADVANCINGaction writes line-terminator characters to the file.If
AFTER ADVANCINGis used (or implied), theADVANCINGaction writes line-terminator characters to the file and then the record data is written to the file.The
ADVANCING n LINESclause will introduce the specified number of line-terminator character sequences into the file either before the written record (AFTER ADVANCING) or after the written record (BEFORE ADVANCING).If the
LINAGE(see File/Sort-Description) clause is absent from the file’sFD:The
ADVANCING PAGEclause will introduce an ASCII formfeed character into the file either before the written record (AFTER PAGE) or after the written record (BEFORE PAGE).Management of areas on the printed page such as top-of page headers, bottom-of-page footers, dealing with “full page” situations and the like are the complete responsibility of the programmer.
If the LINAGE clause is present in the file’s
FD:The
ADVANCING PAGEclause will introduce the appropriate number of line-terminator character sequences into the file either before the written record (AFTER ADVANCING) or after the written record (BEFORE ADVANCING) so as to force the printer to automatically advance to a new sheet of paper when the file prints. No formfeed characters will be generated whenLINAGEis specified — instead, it is assumed that the printer to which the report will be printed will be loaded with special forms that conform to the specifications defined by theLINAGEclause.Management of areas on the printed page such as top-of page headers, bottom-of-page footers, dealing with “full page” situations and the like are now the joint responsibility of the programmer and the GnuCOBOL run-time library, which provides tools such as the
LINAGE-COUNTERspecial register (see Special Registers) and theEND-OF-PAGEclause to deal with page formatting issues.The
AT END-OF-PAGEclause will be triggered, thus executing <imperative-statement-1> (see Imperative Statement), if theWRITEstatement introduces a data line or line-feed character into the file at a line position within the Page Footer area defined by theLINAGEclause. TheNOT AT END-OF-PAGEclause will be triggered (thus executing <imperative-statement-2>) if no end-of-page condition occurred during theWRITE.
XML GENERATE
XML GENERATE Syntax
=======================================================================
XML GENERATE identifier-1 FROM identifier-2
~~~ ~~~~~~~~ ~~~~
[COUNT IN identifier-3]
~~~~~
[ WITH ENCODING codepage ]
~~~~~~~~
[ WITH XML-DECLARATION ]
~~~~~~~~~~~~~~~
[ WITH ATTRIBUTES ]
~~~~~~~~~~
[NAMESPACE IS {identifier-4 }[ NAMESPACE-PREFIX IS {identifier-5 }]
~~~~~~~~~ {literal-4 } ~~~~~~~~~~~~~~~~ {literal-5 }]]
[NAME OF {identifier-6 IS literal-6 } ... ]
~~~~
[TYPE OF {identifier-7 IS {ATTRIBUTE|ELEMENT|CONTENT}} ... ]
~~~~ ~~~~~~~~~ ~~~~~~~ ~~~~~~~
[SUPPRESS {identifier-8 [when-phrase] } ... ]
~~~~~~~~ {generic-suppression-phrase }
[ ON EXCEPTION imperative-statement-1 ]
~~~~~~~~~
[ NOT ON EXCEPTION imperative-statement-2 ]
~~~ ~~~~~~~~~
[ END-XML ]
~~~~~~~
when-phrase Format
WHEN { ZERO } [ [ OR ] { ZERO } ] ...
~~~~ { ZEROES } { ZEROES }
{ ZEROS } { ZEROS }
{ SPACE } { SPACE }
{ SPACES } { SPACES }
{ LOW-VALUE } { LOW-VALUE }
{ LOW-VALUES } { LOW-VALUES }
{ HIGH-VALUE } { HIGH-VALUE }
{ HIGH-VALUES } { HIGH-VALUES }
Generic-suppression-phrase Format
[[EVERY {NUMERIC [ATTRIBUTE|ELEMENT|CONTENT] } ] when-phrase ]
{NONNUMERIC [ATTRIBUTE|ELEMENT|CONTENT] }
{ATTRIBUTE }
{CONTENT }
{ELEMENT }
=======================================================================
The XML GENERATE statement creates an XML document based on the structure and content of the input data item. It takes as input a source data item to generate and store the corresponding XML document in a target data item. Both the source and receive data items must be declared in program’s Data Division. The XML generated document follows syntax rules described at http://www.w3.org/TR/xml.
Identifier-1 is an alphanumeric data item, it will contain the generated XML document output. It must be large enough to contain the generated XML document. Typically, it should be from five to ten times the size of identifier-2, depending on the length of the data-name or data-names within identifier-2. If identifier-1 is not large enough, an error condition exists at the end of the XML GENERATE statement (see XML-CODE).
If identifier-1 is longer than the generated XML document, only the initial part of identifier-1 changes. The rest of identifier-1 will contain the data that was present before this execution of the XML GENERATE statement. To avoid referring to that data, either initialize identifier-1 to spaces before the XML GENERATE statement or specify the COUNT IN phrase.
The element tag names in the XML documents generated from identifier-2 are derived from the name of the data item specified by identifier-2 and from any eligible data-names that are subordinate to identifier-2. The following rules apply:
The exact mixed-case spelling of data-names from the data description entry is retained. The spellings from any references to that data item (for example, in an OCCURS DEPENDING ON clause) are not used.
Data-names beginning with a digit are prefixed by an underscore. For example, the data-name 4C becomes XML tag name _4C.
Names of data items that contain characters that are illegal in XML version 1.0 are prefixed by hex., and the content itself is expressed in hexadecimal.
The XML declaration (header) is not generated. No extra white space, new line, etc. is inserted to make the generated XML more readable.
FROM.
The group or elementary data item identifier-2 is to be converted to the XML document. identifier-2 must not be described with the RENAMES clause. The following data items specified by identifier-2 are ignored by the XML GENERATE statement:
Any unnamed or FILLER data item with its subordinates.
Any elementary data item that assumes a pointer, e.g. USAGE POINTER.
Any data item (with its subordinates) subordinate to identifier-2 that is described with the REDEFINES clause.
Any group item (with its subordinates) subordinate to identifier-2 that contains a non-unique name within the same level.
Any group item that does not contain at least one elementary data item of category alphabetic, alphanumeric, numeric, or index.
The content of each elementary data item within identifier-2 is converted to character format.
Alphabetic, alphanumeric, alphanumeric-edited, external floating-point, and numeric-edited items are not converted.
Fixed-point numeric data items are converted as if they were moved to a numeric-edited item that has:
An explicit decimal point, if the numeric item has at least one decimal position.
The same number of decimal positions as the numeric item.
A leading ‘-’ picture symbol if the data item is signed and has an S in its PICTURE clause.
For COMPUTATIONAL-5 (COMP-5) binary data items, the number of integer positions depends on the number of ‘9’ symbols in the picture character string. If the data item has one to four ‘9’ picture symbols, the number of integer positions is five minus the number of decimal places. If the data item has five to nine ‘9’ picture symbols, the number of integer positions is ten minus the number of decimal places. If the data item has 10 to 18 ‘9’ picture symbols, the number of integer positions is 20 minus the number of decimal places.
All other fixed-point numeric data items will have as many integer positions as the numeric item, but with at least one integer position.
Internal floating-point data items are converted as if they were moved to a data item as follows:
For COMP-1: an external floating-point data item with PICTURE -9.9(8)E+99.
For COMP-2: an external floating-point data item with PICTURE -9.9(17)E+99 (illegal because of the number of digit positions).
Index data items are converted as if they were declared USAGE COMP-5 PICTURE S9(9). After conversion, leading and trailing spaces and leading zeroes are removed, as described under Data trimming.
After conversion, if a data item contains characters that are illegal in XML, the value in the data item before conversion or trimming is represented in hexadecimal, and an element tag name with the prefix "hex." is substituted for the regular tag name. For example, if data item Customer-Name is found at run time to contain LOW-VALUES, the XML element tag name ‘hex.Customer-Name’ is used instead of the normal ‘Customer-Name’, and the content is represented as a string of pairs of zero digits.
Any remaining instances of the five special characters & (ampersand), (apostrophe), > (greater-than sign), < (less-than sign), and (quotation mark) are converted into the equivalent XML references: &, ', >, <, and ", respectively.
Trailing spaces and leading zeroes are eliminated. Values converted from signed numeric values have their leading space removed if the value is positive. Values converted from numeric items have leading zeroes eliminated (after any initial minus sign). This is up to but not including the digit immediately before the actual or implied decimal point. Trailing zeroes after a decimal point are retained. For example: 012.340 becomes -12.340; 0000.45 becomes 0.45 ; 0013 becomes 13 ; 0000 becomes 0. Character values from alphabetic, alphanumeric data items have either trailing or leading spaces removed, depending on whether the corresponding data items have left or right justification, respectively left being the default. Trailing spaces are removed from values whose corresponding data items do not specify the JUSTIFIED clause. Leading spaces are removed from values whose data items do specify the JUSTIFIED clause. If a character value consists solely of spaces, all spaces are removed but one.
COUNT IN.
Identifier-3 contains the count of generated XML characters. It must be an integer data item and normally contains a length of the generated XML document in bytes.
Use the COUNT IN phrase to determine the total number of character positions, in bytes, that were generated. identifier-3 will then contain this information after XML GENERATE executes. You can use identifier-3 as a reference modification length field to refer to the part of identifier-2 that contains the generated XML document.
Identifier-1, identifier-2, identifier-3 must not overlap each other.
XML-CODE.
After execution of the XML GENERATE statement, the special register XML-CODE contains either zero, which indicates successful completion, or a non-zero exception code.
----------|-------------------------------------------------------------------------+ Exception code Description (decimal) ----------|-------------------------------------------------------------------------+ 0 The receiver contains the successfully generated XML document. The COUNT [IN] data item contains the count of character positions in the generated XML document. 400 The receiver was too small to contain the generated XML document. The COUNT IN data item, if specified, contains the count of character positions that were actually generated. 401 A DBCS data-name contained a character that, when converted to Unicode, was not valid in an XML element or attribute name. 402 The first character of a DBCS data-name, when converted to Unicode, was not valid as the first character of an XML element or attribute name. 403 The value of an OCCURS DEPENDING ON variable exceeded 16,777,215. 410 The CCSID (coded character set identifier) page specified by the CODEPAGE compiler option is not supported for conversion to Unicode. 411 The CCSID (coded character set identifier) specified by the CODEPAGE compiler option is not a supported single-byte CCSID. 414 The CCSID (coded character set identifier) specified for the XML document was invalid or was not supported. 415 The receiver was national, but the encoding specified for the document was not UTF-16. 416 The XML name space identifier contained invalid XML characters. 417 Element character content or an attribute value contained characters that are illegal in XML content. XML generation has continued, with the element tag name or the attribute name prefixed with 'hex.' and the original data value represented in the document in hexadecimal. 418 Substitution characters were generated by encoding conversion. 419 The XML name space prefix was invalid. 420 The receiver was alphanumeric and the input included national or DBCS data or names, but the encoding specified for the document was not 1208. 600 - 699 Internal error. Report the error to your service representative.The XML-CODE special register has the implicit definition
01 XML-CODE PICTURE S9(9)USAGE BINARY VALUE 0.If an error (XML-CODE NOT = 0) occurs during generation of the XML document, control is passed to the conditional statement imperative-statement-1. If ON EXCEPTION is not specified control is passed to the end of the XML GENERATE statement.
If no error (XML-CODE = 0) occurs during generation of the XML document, control is passed to the conditional statement imperative-statement-2. If NOT ON EXCEPTION is not specified, control is passed to the end of the XML GENERATE statement.
Example of the above :
01 wXML-DOCUMENT pic x(512). 01 wCHAR-COUNT pic 9(9) binary. 01 wSOURCE. 05 wA pic x(10) value "aaa". 05 wB. 10 wC pic x(10) value "ccc". 10 wD pic x(10) value "ddd". 05 wE pic x(10) value "eee". . . . XML GENERATE wXML-DOCUMENT FROM wSOURCE COUNT IN wCHAR-COUNT ON EXCEPTION DISPLAY 'XML generation error ' XML-CODE STOP RUN NOT ON EXCEPTION DISPLAY 'XML document generated.' wXML-DOCUMENT(1:wCHAR-COUNT) END-XML The code generates the following XML document: <wSOURCE><wA>aaa</wA><wB><wC>ccc</wC><wD>ddd</wD></wB><wE>eee</wE></wSOURCE>ENCODING, XML-DECLARATION
You can code the ENCODING phrase of the XML GENERATE statement to specify the coded character set identifier CCSID of the generated XML document. If you do not use the ENCODING phrase, the document encoding is determined by the category of the receiving data item and by the CODEPAGE compiler option. The XML-DECLARATION phrase causes the generated XML document to have an XML declaration that includes version information and an encoding declaration.
01 MESSAGE. 05 MSG PIC X(80) VALUE 'Hello COBOL!' XML GENERATE OUTPUT FROM MESSAGE WITH ENCODING 1208 WITH XML-DECLARATIONThe code above generates the following XML document:
<?XML VERSION=1.0" ENCODING=UTF-8"?><MESSAGE><MSG>Hello COBOL!</MSG></MESSAGE>If you do not code the XML-DECLARATION phrase, an XML declaration is not generated.
CCSID Description ----- ----------- 1208 UTF-8 1047 Latin 1 / Open Systems 1140, 37 USA, Canada, . . . Euro Country Extended Code Page (ECECP), Country Extended Code Page (CECP) 1141, 273 Austria, Germany ECECP, CECP 1142, 277 Denmark, Norway ECECP, CECP 1143, 278 Finland, Sweden ECECP, CECP 1144, 280 Italy ECECP, CECP 1145, 284 Spain, Latin America (Spanish) ECECP, CECP 1146, 285 UK ECECP, CECP 1147, 297 France ECECP, CECP 1148, 500 International ECECP, CECP 1149, 871 Iceland ECECP, CECPATTRIBUTES.
You can use the ATTRIBUTES phrase of the XML GENERATE statement to have each elementary data item included in the generated XML document to be expressed as an attribute of the XML element that corresponds to its immediately superordinate data item, rather than as a child element.
01 wXML-INPUT. 05 wNAME PIC X(10) VALUE "PETER". 05 wSALARY. 10 wBASIC PIC X(05) VALUE "20000". 10 wHRA PIC X(03) VALUE "3000". 05 wDEPT PIC X(03) VALUE "TRADE". XML GENERATE XML-OUT FROM wXML-INPUT WITH ATTRIBUTE.The code would then generate the following XML document, in which wNAME and wDEPT are expressed as attributes of element XML-INPUT and wBASIC and wHRA become attributes of element wSALARY
<wXML-INPUT wNAME=PETER wDEPT=TRADE> <wSALARY wBASIC=20000" wHRA=3000"></wSALARY> </wXML-INPUT>NAMESPACE and NAMESPACE-PREFIX
Use the NAMESPACE phrase to identify a namespace for the generated XML document. If the NAMESPACE phrase is not specified, or if identifier-4 has length zero or contains all spaces, the element names of XML documents produced by the XML GENERATE statement are not in any namespace.
Use the NAMESPACE-PREFIX phrase to qualify the start and end tag of each element in the generated XML document with a prefix.
If the NAMESPACE-PREFIX phrase is not specified, or if identifier-5 is of length zero or contains all spaces, the namespace specified by the NAMESPACE phrase specifies the default namespace for the document. In this case, the namespace declared on the root element applies by default to each element name in the document, including that of the root element. (Default namespace declarations do not apply directly to attribute names).
If the NAMESPACE-PREFIX phrase is specified, and identifier-5 is not of length zero and does not contain all spaces, then the start and end tag of each element in the generated document is qualified with the specified prefix. The prefix should therefore preferably be short. When the XML GENERATE statement is executed, the prefix must be a valid XML name, but without the colon ( : ), as defined in Namespaces in XML 1.0. at http://www.w3.org/TR/xml-names/#ns-decl. The prefix can have trailing spaces, which are removed before use.
Identifier-4, literal-4; identifier-5, literal-5
Identifier-4, literal-4: The namespace identifier, which must be a valid Uniform Resource Identifier (URI) as defined in Uniform Resource Identifier (URI): Generic Syntax at http://www.rfc-editor.org/rfc/rfc3986.txt.
Identifier-5,literal-5: The namespace prefix, which serves as an alias for the namespace identifier.
Identifier-4 and identifier-5 must reference data items of category alphanumeric.
Identifier-4 and identifier-5 must not overlap identifier-1 or identifier-3.
Literal-4 and literal-5 must be of category alphanumeric and must not be figurative constants.
For full details about namespaces, see Namespaces in XML 1.0 at http://www.w3.org/TR/xml-names/#ns-decl.
01 MESSAGE. 05 MSG PIC X(80) VALUE 'Hello COBOL!'. 01 NAME-SPACE PIC X(10) VALUE "HTTP://GNUCOBOL.COM". XML GENERATE OUTPUT FROM MESSAGE WITH ENCODING 1208 WITH XML-DECLARATIONThe code above generates the following XML document:
<MESSAGE XMLNS=HTTP://GNUCOBOL><MSG>Hello COBOL!</MSG></MESSAGE>If you do not specify a namespace, the element names in the generated XML document are not in any namespace.
01 wRegards. 05 msg pic x(80) value 'Hello,COBOL!'. 01 NS pic x(20) value 'http://sample'. 01 NP pic x(5) value 'pfx'. ... XML Generate Doc from Greeting namespace is NS namespace-prefix is NP <pfx:wRegards xmlns:pfx="http://sample"><pfx:msg>Hello,COBOL!</pfx:msg></pfx:wRegards>NAME.
Allows you to supply element and attribute names.
Identifier-6 must reference identifier-2 or one of its subordinate data items. It cannot be a function identifier and cannot be reference modified or subscripted. It must not specify any data item which is ignored by the XML GENERATE statement. For more information about identifier-2, see the description of identifier-2. If identifier-6 is specified more than once in the NAME phrase, the last specification is used.
Literal-6 must be an alphanumeric literal containing the attribute or element name to be generated in the XML document corresponding to identifier-6. It must be a valid XML local name.
TYPE.
Allows you to control attribute and element generation.
Identifier-7 must reference an elementary data item that is subordinate to identifier-2. It cannot be a function identifier and cannot be reference modified or subscripted. It must not specify any data item which is ignored by the XML GENERATE statement. For more information about identifier-2, see the description of identifier-2. If identifier-7 is specified more than once in the TYPE phrase, the last specification is used.
If the XML GENERATE statement also includes a WITH ATTRIBUTES phrase, the TYPE phrase has precedence for identifier-7.
When ATTRIBUTE is specified, identifier-7 must be eligible to be an XML attribute. identifier-7 is expressed in the generated XML as an attribute of the XML element immediately superordinate to identifier-7 rather than as a child element.
When ELEMENT is specified, identifier-7 is expressed in the generated XML as an element. The XML element name is derived from identifier-7 and the element character content is derived from the converted content of identifier-7 as described in Operation of XML GENERATE.
When CONTENT is specified, identifier-7 is expressed in the generated XML as element character content of the XML element that corresponds to the data item immediately superordinate to identifier-7. The value of the element character content is derived from the converted content of identifier-7 as described in Operation of XML GENERATE. When CONTENT is specified for multiple identifiers all corresponding to the same superordinate identifier, the multiple contributions to the element character content are concatenated.
The exact mixed-case spelling of data-names from the data description entry is retained.
You likely want to change the COBOL variable names to all lower case or use the NAME phrase for all data entries (at least if you expect it to be all in lower case as in your "target sample").
IDENTIFICATION DIVISION. PROGRAM-ID. XMLPROG. DATA DIVISION. WORKING-STORAGE SECTION. 01 TOTAL-CHAR PIC 9(05) VALUE 0. 01 x PIC X(200). 01 y. 03 z PIC X(15) VALUE "hello,COBOL!". 03 az PIC X(15) VALUE "goodbye, COBOL!". 03 ab. 05 abc PIC x(03) value spaces. PROCEDURE DIVISION. XML GENERATE x FROM y COUNT IN TOTAL-CHAR WITH XML-DECLARATION NAME OF abc IS "ABCDEF", z IS "zeta" TYPE OF z IS ATTRIBUTE SUPPRESS WHEN SPACES END-XML DISPLAY "0. [" TOTAL-CHAR "] COUNT" DISPLAY "1. [" FUNCTION TRIM(x) "]" XML GENERATE x FROM abc, NAME OF abc IS "sfdasd" DISPLAY "0. [" TOTAL-CHAR "] COUNT" DISPLAY "2. [" FUNCTION TRIM(x) "]" XML GENERATE x FROM ab, WITH ATTRIBUTES. DISPLAY "0. [" TOTAL-CHAR "] COUNT" DISPLAY "3. [" FUNCTION TRIM(x) "]" DISPLAY "4. [" x(1:TOTAL-CHAR) "]".SUPPRESS
Optionally, you can code the SUPPRESS phrase to specify whether individual data items are generated based on whether or not they meet certain criteria. If the SUPPRESS phrase is specified, identifier-1 must be large enough to contain the generated XML document before any suppression.
With the generic-suppression-phrase, elementary items subordinate to identifier-2 that are not otherwise ignored by XML GENERATE operations are identified generically for potential suppression.
Either items of class numeric, if the NUMERIC keyword is specified, or items that are not of class numeric, if the NONNUMERIC keyword is specified, or both, might be suppressed.
If the ATTRIBUTE keyword is specified, only items that would be expressed in the generated XML document as an XML attribute are identified for potential suppression.
If the ELEMENT keyword is specified, only items that would be expressed in the generated XML document as an XML element are identified for potential suppression.
If the CONTENT keyword is specified, only items that would be expressed in the generated XML document as element character content of the XML element corresponding to the data item superordinate to the CONTENT data item are identified for potential suppression.
If multiple generic-suppression-phrase are specified, the effect is cumulative.
Identifier-8 explicitly identifies items for potential suppression.
If the WHEN phrase is specified, identifier-8 must reference an elementary data item that is subordinate to identifier-2 and that is not otherwise ignored by the XML GENERATE operations. identifier-8 cannot be a function identifier and cannot be reference modified or subscripted.
If the WHEN phrase is omitted, identifier-8 can reference not only an elementary data item but also a group data item. That group data item and all data items that are subordinate to the group item are suppressed. If identifier-8 is specified more than once in the SUPPRESS phrase, the last specification is used. The explicit suppression specification for identifier-8 overrides the suppression specification that is implied by any generic-suppression-phrase, if identifier-8 is also one of the identifiers generically identified.
If identifier-8 is specified, the following rules apply to it:
If ZERO, ZEROES, or ZEROS is specified in the WHEN phrase, identifier-8 must not be of USAGE DISPLAY
If SPACE or SPACES is specified in the WHEN phrase, identifier-8 must be of USAGE DISPLAY, DISPLAY-1, or NATIONAL. If identifier-8 is a zoned or national decimal item, it must be an integer.
If LOW-VALUE, LOW-VALUES, HIGH-VALUE, or HIGH-VALUES is specified in the WHEN phrase, identifier-8 must be of USAGE DISPLAY. If identifier-8 is a zoned decimal item, it must be an integer.
If the generic-suppression-phrase is specified, data items are selected for potential suppression according to the following rules:
If ZERO, ZEROES, or ZEROS is specified in the WHEN phrase, all data items except those that are defined with USAGE DISPLAY-1 are selected.
If SPACE or SPACES is specified in the WHEN phrase, data items of USAGE DISPLAY, DISPLAY-1, or NATIONAL are selected. For zoned or national decimal items, only integers are selected.
If LOW-VALUE, LOW-VALUES, HIGH-VALUE, or HIGH-VALUES is specified in the WHEN phrase, data items of USAGE DISPLAY are selected. For zoned decimal items, only integers are selected.
When the SUPPRESS phrase is specified, a group item subordinate to identifier-2 is suppressed in the generated XML document if all the eligible items subordinate to the group item are suppressed or if, after suppressing any subordinate items, the XML corresponding to the group item would be an empty element with no attributes. The root element is always generated, even if all the items subordinate to identifier-2 are suppressed.
01 wG. 02 HiddenInfo. 03 SSN pic x(11) value '123-45-6789'. 03 HomeAddress pic x(50) value '123 Main St, Anytown, USA'. 02 Atable value spaces. 03 wA pic AAA occurs 5. 02 Btable value spaces. 03 wB pic XXX occurs 5. 02 Ctable value zeros. 03 wC pic 999 occurs 5. Move 'abc' to wA(1) Move 123 to wC(3) XML GENERATE wDoc from wG suppress HiddenInfo every nonnumeric element when space every numeric element when zero END-XML Generated document: <wG> <Atable><A>abc</A></Atable> <Ctable><C>123</C></Ctable> </wG>ON EXCEPTION and NOT ON EXCEPTION.
When an error occurs during XML document generation, an exception condition exists. An example of this is when identifier-1 is not large enough to contain the generated XML document. In this case, XML generation stops and the content of the receiver, identifier-1, is undefined. If the COUNT IN phrase was specified, identifier-3 contains the number of character positions that were generated. This can range from zero to the length of identifier-1.
If the ON EXCEPTION phrase is specified, control is transferred to imperative-statement-1. If it is not specified, NOT ON EXCEPTION phrases are ignored, and control is transferred to the end of the XML GENERATE statement.
At termination of an XML GENERATE statement, special register XML-CODE contains either 0, indicating successful completion of XML generation, or a non-zero error code, indicating that an exception occurred during XML generation.
If no exception conditions arise during generation of the XML document, control is passed to imperative-statement-2, if specified, or to the end of the XML GENERATE statement. If an ON EXCEPTION phrase is specified, it is ignored. Special register XML-CODE contains a zero after the XML GENERATE statement has finished executing.
END-XML
Is an explicit scope terminator that delimits the scope of XML GENERATE statement. With END-XML, conditional XML GENERATE statements can be nested in other conditional statements. Conditional XML GENERATE statements specify the ON EXCEPTION or NOT ON EXCEPTION phrase.
The scope of a conditional XML GENERATE or XML PARSE statement is terminated by:
An END-XML phrase at the same level of nesting
A separator period
NESTED XML GENERATE STATEMENTS.
When a given XML GENERATE statement appears as imperative-statement-1 or imperative-statement-2, or as part of imperative-statement-1 or imperative-statement-2 of another XML GENERATE statement, that given XML GENERATE statement is a nested XML GENERATE statement.
Nested XML GENERATE statements are considered to be matched XML GENERATE and END-XML combinations proceeding from left to right. For this reason, when END-XML phrases are encountered, they are matched with the nearest preceding XML GENERATE statements that have not already been terminated.
XML PARSE
XML PARSE Syntax
=======================================================================
XML PARSE identifier-1
~~~ ~~~~~
[ WITH ENCODING codepage ]
~~~~~~~~
[ RETURNING NATIONAL ]
~~~~~~~~~ ~~~~~~~~
[ VALIDATING WITH identifier-2 ]
~~~~~~~~~~
PROCESSING PROCEDURE IS procedure-name-1 [ { THROUGH } procedure-name-2 ]
~~~~~~~~~~ ~~~~~~~~~ [ { ~~~~~~~ } ]
[ { THRU } ]
~~~~
[ ON EXCEPTION imperative-statement-1 ]
~~~~~~~~~
[ NOT ON EXCEPTION imperative-statement-2 ]
~~~ ~~~~~~~~~
[ END-XML ]
~~~~~~~
=======================================================================
The XML PARSE statement starts an event-driven XML parser, the processing procedure is performed as each component of the XML document is identified in order.
This statement is not available in the runtime yet and will raise a XML exception during execution.
Footnotes
Using a
GO TOstatement to prematurely terminate a sort, or re-starting a previously-cancelled sort is not considered good programming style and should be avoided.↩︎To prematurely terminate a sort, or re-starting a previously-cancelled sort is not considered good programming style and should be avoided.↩︎