COBOL is a reserved word rich language. The OpenCOBOL compiler recognizes:
Reserved Words
514 words in OC 1.1, 136 of which are marked not yet implemented.
378 functional reserved words, as of August 2008.
Makes data available from the keyboard or operating system to named data items.
OpenCOBOL supports both standard and extended ACCEPT statements.
Most extended ACCEPT statements will require an advanced terminal screen
initialization, which can obscure CONSOLE input and output.
ACCEPT variable FROM CONSOLE.
ACCEPT variable FROM ENVIRONMENT "path".
ACCEPT variable FROM COMMAND LINE.
ACCEPT variable AT 0101.
ACCEPT screen-variable.
ACCEPT today FROM DATE.
ACCEPT today FROM DATE YYYYMMDD.
Defines a file’s access mode. One of DYNAMIC, RANDOM, or SEQUENTIAL.
SELECT filename
ASSIGN TO "filename.dat"
ACCESS MODE IS RANDOM
RELATIVE KEY IS keyfield.
Not yet implemented. Object COBOL feature.
Sums two or more numerics, with an eye toward financial precision and
error detection.
ADD 1 TO cobol GIVING OpenCOBOL END-ADD.
ADD
a b c d f g h i j k l m n o p q r s t u v w x y z
GIVING total-of
ON SIZE ERROR
PERFORM log-problem
NOT ON SIZE ERROR
PERFORM graph-result
END-ADD
Allows program access to memory address reference and, under controlled
conditions, assignment.
SET pointer-variable TO ADDRESS OF linkage-store.
SET ADDRESS OF based-var TO ADDRESS OF working-var
Programmer control of newline output and paging.
DISPLAY "Legend: " WITH NO ADVANCING END-DISPLAY.
WRITE printrecord AFTER ADVANCING PAGE END-WRITE.
Nested PERFORM clause and can influence when loop conditional testing
occurs.
PERFORM
WITH TEST AFTER
VARYING variable FROM 1 BY 1
UNTIL variable > 10
AFTER inner FROM 1 BY 1
UNTIL inner > 4
DISPLAY variable ", " inner END-DISPLAY
END-PERFORM.
Will display 55 lines of output. 1 to 11 and 1 to 5. Removing the
WITH TEST AFTER clause would cause 40 lines of output. 1 to 10 and 1 to 4.
Not yet implemented feature that will influence the internal alignment of
not yet implemented USAGE BIT fields.
A multipurpose reserved in context word.
INSPECT variable REPLACING ALL "123" WITH "456".
MOVE ALL QUOTES TO var.
Allocates actual working storage for a BASED element.
ALLOCATE based-var INITIALIZED RETURNING pointer-var.
* Set up for a mixed case SORT COLLATING SEQUENCE IS
CONFIGURATION SECTION.
SPECIAL-NAMES.
ALPHABET name IS "AaBbCcDdEe..".
One of the OpenCOBOL data class (category) tests.
IF variable IS ALPHABETIC
DISPLAY "alphabetic" END-DISPLAY
END-IF
ALPHABETIC is defined as a data item that uses only A in the
PICTURE clause. Finding examples of ALPHABETIC data use is difficult,
which means this type is rarely used, favouring ALPHANUMERIC instead.
When tested, only data that are upper case A to Z and lower case a to z
will return true, all others, including any digits 0 to 9 will return false.
One of the OpenCOBOL data class (category) tests.
IF variable IS ALPHABETIC-LOWER
DISPLAY "alphabetic-lower" END-DISPLAY
END-IF
One of the OpenCOBOL data class (category) tests.
DISPLAY variable "alphabetic-upper " WITH NO ADVANCING
IF variable IS ALPHABETIC-UPPER
DISPLAY "true A-Z, and nothing but A to Z" END-DISPLAY
ELSE
DISPLAY "false A-Z, something else in here" END-DISPLAY
END-IF
INITIALIZE data-record REPLACING ALPHANUMERIC BY literal-value
INITIALIZE data-record
REPLACING ALPHANUMERIC-EDITED BY identifier-1
A powerful, multiple conditional expression feature of EVALUATE.
EVALUATE variable ALSO second-test
WHEN "A" ALSO 1 THRU 5 PERFORM first-case
WHEN "A" ALSO 6 PERFORM second-case
WHEN "A" ALSO 7 THRU 9 PERFORM third-case
WHEN OTHER PERFORM invalid-case
END-EVALUATE
Obsolete and once unsupported verb that modifies the jump target for GO TO
statements.
Yeah, just don’t. Unless you are writing a state machine engine, maybe.
ALTER should rarely be used in COBOL applications.
Rumour is, 1.1 may support this verb, to increase support for legacy
code, and NOT as homage to a good idea. But to be honest, I do look
forward to seeing the first OpenCOBOL Flying Spaghetti Monster for the
giggles of righteous indignation.
Reality is, 2.0 does support ALTER. NIST Test Suite passes over 9,700 tests,
up from just under 9,100 with 1.1.
Defines an ALTERNATE key for ISAM data structures.
SELECT file
ASSIGN TO filename
ACCESS MODE IS RANDOM
RECORD KEY IS key-field
ALTERNATE KEY IS alt-key WITH DUPLICATES.
COBOL rules of precedence are; NOT, AND, OR.
IF field = "A" AND num = 3
DISPLAY "got 3" END-DISPLAY
END-IF
COBOL also allows abbreviated combined relational conditions.
IF NOT (a NOT > b AND c AND NOT d)
code
END-IF
is equivalent to
IF NOT (((a NOT > b) AND (a NOT > c)) AND (NOT (a NOT > d)))
code
END-IF
Allows for any value is TRUE in an EVALUATE statement.
EVALUATE TRUE ALSO TRUE
WHEN a > 3 ALSO ANY *> b can be any value **
PERFORM a-4-b-any
WHEN a = 3 ALSO b = 1
PERFORM a-3-b-1
END-EVALUATE
Not yet implemented. Will allow case insentive match of currency
symbols with FUNCTION NUMVAL-C.
Allows for multiple conditional VALUES.
01 cond-1 PIC X.
88 first-truth VALUES ARE "A" "B" "C".
88 second-truth VALUES ARE "X" "Y" "Z".
Controls SORT, MERGE and RECORD data definitions.
I-O-CONTROL.
SAME RECORD AREA FOR file1, file2.
Plural readability option for AREA
Holds the number of OS parsed command line arguments, and can act as the
explicit index when retrieving ARGUMENT-VALUE data. ARGUMENT-NUMBER can be
used in ACCEPT FROM and DISPLAY UPON expressions.
ACCEPT command-line-argument-count FROM ARGUMENT-NUMBER END-ACCEPT
DISPLAY 2 UPON ARGUMENT-NUMBER END-DISPLAY
ACCEPT indexed-command-line-argument FROM ARGUMENT-VALUE END-ACCEPT
See COMMAND-LINE for more information on the unparsed command invocation
string.
Returns the next command line argument. This post from John on
opencobol.org is an excellent idiom for parsing command line arguments
without too much worry as to the order.
>>source format is free
*>*****************************************************************
*> Author: jrls (John Ellis)
*> Date: Nov-2008
*> Purpose: command line processing
*>*****************************************************************
identification division.
program-id. cmdline.
data division.
*>
working-storage section.
*>******************************************
01 argv pic x(100) value spaces.
88 recv value "-r", "--recv".
88 email value "-e", "--email".
88 delivered value "-d", "--delivered".
01 cmdstatus pic x value spaces.
88 lastcmd value "l".
01 reptinfo.
05 rept-recv pic x(30) value spaces.
05 rept-howsent pic x(10) value spaces.
*>
procedure division.
0000-start.
*>
perform until lastcmd
move low-values to argv
accept argv from argument-value
if argv > low-values
perform 0100-process-arguments
else
move "l" to cmdstatus
end-if
end-perform
display reptinfo.
stop run.
*>
0100-process-arguments.
*>
evaluate true
when recv
if rept-recv = spaces
accept rept-recv from argument-value
else
display "duplicate " argv
end-if
when email
move "email" to rept-howsent
when delivered
move "delivered" to rept-howsent
when other display "invalid switch: " argv
end-evaluate.
Example run:
./cmdline --recv "john ellis" -e -f
invalid switch: -f
john ellis email
PROGRAM-ID. program-name AS literal.
COBOL table suport.
01 CLUBTABLE.
05 MEMBER-DATA OCCURS 1 TO 6000000000 TIMES
DEPENDING ON PEOPLE
ASCENDING KEY IS HOURS-DONATED.
Assign a name to a file or other external resource.
SELECT input-file
ASSIGN TO "filename.ext"
The actual filename used is dependent on a configuration setting.
Under default configuration settings, filename-mapping is set to yes.
See What are the OpenCOBOL compile time configuration files? for details.
# If yes, file names are resolved at run time using
# environment variables.
# For example, given ASSIGN TO "DATAFILE", the actual
# file name will be
# 1. the value of environment variable 'DD_DATAFILE' or
# 2. the value of environment variable 'dd_DATAFILE' or
# 3. the value of environment variable 'DATAFILE' or
# 4. the literal "DATAFILE"
# If no, the value of the assign clause is the file name.
#
# Value: 'yes', 'no'
filename-mapping: yes
So, under GNU/Linux, bash shell
$ export DD_DATAFILE='/tmp/opencobol.dat'
$ ./myprog
the program will find the data in /tmp/opencobol.dat
$ export DD_DATAFILE='/tmp/other.dat'
$ ./myprog
this run of the same program will find the data in /tmp/other.dat
As shown in the sample .conf comments, the order of environment variable
lookup proceeds through three enviroment variables before using a literal
as the filename.
- DD_DATAFILE
- dd_DATAFILE
- DATAFILE
- and finally “DATAFILE”
where DATAFILE is the name used in
and can be any valid COBOL identifier, or string leading to a valid
operating system filename.
Controls position of ACCEPT and DISPLAY screen oriented verbs.
*> Display at line 1, column 4 <*
DISPLAY "Name:" AT 0104 END-DISPLAY
*> Accept starting at line 1, column 10 for length of field <*
ACCEPT name-var AT 0110 END-ACCEPT
Not yet implemented, but when it is, it will allow
SET screen-name ATTRIBUTE BLINK OFF
Automatic cursor flow to next field in screen section.
Not yet implemented BIT field operation. See What STOCK CALL LIBRARY does
OpenCOBOL offer? CBL_OR for alternatives allowing bitwise operations.
For example:
OCOBOL >>SOURCE FORMAT IS FIXED
*> ***************************************************************
*> Author: Brian Tiffin
*> Date: 20110626
*> Purpose: Demonstrate alternative for B-OR
*> Tectonics: cobc -x bits.cob
*> ***************************************************************
identification division.
program-id. bits.
data division.
working-storage section.
01 s1 pic 999 usage comp-5.
01 t2 pic 999 usage comp-5.
01 len pic 9.
01 result usage binary-long.
*> ***************************************************************
procedure division.
move 2 to s1
move 4 to t2
move 1 to len
*> CBL_OR takes source, target and length value 2 OR 4 is 6. **
call "CBL_OR" using s1 t2 by value len returning result end-call
display s1 space t2 space len space result end-display
goback.
end program bits.
giving:
$ cobc -x bits.cob
$ ./bits
002 006 1 +0000000000
For a COBOL source code solution to BIT operations, Paul Chandler was nice
enough to publish BITWISE.cbl and a full listing is included at BITWISE.
05 BLANK SCREEN BACKGROUND-COLOR 7 FOREGROUND-COLOR 0.
01 based-var PIC X(80) BASED.
A sample posted by [human]
OCOBOL*-----------------------------------------------------------------
IDENTIFICATION DIVISION.
PROGRAM-ID. 'MEMALL'.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SPECIAL-NAMES. DECIMAL-POINT IS COMMA.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
DATA DIVISION.
FILE SECTION.
*
WORKING-STORAGE SECTION.
*
77 mychar pic x.
01 REC-TEST BASED.
03 REC-TEST-PART1 PIC X(5500000).
03 REC-TEST-PART2 PIC X(0100000).
03 REC-TEST-PART3 PIC X(1200000).
03 REC-TEST-PART4 PIC X(1200000).
03 REC-TEST-PART5 PIC X(1700000).
*-----------------------------------------------------------------
LINKAGE SECTION.
*-----------------------------------------------------------------
PROCEDURE DIVISION.
declaratives.
end declaratives.
*-----------------------------------------------------------------
main section.
00.
FREE ADDRESS OF REC-TEST
display 'MEMALL loaded and REC-TEST FREEd before ALLOCATE'
accept mychar
*
IF ADDRESS OF REC-TEST = NULL
display 'REC-TEST was not allocated before'
ELSE
display 'REC-TEST was allocated before'
END-IF
accept mychar
*
ALLOCATE REC-TEST
move all '9' to REC-TEST
display 'REC-TEST allocated and filled with '
REC-TEST (1:9)
end-display
accept mychar
*
IF ADDRESS OF REC-TEST = NULL
display 'REC-TEST was not allocated before'
ALLOCATE REC-TEST
display 'REC-TEST allocated again, filled with '
REC-TEST (1:9)
end-display
ELSE
display 'REC-TEST was allocated before'
END-IF
accept mychar
*
*
FREE ADDRESS OF REC-TEST
display 'REC-TEST FREEd'
accept mychar
*
stop run
*
continue.
ex. exit program.
*-----------------------------------------------------------------
*--- End of program MEMALL ---------------------------------------
Ring the terminal bell during DISPLAY output. Alias for BELL
DISPLAY "Beeeeep" LINE 3 COLUMN 1 WITH BEEP END-DISPLAY.
Sets up a PERFORM loop to test the conditional before execution of the
loop body. See AFTER for the alternative. BEFORE is the default.
MOVE 1 TO counter
PERFORM WITH TEST BEFORE
UNTIL counter IS GREATER THAN OR EQUAL TO limiter
CALL "subprogram" USING counter RETURNING result END-CALL
MOVE result TO answers(counter)
ADD 1 TO counter END-ADD
END-PERFORM
Also used with the WRITE verb.
WRITE record-name
BEFORE ADVANCING some-number LINES
And to control how the INSPECT verb goes about its job.
INSPECT character-var TALLYING
the-count FOR ALL "tests" BEFORE "prefix"
And not currently (February 2013) supported, in the declaratives for REPORT SECTION
control.
Ring the terminal bell during DISPLAY output. Alias for BEEP
DISPLAY "Beeeeep" LINE 3 COLUMN 1 WITH BELL END-DISPLAY.
01 result PIC S9(8) USAGE BINARY
With OpenCOBOL’s tight integration with the C Application Binary Interface
the compiler authors have built in support that guarantees a native system
C long value being the same bit size between COBOL and C modules. This
increases coverage of the plethora of open C library functions that can
be directly used with the CALL verb. Including cases where callback
functions that require long stack parameters (that can’t as easily be
wrapped in thin C code layers) can now be used more effectively and safely.
Defines an 8 bit usage item.
Defines a 64 bit usage item.
32 bit native USAGE modifier. Equivalent to S9(8).
16 bit native USAGE. Equivalent to S9(5).
05 BLANK SCREEN BACKGROUND-COLOR 7 FOREGROUND-COLOR 0.
FD file-name
BLOCK CONTAINS 1 TO n RECORDS
As yet unsupported modifier.
A LINAGE setting.
FD mini-report
linage is 16 lines
with footing at 15
lines at top 2
lines at bottom 2.
PERFORM the-procedure
VARYING step-counter FROM 1 BY step-size
UNTIL step-counter > counter-limit
Human inscisors average about 16mm.
More to the point, the BYTE-LENGTH returns the length, in bytes,
of a data item. See FUNCTION BYTE-LENGTH
The OpenCOBOL CALL verb accepts literal or identifier stored names when
resolving the transfer address. The USING phrase allows argument passing
and OpenCOBOL includes internal rules for the data representation of the
call stack entities that depend on the COBOL PICTURE and USAGE clauses.
Return values are captured with RETURNING identifier. See
What STOCK CALL LIBRARY does OpenCOBOL offer?.
For more information see
http://www.opencobol.org/modules/bwiki/index.php?cmd=read&page=UserManual%2F2_3#content_1_0
CALL is the verb that opens up access to the plethora of C based ABI
libraries. A plethora, and the standard C library is accessible without
explicit linkage as a bonus.
One item of note is C pointers. Especially those passed around as handles.
When calling a C routine that returns a handle, the RETURNING identifier will
receive a C pointer. To use that handle in later CALLs, the argument from
COBOL should usually by passed BY VALUE. This passes the C pointer, not the
address of the COBOL identifier as the default BY REFERENCE argument handling
would do.
Below is a sample that allows fairly carefree use of CBL_OC_DUMP during
development. ON EXCEPTION CONTINUE.
OCOBOL*>>SOURCE FORMAT IS FIXED
*> ***************************************************************
*> Author: Brian Tiffin
*> Date: 20110701
*> Purpose: Try C library formatted printing, and CALL exception
*> Tectonics: cobc -x callon.cob
*> or cobc -x callon.cob CBL_OC_DUMP.cob
*> ***************************************************************
identification division.
program-id. callon.
data division.
working-storage section.
01 result usage binary-long.
01 pie usage float-short.
01 stuff pic x(12) value 'abcdefghijkl'.
*> ***************************************************************
procedure division.
move 3.141592654 to pie
*> Get a dump of the memory at pie, but don't stop if not linked
call "CBL_OC_DUMP" using pie 4 on exception continue end-call
*> Call C's printf, abort if not available
call static "printf" using
"float-short: %10.8f" & x"0a00"
by value pie
returning result
end-call
display pie space length of pie space result end-display
*> Get a dump of the memory used by stuff, don't stop if no link
call "CBL_OC_DUMP" using stuff 12 on exception continue end-call
*> Get a dump of the memory used by stuff, abort if not linked <*
call "CBL_OC_DUMP" using stuff 12 end-call
goback.
end program callon.
See What is CBL_OC_DUMP? for details of the subprogram.
A runtime session shows:
$ cobc -x callon.cob
$ ./callon
float-short: 3.14159274
3.1415927 4 +0000000024
libcob: Cannot find module 'CBL_OC_DUMP'
$ cobc -x callon.cob CBL_OC_DUMP.cob
$ ./callon
Offset HEX-- -- -- -5 -- -- -- -- 10 -- -- -- -- 15 -- CHARS----1----5-
000000 db 0f 49 40 ..I@............
float-short: 3.14159274
3.1415927 4 +0000000024
Offset HEX-- -- -- -5 -- -- -- -- 10 -- -- -- -- 15 -- CHARS----1----5-
000000 61 62 63 64 65 66 67 68 69 6a 6b 6c abcdefghijkl....
Offset HEX-- -- -- -5 -- -- -- -- 10 -- -- -- -- 15 -- CHARS----1----5-
000000 61 62 63 64 65 66 67 68 69 6a 6b 6c abcdefghijkl....
So, the first CALL to CBL_OC_DUMP doesn’t ‘fail’ as the ON EXCEPTION CONTINUE
traps the condition and lets the program carry on without a dump displayed.
The last CALL does abend the program with ‘Cannot find module’ when CBL_OC_DUMP
is not compiled in.
Virtual cancel of a module is supported. Physical cancel support is on the
development schedule.
A control clause of the as yet unsupported COMMUNICATION DIVISION.
An as yet unsupported keyword.
Shortform for CONTROL FOOTING, a clause used in REPORT SECTION.
Shortform for CONTROL HEADING, a clause used in PAGE descriptors in the
REPORT SECTION.
Invokes a subprogram, with no return of control implied. The chained
program unit virtually becomes the main program within the run unit.
Passes procedure division data through WORKING-STORAGE and can
be used for shell command line arguments as well, as in
CALL “myprog” USING string END-CALL.
from opencobol.org by human
WORKING-STORAGE SECTION.
01 cmd-argument.
02 some-text pic x(256).
procedure division Chaining cmd-argument.
display 'You wrote:'
'>"' function trim(some-text) '"'
'from shell command line'
end-display
A soon to be obsolete feature.
A multi use keyword.
Used in SPECIAL-NAMES
OCOBOL >>SOURCE FORMAT IS FIXED
*> ***************************************************************
*> Author: Brian Tiffin
*> Date: 20101031
*> Purpose: Try out SYMBOLIC CHARACTERS
*> Tectonics: cobc -x figurative.cob
*> Rave: OpenCOBOL is stone cold cool
*> ***************************************************************
identification division.
program-id. figurative.
environment division.
configuration section.
special-names.
symbolic characters TAB is 10
LF is 11
CMA is 45.
data division.
working-storage section.
01 a-comma pic x(1) value ",".
01 lots-of-commas pic x(20).
*> ***************************************************************
procedure division.
display
"thing" TAB "tabbed thing" LF
"and" TAB "another tabbed thing" LF
"other" CMA " things"
end-display
move a-comma to lots-of-commas
display "MOVE a-comma : " lots-of-commas end-display
move CMA to lots-of-commas
display "MOVE symbolic: " lots-of-commas end-display
goback.
end program figurative.
Output:
$ cobc -x figuratives.cob
$ ./figuratives
thing tabbed thing
and another tabbed thing
other, things
MOVE a-comma : ,
MOVE symbolic: ,,,,,,,,,,,,,,,,,,,,
Used in INSPECT
INSPECT str TALLYING tal FOR CHARACTERS
Used in a File Description FD
FD file-name
BLOCK CONTAINS integer-1 TO integer-2 CHARACTERS
RECORD IS VARYING IN SIZE FROM integer-5 TO integer-6 CHARACTERS
DEPENDING ON identifier-1.
Used to create alphabets in SPECIAL-NAMES.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SPECIAL-NAMES.
CLASS octals IS '0' THRU '7'.
...
PROCEDURE DIVISION.
IF user-value IS NOT octals
DISPLAY "Sorry, not a valid octal number" END-DISPLAY
ELSE
DISPLAY user-value END-DISPLAY
END-IF
An as yet unsupported Object COBOL class identifier clause.
An as yet unsupported source code internationalization clause.
Close an open file. OpenCOBOL will implicitly close all open resources
at termination of a run unit and will display a warning message
stating so, and the danger of potentially unsafe termination.
A syntactically recognized, but as yet unsupported clause of a
report descriptor, RD.
An as yet unsupported data internationalization clause.
Allows definition within a program unit of a character set.
OBJECT-COMPUTER. name.
PROGRAM COLLATING SEQUENCE IS alphabet-1.
- A recognized but unsupported REPORT SECTION RD descriptor clause.
- Also used for positional DISPLAY and ACCEPT, which implicitly uses
SCREEN SECTION style ncurses screen IO.
DISPLAY var-1 LINE 1 COLUMN 23 END-DISPLAY
A recognized but as yet unsupported RD clause.
A SPECIAL-NAMES clause supporting commas in numeric values versus the
default period decimal point. COBOL was way ahead of the internationization
curve, and this feature has caused compiler writers no little grief in its time,
a challenge they rise to and deal with for the world’s benefit.
Provides access to command line arguments.
ACCEPT the-args FROM COMMAND-LINE END-ACCEPT
Flushes ALL current locks, synching file I/O buffers. OpenCOBOL supports
safe transactional processing with ROLLBACK capabilities. Assuming the
ISAM handler configured when building the compiler can support LOCK_
PROGRAM-ID. CBL_OC_PROGRAM IS COMMON PROGRAM.
Ensures a nested sub-program is also available to other nested sub-programs
with a program unit heirarchy.
Implementors choice; OpenCOBOL is a big-endian default. With most Intel
personal computers and operating systems like GNU/Linux, COMPUTATIONAL-5
will run faster.
Equivalent to PACKED DECIMAL. Packed decimal is two digits per byte,
always sign extended and influenced by a .conf setting binary-size
COMPUTATIONAL-6 is UNSIGNED PACKED.
Computational arithmetic.
COMPUTE circular-area = radius ** 2 * FUNCTION PI END-COMPUTE
OpenCOBOL supports the normal gamut of arithmetic expressions.
- Add +
- Subtract -
- Multiply *
- Divide /
- Raise to power **
Order of precedence rules apply.
- unary minus, unary plus
- exponentiation
- multiplication, division
- addition, subtraction
Spaces and expressions
Due to COBOL allowing dash in user names, care must be taken to
properly space arithmetic expressions.
Some examples of seemingly ambiguous and potentially dangerous code
OCOBOL*> ***************************************************************
identification division.
program-id. computing.
data division.
working-storage section.
01 answer pic s9(8).
01 var pic s9(8).
*> ***************************************************************
procedure division.
compute answer = 3*var-1 end-compute
goback.
end program computing.
That is NOT three times var minus one, OpenCOBOL will complain.
$ cobc -x computing.cob
computing.cob:18: Error: 'var-1' is not defined
whew, saved!
OCOBOL*> ***************************************************************
identification division.
program-id. computing.
data division.
working-storage section.
01 answer pic s9(8).
01 var pic s9(8).
01 var-1 pic s9(8).
*> ***************************************************************
procedure division.
compute answer = 3*var-1 end-compute
goback.
end program computing.
With the above source, the compile will succeed.
OpenCOBOL will (properly, according to standard) compile this as
three times var-1. Not saved, if you meant 3 times var minus 1.
OpenCOBOL programmers are strongly encouraged to use full spacing inside
COMPUTE statements.
OCOBOL*> ***************************************************************
identification division.
program-id. computing.
data division.
working-storage section.
01 answer pic s9(8).
01 var pic s9(8).
01 var-1 pic s9(8).
*> ***************************************************************
procedure division.
compute
answer = 3 * var - 1
on size error
display "Problem, call the ghost busters" end-display
not on size error
display "All good, answer is trustworthy" end-display
end-compute
goback.
end program computing.
COMPUTE supports ON SIZE ERROR, NOT ON SIZE ERROR imperatives for safety, and
the ROUNDED modifier for bankers.
As yet unsupported USE AFTER EXCEPTION CONDITION clause.
An extension allowing constant definitions
01 enumerated-value CONSTANT AS 500.
An FD clause:
FD a-file RECORD CONTAINS 80 CHARACTERS.
A CALL clause that controls how arguments are passed and expected.
CALL "subprog" USING BY CONTENT alpha-var.
alpha-var will not be modifieable by subprog as a copy is passed.
See REFERENCE and VALUE for the other supported CALL argument control.
A placeholder, no operation verb.
if action-flag = "C" or "R" or "U" or "D"
continue
else
display "invalid action-code" end-display
end-if
As yet unsupported REPORT SECTION clause for setting control break data fields.
As yet unsupported REPORT SECTION clause for setting control break data fields.
A clause of the INSPECT verb.
INSPECT X CONVERTING "012345678" TO "999999999".
Move any and all sub fields with matching names within records.
01 bin-record.
05 first-will usage binary-short.
05 second-will usage binary-long.
05 this-wont-move usage binary-long.
05 third-will usage binary-short.
01 num-record.
05 first-will pic 999.
05 second-will pic s9(9).
05 third-will pic 999.
05 this-doesnt-match pic s9(9).
move corresponding bin-record to num-record
display
first-will in num-record
second-will in num-record
third-will in num-record
end-display
Sets the count of characters set in an UNSTRING substring.
From the OpenCOBOL Programmer’s Guide’s UNSTRING entry.
UNSTRING Input-Address
DELIMITED BY "," OR "/"
INTO
Street-Address DELIMITER D1 COUNT C1
Apt-Number DELIMITER D2 COUNT C2
City DELIMITER D3 COUNT C3
State DELIMITER D4 COUNT C4
Zip-Code DELIMITER D5 COUNT C5
END-UNSTRING
SPECIAL-NAMES.
CONSOLE IS CRT
CRT STATUS is identifier-1.
CONSOLE IS CRT allows “CRT” and “CONSOLE” to be used interchangeably
on DISPLAY but this is a default for newer OpenCOBOL implementations.
CRT STATUS IS establishes a PIC 9(4) field for screen ACCEPT status codes.
There is also an implicit COB-CRT-STATUS register defined for all
programs, that will be used if no explicit field is established.
SPECIAL-NAMES.
CURRENCY SIGN IS literal-1.
Default currency sign is the dollar sign “$”.
Tracks the line/column location of screen ACCEPT.
SPECIAL-NAMES.
CURSOR IS identifier-2.
identifier-2 is to be declared as PIC 9(4) or 9(6). If 4, the field is
LLCC. With 9(6) it is LLLCCC where L is line and C is column, zero relative.
A clause that causes EXIT PERFORM to return to the top of a loop.
See FOREVER for an example.
A magical DIVISION. One of COBOL’s major strength is the rules surrounding the
DATA DIVISION and pictorial record definitions.
An as yet unsupported Object COBOL feature.
An ACCEPT source. 6 digit and 8 digit Gregorian dates.
- ACCEPT ident-1 FROM DATE
- ACCEPT ident-2 FROM DATE YYYYMMDD
identification division.
program-id. dates.
data division.
working-storage section.
01 date-2nd
03 date-yy pic 9(2).
03 date-mm pic 9(2).
03 date-dd pic 9(2).
01 date-3rd
03 date-yyyy pic 9(4).
03 date-mm pic 9(2).
03 date-dd pic 9(2).
procedure division.
accept date-2nd from date end-accept
*> Just before the 3rd millennium, programmers admitted <*
*> that 2 digit year storage was a bad idea and ambiguous <*
accept date-3rd from date yyyymmdd end-accept
display date-2nd space date-3rd end-display
goback.
end program dates.
An ACCEPT source. Access the current date in Julian form. Returns
yyddd and yyyyddd formats.
- ACCEPT ident-1 FROM DAY
- ACCEPT ident-2 FROM DAY YYYYDDD
OCOBOL >>SOURCE FORMAT IS FIXED
*> ***************************************************************
*> Author: Brian Tiffin
*> Date: 2011182 (July 01)
*> Purpose: Accept from day in Julian form
*> Tectonics: cobc -x days.cob
*> ***************************************************************
identification division.
program-id. days.
data division.
working-storage section.
01 julian-2nd.
03 julian-yy pic 9(2).
03 julian-days pic 9(3).
01 julian-3rd.
03 julian-yyyy pic 9(4).
03 julian-days pic 9(3).
procedure division.
accept julian-2nd from day end-accept
*> Just before the 3rd millennium, programmers admitted <*
*> that 2 digit year storage was a bad idea and ambiguous <*
accept julian-3rd from day yyyyddd end-accept
display julian-2nd space julian-3rd end-display
goback.
end program days.
$ make days
cobc -W -x days.cob -o days
$ ./days
11182 2011182
An ACCEPT source. Single digit day of week. 1 for Monday, 7 for Sunday.
accept the-day from day-of-week
Report Writer shortcut for DETAIL. Recognized, but not yet implemented. This
author found this type of shortcut very unCOBOL, until trying to layout a
report, when it made a lot more practical sense in FIXED form COBOL.
A SOURCE-COMPUTER clause and DECLARATIVE phrase.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SOURCE-COMPUTER mine
WITH DEBUGGING MODE.
DEBUGGING MODE can also be toggled on with the -fdebugging-line cobc option,
and will compile in ‘D’ lines.
PROCEDURE DIVISION.
DECLARATIVES.
decl-debug section.
USE FOR DEBUGGING ON ALL PROCEDURES
decl-paragraph.
DISPLAY "Why is this happening to me?" END-DISPLAY
END DECLARATIVES.
USE FOR DEBUGGING sets up a section that is executed when the named section is
entered. Powerful. It can also name a file, and the debug section is
evaluated after open, close, read, start etc. Identifiers can be also be named
and the debug section will trigger when referenced (usually after).
Allows internationization for number formatting. In particular
IDENTIFICATION DIVISION.
PROGRAM-ID. 'MEMALL'.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SPECIAL-NAMES. DECIMAL-POINT IS COMMA.
will cause OpenCOBOL to interpret numeric literals along the lines of
123,45 as one hundred twenty three and forty five one hundreths.
DECIMAL-POINT IS COMMA, while world friendly, can be the cause of
ambiguous parsing and care must be taken by developers that use
comma to separate parameters to FUNCTIONs.
An imperative entry that can control exception handling
of file operations and turn on debug entry points.
procedure division.
declaratives.
handle-errors section.
use after standard error procedure on filename-1.
handle-error.
display "Something bad happened with " filename-1 end-display.
.
helpful-debug section.
use for debugging on main-file.
help-me.
display "Just touched " main-file end-display.
.
end declaratives.
A multi-use clause used in
- CALL ... SIZE IS DEFAULT
- ENTRY ... SIZE IS DEFAULT
- INITIALIZE ... WITH ... THEN TO DEFAULT
Allows removal of records from RELATIVE and INDEXED files.
DELETE filename-1 RECORD
INVALID KEY
DISPLAY "no delete" END-DISPLAY
NOT INVALID KEY
DISPLAY "record removed" END-DISPLAY
END-DELETE
4.1.130.1 OC 2.0
Allows file deletes.
DELETE FILE
filename-1 filename-2 filename-3
END-DELETE
A fairly powerful keyword used with the STRING and UNSTRING verbs. Accepts
literals and the BY SIZE modifier.
STRING null-terminated
DELIMITED BY LOW-VALUE
INTO no-zero
END-STRING
Tracks which delimiter was used for a substring in an UNSTRING operation.
From Gary’s OCic.cbl
UNSTRING Expand-Code-Rec
DELIMITED BY ". " OR " "
INTO SPI-Current-Token
DELIMITER IN Delim
WITH POINTER Src-Ptr
END-UNSTRING
Sets a control identifier for variable OCCURS table definitions.
01 TABLE-DATA.
05 TABLE-ELEMENTS
OCCURS 1 TO 100 TIMES DEPENDING ON crowd-size
INDEXED BY cursor-var.
10 field-1 PIC X.
Controls a descending sort and/or retrieval order, with
- SORT filename ON DESCENDING KEY alt-key
- OCCURS 1 TO max-size TIMES DESCENDING KEY key-for-table
Currently unsupported data descriptor. Part of VALIDATE.
A recognized but currently unsupported report descriptor detail line control
clause.
An unsupported COMMUNICATION SECTION control verb.
A SELECT devicename phrase.
ASSIGN TO DISK USING dataname
Alternative spelling of DISC is allowed.
A general purpose output verb.
- prints values to default console or other device
- set the current ARGUMENT-NUMBER influencing subsequent access
ACCEPT FROM ARGUMENT-VALUE statements
- specify explicit COMMAND-LINE influencing subsequent access
with ACCEPT FROM COMMAND-LINE, but not ARGUMENT-VALUE access
- sets enviroment variables, as part of a two step process.
(Use the more concise SET ENVIRONMENT instead)
- DISPLAY “envname” UPON ENVIRONMENT-NAME
- DISPLAY “envname-value” UPON ENVIRONMENT-VALUE
DISPLAY "First value: " a-variable " and another string" END-DISPLAY
DISPLAY "1" 23 "4" END-DISPLAY
The setting of environment variables does not influence the owning process
shell.
DISPLAY "ENVNAME" UPON ENVIRONMENT-NAME END-DISPLAY
DISPLAY "COBOL value" UPON ENVIRONMENT-VALUE
ON EXCEPTION stop run
NOT ON EXCEPTION continue
END-DISPLAY
CALL "SYSTEM" USING "echo $ENVNAME"
gives:
$ ENVNAME="parent shell value"
$ ./disps
COBOL value
$ echo $ENVNAME
parent shell value
Highly precise arthimetic. Supports various forms:
- DIVIDE INTO
- DIVIDE INTO GIVING
- DIVIDE BY GIVING
- DIVIDE INTO REMAINDER
- DIVIDE BY REMAINDER
For example:
DIVIDE dividend BY divisor GIVING answer ROUNDED REMAINDER r
ON SIZE ERROR
PERFORM log-division-error
SET division-error TO TRUE
NOT ON SIZE ERROR
SET division-error TO FALSE
END-DIVIDE
The 20xx draft standard requires conforming implementations to use 1,000
digits of precision for intermediate results. There will be no rounding
errors when properly calculating financials in a COBOL program.
Ahh, sub-divisions. I think my favourite is the DATA DIVISION. It gives
COBOL a distinctive and delicious flavour in a picturesque codescape.
Divisions must be specified in the order below within each source program unit.
- IDENTIFICATION DIVISION.
- ENVIRONMENT DIVISION.
- DATA DIVISION.
- PROCEDURE DIVISION.
A handy mnemonic may be “I Enter Data Properly”.
OpenCOBOL is flexible enough to compile files with only a PROCEDURE DIVISION,
and even then it really only needs a PROGRAM-ID. See
What is the shortest OpenCOBOL program? for an example.
Allows decrement of an index control or pointer variable.
Also used for SCREEN SECTION scroll control.
Allows duplicate keys in indexed files.
SELECT filename
ALTERNATE RECORD KEY IS altkey WITH DUPLICATES
Also for SORT control.
SORT filename ON DESCENDING KEY keyfield
WITH DUPLICATES IN ORDER
USING sort-in GIVING sort-out.
A file access mode allowing runtime control over SEQUENTIAL and RANDOM access
for INDEXED and RELATIVE ORGANIZATION.
SELECT filename
ORGANIZATION IS RELATIVE
ACCESS MODE IS DYNAMIC
Extended Binary Coded Decimal Interchange Code.
A character encoding common to mainframe systems, therefore COBOL, therefore
OpenCOBOL. Different than ASCII and OpenCOBOL supports both through
efficient mappings. See http://en.wikipedia.org/wiki/EBCDIC for more info.
ASCII to EBCDIC conversion the OpenCOBOL way
SPECIAL-NAMES.
ALPHABET ALPHA IS NATIVE.
ALPHABET BETA IS EBCDIC.
PROCEDURE DIVISION.
INSPECT variable CONVERTING ALPHA TO BETA
An unsupported shortform for USE AFTER EXCEPTION CONDITION
An unsupported COMMUNICATION SECTION word.
Alternate conditional branch point.
IF AGE IS ZERO
DISPLAY "Cigar time" END-DISPLAY
ELSE
DISPLAY "What is it with kids anyway?" END-DISPLAY
END-IF
For multi branch conditionals, see EVALUATE.
An unsupported COMMUNICATION SECTION word.
An unsupported COMMUNICATION SECTION control verb.
Ends things. Programs, declaratives, functions.
Explicit terminator for ACCEPT.
Explicit terminator for ADD.
Explicit terminator for CALL.
Explicit terminator for DELETE.
Explicit terminator for DIVIDE.
Explicit terminator for IF.
A LINAGE phrase used by WRITE controlling end of page imperative clause.
Explicit terminator for READ.
Explicit terminator for RETURN.
Explicit terminator for SEARCH.
Explicit terminator for START.
Explicit terminator for STRING.
Explicit terminator for WRITE.
Always for CALL entry points without being fully specified sub-programs.
Great for defining callbacks required by many GUI frameworks.
See Does OpenCOBOL support the GIMP ToolKit, GTK+? for an example.
An as yet unsupported clause.
Divisional name. And allows access to operating system environment
variables. OpenCOBOL supports
within the ENVIROMENT DIVISION.
Also a context sensitive keyword for access to the process environment
variables.
- SET ENVIRONMENT “env-var” TO value
- ACCEPT var FROM ENVIRONMENT “env-var” END-ACCEPT
Provides access to the running process environment variables.
Provides access to the running process environment variables.
An unsupported shortform for USE AFTER EXCEPTION OBJECT
Conditional expression to compare two data items for equality.
Conditional expression to compare two data items for equality.
A screen section data attribute clause that can control which portions
of the screen are cleared during DISPLAY, and ACCEPT.
01 form-record.
02 first-field PIC xxx
USING identifier-1
ERASE EOL.
A DECLARATIVES clause that can control error handling.
USE AFTER STANDARD ERROR PROCEDURE ON filename-1
Program return control.
STOP RUN WITH ERROR STATUS stat-var.
Programmer access to escape key value during ACCEPT.
ACCEPT identifier FROM ESCAPE KEY END-ACCEPT
Data type is 9(4).
Unsupported COMMUNICATION SECTION control.
A very powerful and concise selection construct.
EVALUATE a ALSO b ALSO TRUE
WHEN 1 ALSO 1 THRU 9 ALSO c EQUAL 1 PERFORM all-life
WHEN 2 ALSO 1 THRU 9 ALSO c EQUAL 2 PERFORM life
WHEN 3 THRU 9 ALSO 1 ALSO c EQUAL 9 PERFORM disability
WHEN OTHER PERFORM invalid
END-EVALUATE
Allow detection of CALL problem.
CALL "CBL_OC_DUMP" ON EXCEPTION CONTINUE END-CALL
Unsupport object COBOL data item reference.
Mode control for file locks.
OpenCOBOL supports
Controls flow of the program. EXIT PERFORM CYCLE causes an inline perform
to return control to the VARYING, UNTIL or TIMES clause, testing the
conditional to see if another cycle is required. EXIT PERFORM without the
CYCLE option causes flow to continue passed the end of the current PERFORM
loop.
Unsupported COMMUNICATION SECTION control.
Open a resource in an append mode.
Clause to specify external data item, file connection and program unit.
77 shared-var PIC S9(4) IS EXTERNAL AS 'shared_var'.
An unsupported object COBOL keyword.
Logical false and conditional set condition.
01 record-1 pic 9.
88 conditional-1 values 1,2,3 when set to false is 0.
set conditional-1 to true
display record-1 end-display
set conditional-1 to false
display record-1 end-display
if conditional-1
display "BAD" end-display
end-if
Runs as:
Also used in EVALUATE, inverting the normal sense of WHEN
evaluate false
when 1 equal 1
display "Not displayed, as 1 equal 1 is true" end-display
when 1 equal 2
display "This displays because 1 equal 2 is false" end-display
when other
display "the truest case, nothing is false" end-display
end-evaluate
The record side of the COBOL file system. The File Descriptor. COBOL provides
lots of control over file access. FD is part of that engine.
Sort files use SD
Some FD phrases are old, and their uses have been overtaken by features of modern
operating systems.
- BLOCK CONTAINS
- RECORDING MODE IS
Others are pretty cool. LINAGE is one example. FD supports a mini report
writer feature. Control over lines per page, heaVer, footer and a line
counter, LINAGE IS, that is implicitly maintained by OpenCOBOL during file
writes. These files are usually reports, but they don’t have to be, LINAGE
can be used for a simple step counter when you’d like progress displays of
file updates.
Other recognized file descriptions include:
- RECORD IS VARYING IN SIZE FROM 1 TO 999999999 DEPENDING ON size-variable
Record sizes need to fit in PIC 9(9), just shy of a thousand million.
- CODE-SET IS alphabet-name
- DATA RECORD IS data-name
- LABEL RECORDS ARE STANDARD (or OMITTED)
- RECORD CONTAINS 132 CHARACTERS
FD filename-sample
RECORD IS VARYING IN SIZE FROM 1 TO 32768 CHARACTERS
DEPENDING ON record-size-sample.
FILE is another multi use COBOL word.
- A SECTION of the DATA DIVISION.
The FILE section holds file description paragraphs and buffer layouts.
data division.
FILE section.
fd cobol-file-selector.
01 cobol-io-buffer pic x(132).
- a context word for setting name for FILE STATUS fields in FILE-CONTROL
paragraphs.
Some programmers don’t like seeing COBOL code that does not verify and test
FILE STATUS, so you should. See ISAM for the numeric codes supported.
environment division.
input-output section.
file-control.
select optional data-file assign to file-name
organization is line sequential
FILE STATUS is data-file-status.
select mini-report assign to "mini-report".
- a context word as part of the PROCEDURE DIVISION declarative statements
allowing for out-of-band exception handling for file access.
Exception handling with declaratives can be powerful, but some programmers find
the out of band nature of where the source code that caused a problem
compared to where the error handler is, distasteful.
procedure division.
declaratives.
error-handling section.
USE AFTER EXCEPTION FILE filename-maybe.
error-handler.
display "Exception on filename" end-display
.
end declaratives.
Support for USE AFTER EXCEPTION FILE is a work in progress. Using
DECLARATIVES forces use of section names in the PROCEDURE DIVISION.
- a context word as part of DELETE FILE filenames.
DELETE FILE file-selector-1 file-selector-2
DELETE FILE is supported in OpenCOBOL 2.0.
Files. The paragraph in the INPUT-OUTPUT section, in the ENVIRONMENT division.
It’s verbose, a little voodooey, and worth it.
environment division.
input-output section.
FILE-CONTROL.
select optional data-file assign to file-name
organization is line sequential
file status is data-file-status.
select mini-report assign to "mini-report".
File naming clause. Assigned name may be device, FD clause specifies value of
the file identifier.
VALUE OF FILE-ID IS file-ids in summary-array
more specifically
environment division.
input-output section.
file-control.
select cobol-file-selector
assign to disk
organization indexed
access mode dynamic
record key fd-key-field
file status file-status-field.
data division.
file section.
fd cobol-file-selector label record standard
VALUE OF FILE-ID is "actual-filename.dat".
An alternative, and likely more common, method is to set the actual filename
(or the enviroment variable that references the actual filename) in the
ASSIGN clause. OpenCOBOL has a configuration setting to control how the
actual filenames are mapped, see ASSIGN. VALUE OF FILE-ID is not ISO
standard COBOL.
Data division clause, for unnamed data allocations; filler, if you will.
01 the-record.
05 first-field pic x(10).
05 filler pic x(35) value "this space intentionally left blank".
04 third-field pic x(10).
FILLER is an optional word, and this code snippet is equivalent.
01 the-record.
05 first-field pic x(10).
05 pic x(35) value "this space intentionally left blank".
05 third-field pic x(10).
Personal preference of this author is to explicitly type FILLER.
Final. A recognized but currently not supported Report Writer feature.
First. A recognized but currently not supported Report Writer feature.
OpenCOBOL recognizes but does not yet support FLOAT-EXTENDED and
will abend a compile.
OpenCOBOL supports floating point long.
identification division.
program-id. threes.
data division.
working-storage section.
01 fshort usage float-short.
01 flong usage float-long.
01 fpic pic 9v9(35).
procedure division.
compute fshort = 1 / 3 end-compute
display "as short " fshort end-display
compute flong = 1 / 3 end-compute
display "as long " flong end-display
compute fpic = 1 / 6 end-compute
display "as pic " fpic end-display
compute fpic rounded = 1 / 6 end-compute
display "rounded " fpic end-display
goback.
end program threes.
displays:
$ ./threes
as short 0.333333343267440796
as long 0.333333333333333315
as pic 0.16666666666666666666666666666666666
rounded 0.16666666666666666666666666666666667
OpenCOBOL supports short floating point.
Recognized but unsupported Report Writer clause.
Provides for infinite loops. Use EXIT PERFORM or EXIT PERFORM CYCLE to
control program flow.
identification division.
program-id. foreverloop.
data division.
working-storage section.
01 cobol pic 9 value 0.
01 c pic 9 value 1.
01 fortran pic 9 value 2.
procedure division.
perform forever
add 1 to cobol
display "cobol at " cobol end-display
if cobol greater than fortran
exit perform
end-if
if cobol greater than c
exit perform cycle
end-if
display "cobol still creeping up on c" end-display
end-perform
display "cobol surpassed c and fortran" end-display
goback.
end program foreverloop.
Which produces:
$ cobc -free -x foreverloop.cob
$ ./foreverloop
cobol at 1
cobol still creeping up on c
cobol at 2
cobol at 3
cobol surpassed c and fortran
I asked on opencobol.org for some input, and an interesting conversation
ensued. I’ve included the forum thread archive, nearly in its entirety, to
give a sense of various programmer styles and group thought processing. See
Performing FOREVER?.
Properly cleans up ALLOCATE alloted memory, and source format directive.
>>SOURCE FORMAT IS FREE
01 var PIC X(1024) BASED.
ALLOCATE var
CALL "buffer-thing" USING BY REFERENCE var END-CALL
MOVE var TO working-store
FREE var
ACCEPT var FROM ENVIRONMENT "path"
ON EXCEPTION
DISPLAY "No path" END-DISPLAY
NOT ON EXCEPTION
DISPLAY var END-DISPLAY
END-ACCEPT
A screen section screen item control operator, requesting the normal terminator
be ignored until the field is completely full or completely empty.
Not yet implemented, but it will allow for user defined FUNCTION.
Not yet implemented beyond simple parsing REPORT writer feature.
Destination control for computations, and return value clause.
ADD 1 TO cobol GIVING OpenCOBOL.
A global name is accessible to all contained programs.
GO TO is your friend. Edsger was wrong. Transfer control to a
named paragraph or section. See ALTER for details of monster goto power.
A return. This will work correctly for all cases. A return to the
operating system or a return to a called program.
COBOL conditional expression, IF A GREATER THAN B, See LESS
Recognized but unsupported Report Writer clauses.
An unsupported BIT clause.
Recognized but unsupported Report Writer clauses.
Screen control for field intensity.
An OPEN mode allowing for both read and write.
A paragraph in the INPUT-OUTPUT section, allowing sharing memory areas for
different files.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
I-O-CONTROL.
SAME RECORD AREA FOR filename-1 filename-2.
The initial division for OpenCOBOL programs.
IDENTIFICATION DIVISION.
PROGRAM-ID. sample.
Many historical paragraphs from the IDENTIFICATION DIVISION have been
deemed obsolete. OpenCOBOL will treat these as comment paragraphs.
Including
- AUTHOR
- DATE-WRITTEN
- DATE-MODIFIED
- DATE-COMPILED
- INSTALLATION
- REMARKS
- SECURITY
Conditional branching. In COBOL, conditionals are quite powerful and
there are many conditional expressions allowed with concise shortcuts.
IF A = 1 OR 2
MOVE 1 TO B
END-IF
READ filename-1 INTO identifer-1 IGNORING LOCK END-READ
Unsupported Object COBOL expression.
A data structure reference and name conflict resolution qualifier.
MOVE "abc" TO field IN the-record IN the-structure
Synonym for OF
01 cursor-var USAGE INDEX.
SET cursor-var UP BY 1.
An ISAM file organization.
environment division.
input-output section.
file-control.
select optional indexing
assign to "indexing.dat"
organization is indexed
access mode is dynamic
record key is keyfield of indexing-record
alternate record key is splitkey of indexing-record
with duplicates
.
Sets an indexing control identifier for OCCURS data arrays.
01 TABLE-DATA.
05 TABLE-ELEMENTS
OCCURS 1 TO 100 TIMES DEPENDING ON crowd-size
INDEXED BY cursor-var.
10 field-1 PIC X.
GROUP INDICATE is an as yet unsupported REPORT SECTION RD clause
that specifies that printable item is ouput only on the first
occurrence of its report group for that INITIATE, control break,
or page advance.
An unsupported Object COBOL clause.
A modifier for the PROGRAM-ID clause, that causes the entire DATA DIVISION
to be set to an initial state each time the subprogram is executed by CALL.
ocobol >>SOURCE FORMAT IS FIXED
*> ***************************************************************
*> Author: Brian Tiffin
*> Date: 20111226
*> Purpose: Small sample of INITIAL procedure division clause
*> Tectonics: cobc -x -w -g -debug initialclause.cob
*> ***************************************************************
identification division.
program-id. initialclause.
*> -*********-*********-*********-*********-*********-*********-**
procedure division.
call "with-initial" end-call
call "without-initial" end-call
call "with-initial" end-call
call "without-initial" end-call
call "without-initial" end-call
goback.
end program initialclause.
*> -*********-*********-*********-*********-*********-*********-**
*> -*********-*********-*********-*********-*********-*********-**
identification division.
program-id. with-initial is initial.
data division.
working-storage section.
01 the-value pic 99 value 42.
*> -*********-*********-*********-*********-*********-*********-**
procedure division.
display "Inside with-initial with : " the-value end-display
multiply the-value by 2 giving the-value
on size error
display "size overflow" end-display
end-multiply
goback.
end program with-initial.
*> -*********-*********-*********-*********-*********-*********-**
*> -*********-*********-*********-*********-*********-*********-**
identification division.
program-id. without-initial.
data division.
working-storage section.
01 the-value pic 99 value 42.
*> -*********-*********-*********-*********-*********-*********-**
procedure division.
display "Inside without-initial with: " the-value end-display
multiply the-value by 2 giving the-value
on size error
display "size overflow" end-display
end-multiply
goback.
end program without-initial.
Gives:
[btiffin@home cobol]$ ./initialclause
Inside with-initial with : 42
Inside without-initial with: 42
Inside with-initial with : 42
Inside without-initial with: 84
size overflow
Inside without-initial with: 84
size overflow
INITIAL sets the-value to 42 upon each and every entry, without-initial
multiplies through 42, 84, 168 (or would have).
A sample of the INITIALIZE verb posted to opencobol.org by human
OCOBOL*-----------------------------------------------------------------
IDENTIFICATION DIVISION.
PROGRAM-ID. 'INITTEST'.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SPECIAL-NAMES. DECIMAL-POINT IS COMMA.
INPUT-OUTPUT SECTION.
DATA DIVISION.
*
WORKING-STORAGE SECTION.
*
77 mychar pic x.
77 mynumeric pic 9.
01 REC-TEST BASED.
03 REC-TEST-PART1 PIC X(10) value all '9'.
03 REC-TEST-PART2 PIC X(10) value all 'A'.
01 fillertest.
03 fillertest-1 PIC 9(10) value 2222222222.
03 filler PIC X value '|'.
03 fillertest-2 PIC X(10) value all 'A'.
03 filler PIC 9(03) value 111.
03 filler PIC X value '.'.
*-----------------------------------------------------------------
LINKAGE SECTION.
*-----------------------------------------------------------------
PROCEDURE DIVISION.
*-----------------------------------------------------------------
Main section.
00.
*
display 'fillertest '
'on start:'
end-display
display fillertest
end-display
accept mychar
*
initialize fillertest
display 'fillertest '
'after initialize:'
end-display
display fillertest
end-display
accept mychar
*
initialize fillertest replacing numeric by 9
display 'fillertest '
'after initialize replacing numeric by 9:'
end-display
display fillertest
end-display
accept mychar
*
initialize fillertest replacing alphanumeric by 'X'
display 'fillertest '
'after initialize replacing alphanumeric by "X":'
end-display
display fillertest
end-display
accept mychar
*
initialize fillertest replacing alphanumeric by all 'X'
display 'fillertest '
'after initialize replacing alphanumeric by all "X":'
end-display
display fillertest
end-display
accept mychar
*
initialize fillertest with filler
display 'fillertest '
'after initialize with filler:'
end-display
display fillertest
end-display
accept mychar
*
initialize fillertest all to value
display 'fillertest '
'after initialize all to value:'
end-display
display fillertest
end-display
accept mychar
*
ALLOCATE REC-TEST
display 'REC-TEST after allocating:'
end-display
display REC-TEST
end-display
accept mychar
*
initialize REC-TEST all to value
display 'REC-TEST after initalize all to value:'
end-display
display REC-TEST
end-display
accept mychar
*
stop run
*
continue.
ex. exit program.
*-----------------------------------------------------------------
*--- End of program INITTEST -------------------------------------
Outputs:
fillertest on start:
2222222222|AAAAAAAAAA111.
fillertest after initialize:
0000000000| 111.
fillertest after initialize replacing numeric by 9:
0000000009| 111.
fillertest after initialize replacing alphanumeric by "X":
0000000009|X 111.
fillertest after initialize replacing alphanumeric by all "X":
0000000009|XXXXXXXXXX111.
fillertest after initialize with filler:
0000000000 000
fillertest after initialize all to value:
2222222222|AAAAAAAAAA111.
REC-TEST after allocating:
REC-TEST after initalize all to value:
9999999999AAAAAAAAAA
A modifier for the ALLOCATE verb, filling the target with a default value.
77 based-var PIC X(9) BASED VALUE "ALLOCATED".
77 pointer-var USAGE POINTER.
ALLOCATE based-var
DISPLAY ":" based-var ":" END-DISPLAY
FREE based-var
ALLOCATE based-var INITIALIZED RETURNING pointer-var
DISPLAY ":" based-var ":" END-DISPLAY
displays:
Initialize internal storage for named REPORT SECTION entries.
Not currently (February 2013) supported.
Provides very powerful parsing and replacement to COBOL and OpenCOBOL supports
the full gamet of options.
ocobol identification division.
program-id. inspecting.
data division.
working-storage section.
01 ORIGINAL pic XXXX/XX/XXBXX/XX/XXXXXXX/XX.
01 DATEREC pic XXXX/XX/XXBXX/XX/XXXXXXX/XX.
procedure division.
move function when-compiled to DATEREC ORIGINAL
INSPECT DATEREC REPLACING ALL "/" BY ":" AFTER INITIAL SPACE
display
"Intrinsic function WHEN-COMPILED " ORIGINAL
end-display
display
" after INSPECT REPLACING " DATEREC
end-display
goback.
end program inspecting.
Example output:
Intrinsic function WHEN-COMPILED 2010/03/25 23/05/0900-04/00
after INSPECT REPLACING 2010/03/25 23:05:0900-04:00
Division.
DIVIDE A INTO B GIVING C.
Used in REPOSITORY to allow the optional use of “FUNCTION” keyword.
environment division.
configuration section.
repository.
function all intrinsic.
The source unit will now allow for program lines such as
move trim(" abc") to dest
move function trim(" abc") to dest
to compile the same code.
Key exception imperative phrase.
READ filename-1
INVALID KEY
DISPLAY "Bad key"
NOT INVALID KEY
DISPLAY "Good read"
END-READ
Unsupported Object COBOL method call.
Readability word. A IS LESS THAN B is equivalent to A LESS B.
Tweaks storage rules in wierd JUST ways, lessening the voodoo behind MOVE
instructions, he said, sarcastically.
77 str1 pic x(40) justified right.
Multi use, always means key:
- RELATIVE KEY IS
- ALTERNATE RECORD KEY IS
- NOT INVALID KEY
- SORT filename ON DESCENDING KEY keyfield
- START indexing KEY IS LESS THAN keyfield
A special value for Standard Input
file-control.
select cgi-in
assign to keyboard.
A record label. As with most record labels, falling into disuse.
Used in START to prepare a read of the last record. A recognized but
unsupported Report Writer clause.
START filename-1 LAST
INVALID KEY
MOVE ZERO TO record-count
>>D DISPLAY "No last record for " filename-1 END-DISPLAY
END-START
A reserved but unsupported category group. See Setting Locale. OpenCOBOL is
‘locale’ aware, but it is currently more external than in COBOL source. For
now, it is safest to assume LC_ALL=C, but this can be configured
differently when OpenCOBOL is built.
A reserved but unsupported category name. Will be used with SET.
A reserved but unsupported Locale category name. Will be used with SET.
A reserved but unsupported category name. See Setting Locale. OpenCOBOL is
‘locale’ aware, but it is currently more external than in COBOL source.
OpenCOBOL 2.0 extends locale support to the compiler messages.
$ export LC_MESSAGES=es_ES
$ cobc -x fdfgffd.cob
cobc: fdfgffd.cob: No existe el fichero o el directorio
A reserved but unsupported Locale category name. Will be used with SET.
A reserved but unsupported Locale category name. Will be used with SET.
A reserved but unsupported Locale category name. Will be used with SET.
Multipurpose.
DISPLAY FUNCTION TRIM(var-1 LEADING) END-DISPLAY
INSPECT FUNCTION REVERSE(TEST-CASE)
TALLYING B-COUNT
FOR LEADING ' '.
DISPLAY B-COUNT.
INSPECT X REPLACING LEADING ZEROS BY SPACES.
as well as use in the COBOL preprocessor:
COPY "copy.inc"
REPLACING LEADING ==TEST== BY ==FIRST==
LEADING ==NORM== BY ==SECOND==.
A ‘cell-count’ length. Not always the same as BYTE-LENGTH.
A comparison operation.
IF requested LESS THAN OR EQUAL TO balance
PERFORM transfer
ELSE
PERFORM reject
END-IF
Recognized but unsupported Report Writer clause.
Recognized but unsupported Report Writer clause.
LINAGE is a SPECIAL-REGISTER supported by OpenCOBOL. A counter is
maintained for file WRITE and can be used for pageing and other control.
COBOL *****************************************************************
* Example of LINAGE File Descriptor
* Author: Brian Tiffin
* Date: 10-July-2008
* Tectonics: $ cocb -x linage.cob
* $ ./linage <filename ["linage.cob"]>
* $ cat -n mini-report
*****************************************************************
IDENTIFICATION DIVISION.
PROGRAM-ID. linage-demo.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
select optional data-file assign to file-name
organization is line sequential
file status is data-file-status.
select mini-report assign to "mini-report".
DATA DIVISION.
FILE SECTION.
FD data-file.
01 data-record.
88 endofdata value high-values.
02 data-line pic x(80).
FD mini-report
linage is 16 lines
with footing at 15
lines at top 2
lines at bottom 2.
01 report-line pic x(80).
WORKING-STORAGE SECTION.
01 command-arguments pic x(1024).
01 file-name pic x(160).
01 data-file-status pic 99.
01 lc pic 99.
01 report-line-blank.
02 filler pic x(18) value all "*".
02 filler pic x(05) value spaces.
02 filler pic x(34)
VALUE "THIS PAGE INTENTIONALLY LEFT BLANK".
02 filler pic x(05) value spaces.
02 filler pic x(18) value all "*".
01 report-line-data.
02 body-tag pic 9(6).
02 line-3 pic x(74).
01 report-line-header.
02 filler pic x(6) VALUE "PAGE: ".
02 page-no pic 9999.
02 filler pic x(24).
02 filler pic x(5) VALUE " LC: ".
02 header-tag pic 9(6).
02 filler pic x(23).
02 filler pic x(6) VALUE "DATE: ".
02 page-date pic x(6).
01 page-count pic 9999.
PROCEDURE DIVISION.
accept command-arguments from command-line end-accept.
string
command-arguments delimited by space
into file-name
end-string.
if file-name equal spaces
move "linage.cob" to file-name
end-if.
open input data-file.
read data-file
at end
display
"File: " function trim(file-name) " open error"
end-display
go to early-exit
end-read.
open output mini-report.
write report-line
from report-line-blank
end-write.
move 1 to page-count.
accept page-date from date end-accept.
move page-count to page-no.
write report-line
from report-line-header
after advancing page
end-write.
perform readwrite-loop until endofdata.
display
"Normal termination, file name: "
function trim(file-name)
" ending status: "
data-file-status
end-display.
close mini-report.
* Goto considered harmful? Bah! :)
early-exit.
close data-file.
exit program.
stop run.
****************************************************************
readwrite-loop.
move data-record to report-line-data
move linage-counter to body-tag
write report-line from report-line-data
end-of-page
add 1 to page-count end-add
move page-count to page-no
move linage-counter to header-tag
write report-line from report-line-header
after advancing page
end-write
end-write
read data-file
at end set endofdata to true
end-read
.
*****************************************************************
* Commentary
* LINAGE is set at a 20 line logical page
* 16 body lines
* 2 top lines
* A footer line at 15 (inside the body count)
* 2 bottom lines
* Build with:
* $ cobc -x -Wall -Wtruncate linage.cob
* Evaluate with:
* $ ./linage
* This will read in linage.cob and produce a useless mini-report
* $ cat -n mini-report
*****************************************************************
END PROGRAM linage-demo.
Using
Produces a mini-report of:
****************** THIS PAGE INTENTIONALLY LEFT BLANK ******************
PAGE: 0001 LC: 000000 DATE: 090206
000001 IDENTIFICATION DIVISION.
000002 PROGRAM-ID. MINIPROG.
000003 ENVIRONMENT DIVISION.
000004 CONFIGURATION SECTION.
000005 SOURCE-COMPUTER. LINUX.
000006 OBJECT-COMPUTER. LINUX.
000007 SPECIAL-NAMES.
000008 INPUT-OUTPUT SECTION.
000009 FILE-CONTROL.
000010 SELECT PRINTFILE ASSIGN TO "XXRXWXX"
000011 FILE STATUS RXWSTAT.
000012 DATA DIVISION.
000013 FILE SECTION.
000014 FD PRINTFILE.
PAGE: 0002 LC: 000015 DATE: 090206
000001 01 PRINTREC PIC X(132).
000002 WORKING-STORAGE SECTION.
000003 01 RXWSTAT PIC XX.
000004 01 str pic x(4).
000005 PROCEDURE DIVISION.
000006 A00-MAIN SECTION.
000007 001-MAIN-PROCEDURE.
000008 OPEN INPUT PRINTFILE.
000009 DISPLAY "File Status: " RXWSTAT.
000010 DISPLAY "EXCEPTION-FILE: " FUNCTION EXCEPTION-FILE.
000011 DISPLAY "Return Length: "
000012 FUNCTION LENGTH (FUNCTION EXCEPTION-FILE).
000013 DISPLAY "EXCEPTION-STATUS: " FUNCTION EXCEPTION-STATUS.
000014 DISPLAY "EXCEPTION-STATEMENT: " FUNCTION EXCEPTION-STATEMENT.
PAGE: 0003 LC: 000015 DATE: 090206
000001 STRING "TOOLONG" DELIMITED SIZE INTO RXWSTAT.
000002 DISPLAY "EXCEPTION-STATUS: " FUNCTION EXCEPTION-STATUS.
000003 DISPLAY "EXCEPTION-STATEMENT: " FUNCTION EXCEPTION-STATEMENT.
000004 DISPLAY "EXCEPTION-LOCATION: " FUNCTION EXCEPTION-LOCATION.
000005 STOP RUN.
See except.cob under the FUNCTION EXCEPTION-STATUS entry.
An internal OpenCOBOL noun, or Special Register. Value is readonly and is
maintained during WRITEs to files that have a LINAGE clause. Useful for
quick reports and logical page layouts.
LINE SEQUENTIAL files. Screen section line control.
Special register for the unsupported Report Writer.
Screen section line control, screen occurs control and area scrolling.
A SECTION in the DATA DIVISION. Used for call frame data handling when
the current run unit may not be in charge of the location of working
storage. Defaults to uninitialized references which must be set with
USING in a CALL or explicitly with SET ADDRESS. References without
initialization will cause an addressing segfault.
A SECTION in the DATA DIVISION. Data defined in local storage will be local
to the running module and re-entrant within subprogram call trees.
Unsupported in OpenCOBOL 1.1pre-rel. Support added in 2.0
A SPECIAL-NAMES entry giving OpenCOBOL an international flair.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SPECIAL-NAMES.
LOCALE spanish IS 'ES_es'.
Record management.
SELECT filename-1 ASSIGN TO 'master.dat' LOCK MODE IS MANUAL.
A figurative ALPHABETIC constant, being the lowest character value in
the COLLATING sequence.
MOVE LOW-VALUE TO alphanumeric-1.
IF alphabetic-1 EQUALS LOW-VALUE
DISPLAY "Failed validation" END-DISPLAY
END-IF.
It’s invalid to MOVE LOW-VALUE to a numeric field.
A pluralized form of LOW-VALUE. Equivalent.
MOVE LOW-VALUES TO alphanumeric-1.
A screen attribute for DISPLAY and SCREEN SECTION fields.
SCREEN SECTION.
01 example.
05 FILLER
LINE 1 COLUMN 10
VALUE IS "Example:"
LOWLIGHT.
Will display the Example: legend in a dimmed video if supported
with the current terminal settings.
LOCK MODE IS MANUAL WITH LOCK ON MULTIPLE RECORDS. See AUTOMATIC and
EXCLUSIVE for more LOCK options.
An OBJECT-COMPUTER clause.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
OBJECT-COMPUTER.
MEMORY SIZE IS 8 CHARACTERS.
Combines two or more identically sequenced files on a set of specified keys.
MERGE sort-file
ON DESCENDING KEY key-field-1
WITH DUPLICATES IN ORDER
COLLATING SEQUENCE IS user-alphabet
USING filename-1 filename-2
GIVING filename-3
Unsupported Communication Section clause.
Unsupported Object COBOL feature.
Unsupported Object COBOL feature.
Screen section relative line and column control.
05 some-field pic x(16)
line number is plus 1
column number is minus 8
A workhorse of the COBOL paradigm. MOVE is highly flexible,
intelligent, safe and sometimes perplexing data movement verb.
01 alphanum-3 PIC XXX.
01 num2 PIC 99.
MOVE "ABCDEFG" TO xvar3
DISPLAY xvar3 END-DISPLAY
MOVE 12345 TO num2
DISPLAY num2 END-DISPLAY
displays:
Note the 45, MOVE uses a right to left rule when moving numerics.
Groups can be moved with
MOVE CORRESPONDING ident-1 TO ident-2
in which case only the group items of the same name will be
transferred from the ident-1 group to the ident-2 fields.
LOCK MODE IS MANUAL WITH LOCK ON MULTIPLE RECORDS.
A mathematic operation.
MULTIPLY var-1 BY var-2 GIVING var-3
ON SIZE ERROR
SET invalid-result TO TRUE
END-MULTIPLY
NATIONAL character usage. Not yet supported. OpenCOBOL does support PICTURE N.
Conditional expression.
IF a IS NEGATIVE
SET in-the-red TO TRUE
END-IF
An unsupported program-protoype CALL clause.
With READ, to read the next record, possibly by KEY. Also an obsolete
control flow verb.
READ index-sequential-file NEXT RECORD INTO ident-1
IF condition-1
NEXT SENTENCE
ELSE
PERFORM do-something.
Specify NO locks, NO sharing, NO rewind.
CLOSE filename-1 WITH NO REWIND
READ file-1 WITH NO LOCK
Program return control
STOP RUN WITH NORMAL STATUS status-val
See ERROR
Conditional negation. See AND, OR. Also used in operational declaratives
such as NOT ON SIZE ERROR, in which case the operation succeeded without
overflowing the receiving data field.
IF NOT testing
CALL "thing"
NOT ON EXCEPTION
DISPLAY "Linkage to thing, OK" END-DISPLAY
END-CALL
END-IF
Void. A zero address pointer. A symbolic literal.
CALL "thing" RETURNING NULL END-CALL
SET ADDRESS OF ptr TO NULL
IF ptr EQUAL NULL
DISPLAY "ptr not valid" END-DISPLAY
END-IF
MOVE CONCATENATE(TRIM(cbl-string TRAILING) NULL) TO c-string
Screen section LINE COLUMN control.
05 some-field pic x(16) LINE NUMBER 5.
Unsupported Object COBOL feature.
Environment division, configuration section run-time machine paragraph.
OpenCOBOL supports
OCOBOL identification division.
program-id. runtime-computer.
environment division.
configuration section.
object-computer.
memory size is 8 characters
program collating sequence is bigiron-alphabet
segment-limit is 64
character classificiation is spanish-locale.
repository.
function all intrinsic.
special-names.
alphabet bigiron-alphabet is ebcdic
symbolic characters BS is 9
TAB is 10
LF is 11
NEWLINE is 11
CMA is 45
locale spanish-locale is "es_ES".
Unsupported Object COBOL feature.
Controls multiple occurances of data structures.
01 main-table.
03 main-record occurs 366 times depending on the-day.
05 main-field pic x occurs 132 times depending on the-len.
A data structure reference and name conflict resolution qualifier.
MOVE "abc" TO the-field OF the-record OF the-structure
Synonym for IN
Turn off a switch. See ON.
SPECIAL-NAMES.
SWITCH-1 IS mainframe
ON STATUS IS bigiron
OFF STATUS IS pc
...
SET mainframe TO OFF
Allows for placeholders in call frames and testing for said placeholders.
Also allows for omitted label records, and void returns. OMITTED is only
allowed with BY REFERENCE data.
CALL "thing" USING
BY REFERENCE string-var
BY VALUE number-var
BY REFERENCE OMITTED
GIVING NULL
END-CALL
...
PROGRAM-ID. thing.
DATA DIVISION.
WORKING-STORAGE SECTION.
77 default-float usage float-long.
LINKAGE-SECTION.
77 string-var pic x(80).
77 number-var pic 9(8).
77 float-var usage float-long.
PROCEDURE DIVISION
USING
BY REFERENCE OPTIONAL string-var
BY VALUE number-var
BY REFERENCE OPTIONAL float-var
RETURNING OMITTED.
IF float-var IS OMITTED
SET ADDRESS OF float-var TO default-float
END-IF
Turn on a switch. See OFF.
SPECIAL-NAMES.
SWITCH-1 IS mainframe
ON STATUS IS bigiron
OFF STATUS IS pc
...
SET mainframe TO ON
Starts declaratives.
ADD 1 TO wafer-thin-mint
ON SIZE ERROR
SET get-a-bucket TO TRUE
END-ADD
See SIZE, EXCEPTION.
Sharing control. SHARING WITH READ ONLY
Opens a file selector. Modes include INPUT, OUTPUT, I-O, EXTEND.
May be OPTIONAL in the FD.
OPEN INPUT SHARING WITH ALL OTHER infile
OPEN EXTEND SHARING WITH NO OTHER myfile
Allows for referencing non-existent files. Allows for optionally OMITTED call
arguments.
Code below shows optional file open and optional CALL arguments.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT OPTIONAL nofile ASSIGN TO "file.not"
ORGANIZATION IS LINE SEQUENTIAL.
...
DATA DIVISION.
LINKAGE SECTION.
77 arg PIC 99.
PROCEDURE DIVISION USING OPTIONAL arg
OPEN INPUT nofile
CLOSE nofile
IF arg IS OMITTED OR NOT NUMERIC
MOVE 0 TO RETURN-CODE
ELSE
MOVE arg TO RETURN-CODE
END-IF
GOBACK.
Logical operation. See AND, NOT. OpenCOBOL supports COBOL’s logical
expression shortcuts. Order of precedence can be controlled with parenthesis,
and default to NOT, AND, OR, right to left.
IF A NOT EQUAL 1 OR 2 OR 3 OR 5
DISPLAY "FORE!" END-DISPLAY
END-IF
Sort clause to influence how duplicates are managed.
sort sort-work
ascending key work-rec with duplicates in order
using sort-in
giving sort-out.
In 1.1pre-rel, WITH DUPLICATES IN ORDER is a default.
File sharing option, ALL OTHER, NO OTHER.
EVALUATE‘s else clause.
OCOBOL*> Here be dragons <*
EVALUATE TRUE
WHEN a IS 1
PERFORM paragraph-1
WHEN OTHER
ALTER paragraph-1 TO paragraph-2
PERFORM paragraph-3
END-EVALUATE
File OPEN mode. Procedure named in SORT
sort sort-work
on descending key work-rec
collating sequence is mixed
input procedure is sort-transform
output procedure is output-uppercase.
Declarative clause for STRING and UNSTRING that will trigger on
space overflow conditions.
A display control for SCREEN section fields.
Unsupportd Object COBOL METHOD-ID clause.
Numeric USAGE clause, equivalent to COMPUTATIONAL-3. Holds
each digit in a 4-bit field.
From the opencobol-2.0 tarball testsuite
OCOBOL
IDENTIFICATION DIVISION.
PROGRAM-ID. prog.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 G-1.
02 X-1 PIC 9(1) VALUE 1
PACKED-DECIMAL.
02 FILLER PIC X(18) VALUE SPACE.
01 G-2.
02 X-2 PIC 9(2) VALUE 12
PACKED-DECIMAL.
02 FILLER PIC X(18) VALUE SPACE.
01 G-3.
02 X-3 PIC 9(3) VALUE 123
PACKED-DECIMAL.
02 FILLER PIC X(18) VALUE SPACE.
01 G-4.
02 X-4 PIC 9(4) VALUE 1234
PACKED-DECIMAL.
02 FILLER PIC X(18) VALUE SPACE.
01 G-5.
02 X-5 PIC 9(5) VALUE 12345
PACKED-DECIMAL.
02 FILLER PIC X(18) VALUE SPACE.
01 G-6.
02 X-6 PIC 9(6) VALUE 123456
PACKED-DECIMAL.
02 FILLER PIC X(18) VALUE SPACE.
01 G-7.
02 X-7 PIC 9(7) VALUE 1234567
PACKED-DECIMAL.
02 FILLER PIC X(18) VALUE SPACE.
01 G-8.
02 X-8 PIC 9(8) VALUE 12345678
PACKED-DECIMAL.
02 FILLER PIC X(18) VALUE SPACE.
01 G-9.
02 X-9 PIC 9(9) VALUE 123456789
PACKED-DECIMAL.
02 FILLER PIC X(18) VALUE SPACE.
01 G-10.
02 X-10 PIC 9(10) VALUE 1234567890
PACKED-DECIMAL.
02 FILLER PIC X(18) VALUE SPACE.
01 G-11.
02 X-11 PIC 9(11) VALUE 12345678901
PACKED-DECIMAL.
02 FILLER PIC X(18) VALUE SPACE.
01 G-12.
02 X-12 PIC 9(12) VALUE 123456789012
PACKED-DECIMAL.
02 FILLER PIC X(18) VALUE SPACE.
01 G-13.
02 X-13 PIC 9(13) VALUE 1234567890123
PACKED-DECIMAL.
02 FILLER PIC X(18) VALUE SPACE.
01 G-14.
02 X-14 PIC 9(14) VALUE 12345678901234
PACKED-DECIMAL.
02 FILLER PIC X(18) VALUE SPACE.
01 G-15.
02 X-15 PIC 9(15) VALUE 123456789012345
PACKED-DECIMAL.
02 FILLER PIC X(18) VALUE SPACE.
01 G-16.
02 X-16 PIC 9(16) VALUE 1234567890123456
PACKED-DECIMAL.
02 FILLER PIC X(18) VALUE SPACE.
01 G-17.
02 X-17 PIC 9(17) VALUE 12345678901234567
PACKED-DECIMAL.
02 FILLER PIC X(18) VALUE SPACE.
01 G-18.
02 X-18 PIC 9(18) VALUE 123456789012345678
PACKED-DECIMAL.
02 FILLER PIC X(18) VALUE SPACE.
01 G-S1.
02 X-S1 PIC S9(1) VALUE -1
PACKED-DECIMAL.
02 FILLER PIC X(18) VALUE SPACE.
01 G-S2.
02 X-S2 PIC S9(2) VALUE -12
PACKED-DECIMAL.
02 FILLER PIC X(18) VALUE SPACE.
01 G-S3.
02 X-S3 PIC S9(3) VALUE -123
PACKED-DECIMAL.
02 FILLER PIC X(18) VALUE SPACE.
01 G-S4.
02 X-S4 PIC S9(4) VALUE -1234
PACKED-DECIMAL.
02 FILLER PIC X(18) VALUE SPACE.
01 G-S5.
02 X-S5 PIC S9(5) VALUE -12345
PACKED-DECIMAL.
02 FILLER PIC X(18) VALUE SPACE.
01 G-S6.
02 X-S6 PIC S9(6) VALUE -123456
PACKED-DECIMAL.
02 FILLER PIC X(18) VALUE SPACE.
01 G-S7.
02 X-S7 PIC S9(7) VALUE -1234567
PACKED-DECIMAL.
02 FILLER PIC X(18) VALUE SPACE.
01 G-S8.
02 X-S8 PIC S9(8) VALUE -12345678
PACKED-DECIMAL.
02 FILLER PIC X(18) VALUE SPACE.
01 G-S9.
02 X-S9 PIC S9(9) VALUE -123456789
PACKED-DECIMAL.
02 FILLER PIC X(18) VALUE SPACE.
01 G-S10.
02 X-S10 PIC S9(10) VALUE -1234567890
PACKED-DECIMAL.
02 FILLER PIC X(18) VALUE SPACE.
01 G-S11.
02 X-S11 PIC S9(11) VALUE -12345678901
PACKED-DECIMAL.
02 FILLER PIC X(18) VALUE SPACE.
01 G-S12.
02 X-S12 PIC S9(12) VALUE -123456789012
PACKED-DECIMAL.
02 FILLER PIC X(18) VALUE SPACE.
01 G-S13.
02 X-S13 PIC S9(13) VALUE -1234567890123
PACKED-DECIMAL.
02 FILLER PIC X(18) VALUE SPACE.
01 G-S14.
02 X-S14 PIC S9(14) VALUE -12345678901234
PACKED-DECIMAL.
02 FILLER PIC X(18) VALUE SPACE.
01 G-S15.
02 X-S15 PIC S9(15) VALUE -123456789012345
PACKED-DECIMAL.
02 FILLER PIC X(18) VALUE SPACE.
01 G-S16.
02 X-S16 PIC S9(16) VALUE -1234567890123456
PACKED-DECIMAL.
02 FILLER PIC X(18) VALUE SPACE.
01 G-S17.
02 X-S17 PIC S9(17) VALUE -12345678901234567
PACKED-DECIMAL.
02 FILLER PIC X(18) VALUE SPACE.
01 G-S18.
02 X-S18 PIC S9(18) VALUE -123456789012345678
PACKED-DECIMAL.
02 FILLER PIC X(18) VALUE SPACE.
PROCEDURE DIVISION.
*> Dump all values <*
CALL "dump" USING G-1
END-CALL.
CALL "dump" USING G-2
END-CALL.
CALL "dump" USING G-3
END-CALL.
CALL "dump" USING G-4
END-CALL.
CALL "dump" USING G-5
END-CALL.
CALL "dump" USING G-6
END-CALL.
CALL "dump" USING G-7
END-CALL.
CALL "dump" USING G-8
END-CALL.
CALL "dump" USING G-9
END-CALL.
CALL "dump" USING G-10
END-CALL.
CALL "dump" USING G-11
END-CALL.
CALL "dump" USING G-12
END-CALL.
CALL "dump" USING G-13
END-CALL.
CALL "dump" USING G-14
END-CALL.
CALL "dump" USING G-15
END-CALL.
CALL "dump" USING G-16
END-CALL.
CALL "dump" USING G-17
END-CALL.
CALL "dump" USING G-18
END-CALL.
CALL "dump" USING G-S1
END-CALL.
CALL "dump" USING G-S2
END-CALL.
CALL "dump" USING G-S3
END-CALL.
CALL "dump" USING G-S4
END-CALL.
CALL "dump" USING G-S5
END-CALL.
CALL "dump" USING G-S6
END-CALL.
CALL "dump" USING G-S7
END-CALL.
CALL "dump" USING G-S8
END-CALL.
CALL "dump" USING G-S9
END-CALL.
CALL "dump" USING G-S10
END-CALL.
CALL "dump" USING G-S11
END-CALL.
CALL "dump" USING G-S12
END-CALL.
CALL "dump" USING G-S13
END-CALL.
CALL "dump" USING G-S14
END-CALL.
CALL "dump" USING G-S15
END-CALL.
CALL "dump" USING G-S16
END-CALL.
CALL "dump" USING G-S17
END-CALL.
CALL "dump" USING G-S18
END-CALL.
INITIALIZE X-1.
CALL "dump" USING G-1
END-CALL.
INITIALIZE X-2.
CALL "dump" USING G-2
END-CALL.
INITIALIZE X-3.
CALL "dump" USING G-3
END-CALL.
INITIALIZE X-4.
CALL "dump" USING G-4
END-CALL.
INITIALIZE X-5.
CALL "dump" USING G-5
END-CALL.
INITIALIZE X-6.
CALL "dump" USING G-6
END-CALL.
INITIALIZE X-7.
CALL "dump" USING G-7
END-CALL.
INITIALIZE X-8.
CALL "dump" USING G-8
END-CALL.
INITIALIZE X-9.
CALL "dump" USING G-9
END-CALL.
INITIALIZE X-10.
CALL "dump" USING G-10
END-CALL.
INITIALIZE X-11.
CALL "dump" USING G-11
END-CALL.
INITIALIZE X-12.
CALL "dump" USING G-12
END-CALL.
INITIALIZE X-13.
CALL "dump" USING G-13
END-CALL.
INITIALIZE X-14.
CALL "dump" USING G-14
END-CALL.
INITIALIZE X-15.
CALL "dump" USING G-15
END-CALL.
INITIALIZE X-16.
CALL "dump" USING G-16
END-CALL.
INITIALIZE X-17.
CALL "dump" USING G-17
END-CALL.
INITIALIZE X-18.
CALL "dump" USING G-18
END-CALL.
INITIALIZE X-S1.
CALL "dump" USING G-S1
END-CALL.
INITIALIZE X-S2.
CALL "dump" USING G-S2
END-CALL.
INITIALIZE X-S3.
CALL "dump" USING G-S3
END-CALL.
INITIALIZE X-S4.
CALL "dump" USING G-S4
END-CALL.
INITIALIZE X-S5.
CALL "dump" USING G-S5
END-CALL.
INITIALIZE X-S6.
CALL "dump" USING G-S6
END-CALL.
INITIALIZE X-S7.
CALL "dump" USING G-S7
END-CALL.
INITIALIZE X-S8.
CALL "dump" USING G-S8
END-CALL.
INITIALIZE X-S9.
CALL "dump" USING G-S9
END-CALL.
INITIALIZE X-S10.
CALL "dump" USING G-S10
END-CALL.
INITIALIZE X-S11.
CALL "dump" USING G-S11
END-CALL.
INITIALIZE X-S12.
CALL "dump" USING G-S12
END-CALL.
INITIALIZE X-S13.
CALL "dump" USING G-S13
END-CALL.
INITIALIZE X-S14.
CALL "dump" USING G-S14
END-CALL.
INITIALIZE X-S15.
CALL "dump" USING G-S15
END-CALL.
INITIALIZE X-S16.
CALL "dump" USING G-S16
END-CALL.
INITIALIZE X-S17.
CALL "dump" USING G-S17
END-CALL.
INITIALIZE X-S18.
CALL "dump" USING G-S18
END-CALL.
MOVE ZERO TO X-1.
CALL "dump" USING G-1
END-CALL.
MOVE ZERO TO X-2.
CALL "dump" USING G-2
END-CALL.
MOVE ZERO TO X-3.
CALL "dump" USING G-3
END-CALL.
MOVE ZERO TO X-4.
CALL "dump" USING G-4
END-CALL.
MOVE ZERO TO X-5.
CALL "dump" USING G-5
END-CALL.
MOVE ZERO TO X-6.
CALL "dump" USING G-6
END-CALL.
MOVE ZERO TO X-7.
CALL "dump" USING G-7
END-CALL.
MOVE ZERO TO X-8.
CALL "dump" USING G-8
END-CALL.
MOVE ZERO TO X-9.
CALL "dump" USING G-9
END-CALL.
MOVE ZERO TO X-10.
CALL "dump" USING G-10
END-CALL.
MOVE ZERO TO X-11.
CALL "dump" USING G-11
END-CALL.
MOVE ZERO TO X-12.
CALL "dump" USING G-12
END-CALL.
MOVE ZERO TO X-13.
CALL "dump" USING G-13
END-CALL.
MOVE ZERO TO X-14.
CALL "dump" USING G-14
END-CALL.
MOVE ZERO TO X-15.
CALL "dump" USING G-15
END-CALL.
MOVE ZERO TO X-16.
CALL "dump" USING G-16
END-CALL.
MOVE ZERO TO X-17.
CALL "dump" USING G-17
END-CALL.
MOVE ZERO TO X-18.
CALL "dump" USING G-18
END-CALL.
MOVE ZERO TO X-S1.
CALL "dump" USING G-S1
END-CALL.
MOVE ZERO TO X-S2.
CALL "dump" USING G-S2
END-CALL.
MOVE ZERO TO X-S3.
CALL "dump" USING G-S3
END-CALL.
MOVE ZERO TO X-S4.
CALL "dump" USING G-S4
END-CALL.
MOVE ZERO TO X-S5.
CALL "dump" USING G-S5
END-CALL.
MOVE ZERO TO X-S6.
CALL "dump" USING G-S6
END-CALL.
MOVE ZERO TO X-S7.
CALL "dump" USING G-S7
END-CALL.
MOVE ZERO TO X-S8.
CALL "dump" USING G-S8
END-CALL.
MOVE ZERO TO X-S9.
CALL "dump" USING G-S9
END-CALL.
MOVE ZERO TO X-S10.
CALL "dump" USING G-S10
END-CALL.
MOVE ZERO TO X-S11.
CALL "dump" USING G-S11
END-CALL.
MOVE ZERO TO X-S12.
CALL "dump" USING G-S12
END-CALL.
MOVE ZERO TO X-S13.
CALL "dump" USING G-S13
END-CALL.
MOVE ZERO TO X-S14.
CALL "dump" USING G-S14
END-CALL.
MOVE ZERO TO X-S15.
CALL "dump" USING G-S15
END-CALL.
MOVE ZERO TO X-S16.
CALL "dump" USING G-S16
END-CALL.
MOVE ZERO TO X-S17.
CALL "dump" USING G-S17
END-CALL.
MOVE ZERO TO X-S18.
CALL "dump" USING G-S18
END-CALL.
STOP RUN.
With a support file to dump the first 10 bytes of each record
#include <stdio.h>
#ifdef __INTEL_COMPILER
#pragma warning ( disable : 1419 )
#endif
int dump (unsigned char *data);
int dump (unsigned char *data)
{
int i;
for (i = 0; i < 10; i++)
printf ("%02x", data[i]);
puts ("");
return 0;
}
/**/
Which captures:
1f202020202020202020
012f2020202020202020
123f2020202020202020
01234f20202020202020
12345f20202020202020
0123456f202020202020
1234567f202020202020
012345678f2020202020
123456789f2020202020
01234567890f20202020
12345678901f20202020
0123456789012f202020
1234567890123f202020
012345678901234f2020
123456789012345f2020
01234567890123456f20
12345678901234567f20
0123456789012345678f
1d202020202020202020
012d2020202020202020
123d2020202020202020
01234d20202020202020
12345d20202020202020
0123456d202020202020
1234567d202020202020
012345678d2020202020
123456789d2020202020
01234567890d20202020
12345678901d20202020
0123456789012d202020
1234567890123d202020
012345678901234d2020
123456789012345d2020
01234567890123456d20
12345678901234567d20
0123456789012345678d
0f202020202020202020
000f2020202020202020
000f2020202020202020
00000f20202020202020
00000f20202020202020
0000000f202020202020
0000000f202020202020
000000000f2020202020
000000000f2020202020
00000000000f20202020
00000000000f20202020
0000000000000f202020
0000000000000f202020
000000000000000f2020
000000000000000f2020
00000000000000000f20
00000000000000000f20
0000000000000000000f
0c202020202020202020
000c2020202020202020
000c2020202020202020
00000c20202020202020
00000c20202020202020
0000000c202020202020
0000000c202020202020
000000000c2020202020
000000000c2020202020
00000000000c20202020
00000000000c20202020
0000000000000c202020
0000000000000c202020
000000000000000c2020
000000000000000c2020
00000000000000000c20
00000000000000000c20
0000000000000000000c
0f202020202020202020
000f2020202020202020
000f2020202020202020
00000f20202020202020
00000f20202020202020
0000000f202020202020
0000000f202020202020
000000000f2020202020
000000000f2020202020
00000000000f20202020
00000000000f20202020
0000000000000f202020
0000000000000f202020
000000000000000f2020
000000000000000f2020
00000000000000000f20
00000000000000000f20
0000000000000000000f
0c202020202020202020
000c2020202020202020
000c2020202020202020
00000c20202020202020
00000c20202020202020
0000000c202020202020
0000000c202020202020
000000000c2020202020
000000000c2020202020
00000000000c20202020
00000000000c20202020
0000000000000c202020
0000000000000c202020
000000000000000c2020
000000000000000c2020
00000000000000000c20
00000000000000000c20
0000000000000000000c
Defines a character to use for short record padding.
ORGANIZATION IS LINE SEQUENTIAL PADDING CHARACTER IS '*'
Write and Report writer clause.
WRITE theline AFTER ADVANCING PAGE
PAGE LIMITS ARE 66 LINES 132 COLUMNS
HEADING iS 4 FIRST DETAIL IS 6
LAST CONTROL HEADING IS 58
LAST DETAIL IS 60
FOOTING IS 62
A special register, qualified by Report Name. Report Writer is recognized
but not yet supported.
An allowable EXIT point.
NAMED-PARAGRAPH.
PERFORM FOREVER
IF solution
EXIT PARAGRAPH
END-IF
PERFORM solve-the-puzzle.
END-PERFORM.
A commonly used shortform of PICTURE.
The PICTURE clause is easily one of COBOL’s greatest strengths. Fully
detailed pictorial data definitions. The internal complexity is left
to compiler authors, while developers and management are free to
describe data at a very high conceptual level.
The two most common picture characters are 9 and X, for numeric and
alphanumeric data respectively. For alphbetic data, A can be used.
Aside from data storage pictures, a vast array of edit pictures are
allowed for control of input and output formatting.
+, -, A, B, N, X, Z, “*”, ‘CR’, ‘DB’, E, S, V, ., P, currency symbol
OpenCOBOL offers full standards support of all alpha, alphanumeric and
numeric storage specifiers as well as full support for edit and numeric-edit
clauses.
An example of some of the PICTURE options
*>>source format is free
*> ********************************************************************
*> Author: jrls (John Ellis)
*> Date: Oct-2008
*> Purpose: formated output examples using pic strings.
*> ********************************************************************
identification division.
program-id. picstring.
data division.
working-storage section.
*><*
01 header.
05 filler pic xxx value "ln".
05 filler pic x(11) value " disp1".
05 filler pic x(11) value " disp2".
05 filler pic x(11) value " disp3".
05 filler pic x(11) value " disp4".
05 filler pic x(12) value " disp5".
05 filler pic x(9) value " an1".
05 filler pic x(14) value " phone".
05 filler pic x(10) value " date".
*><*
01 headerLines pic x(90) value all "-".
*><*
01 displayformats.
05 linenum pic 99 value 1.
05 disp1 pic zzz,zz9.99 value zero.
05 filler pic x value spaces.
05 disp2 pic $zz,zz9.99 value zero.
05 filler pic x value spaces.
05 disp3 pic ---,--9.99 value zero.
05 filler pic x value spaces.
05 disp4 pic $-z,zz9.99 value zero.
05 filler pic x value spaces.
05 disp5 pic -zz,zz9.zz- blank zero value zero.
05 filler pic x value spaces.
*><*an1 is actually a string field because of the embedded blanks, thus you put value spaces.
05 an1 pic 99b99b99 value spaces.
05 filler pic x value spaces.
05 phone pic bxxxbxxxbxxxx value spaces.
05 filler pic x value spaces.
05 dispdate pic 99/99/9999 value zero.
*><*
procedure division.
0000-start.
*><*
display headerLines.
display header.
display headerLines.
*><****************************************************
move 220.22 to disp1,
disp2.
move -220.22 to disp3,
disp4,
disp5.
inspect disp5 replacing first "-" by "(",
first "-" by ")".
move 10122008 to dispdate.
*><****************************************************
*><*Please note the results of moving 'abcd' to an1.
*><*an1 will show up as 00 00 00 because alpha data was
*><*moved into instead of numeric data.
*><*
*><*The phone field will display " abc def ghij" because
*><*'b' in the pic string.
*><****************************************************
move "abcd" to an1.
move "abcdefghij" to phone.
display displayformats.
add 1 to linenum.
move zero to disp4,
disp5.
*><****************************************************
*><*Here after moving data to an1 and phone, I use the
*><*inspect statement to replace the blanks.
*><****************************************************
move "123456" to an1.
move "5555551234" to phone.
inspect an1 replacing all " " by "-".
inspect phone replacing first " " by "(",
first " " by ")",
first " " by "-".
display displayformats.
inspect phone converting "23456789" to "adgjmptw".
display phone.
perform 0010-endProgram.
*><*
0010-endProgram.
stop run.
*><*
Outputs:
------------------------------------------------------------------------------------------
ln disp1 disp2 disp3 disp4 disp5 an1 phone date
------------------------------------------------------------------------------------------
01 220.22 $220.22 -220.22 $-220.22 (220.22) 00 00 00 abc def ghij 10/12/2008
02 220.22 $220.22 -220.22 $ 0.00 12-34-56 (555)555-1234 10/12/2008
(jjj)jjj-1adg
Screen section relative line / column control during layout.
01 form-1 AUTO.
05 LINE 01 COLUMN 01 VALUE "Form!".
05 LINE PLUS 3 COLUMN 01 VALUE value-4.
Allocates a restricted use variable for holding addresses.
01 c-handle USAGE IS POINTER.
CALL "open-lib" RETURNING c-handle
ON EXCEPTION
DISPLAY "Can't link open-lib" END-DISPLAY
STOP RUN RETURNING 1
END-CALL
IF c-handle EQUAL NULL
DISPLAY "Can't open-lib" END-DISPLAY
STOP RUN RETURNING 1
END-IF
CALL "use-lib" USING BY VALUE c-handle BY CONTENT "Hello" & x"00"
CALL "close-lib" USING BY VALUE c-handle
*> Interfacing with the C ABI is just a teenie-weenie bit of voodoo
*> Pass the REFERENCE or use RETURNING if C sets the value. Use
*> VALUE when you want C to have its pointer, not the
*> REFERENCE address of the COBOL POINTER. So most inits are
*> BY REFERENCE (or RETURNING) and most usage, including
*> rundown of C ABI tools, is USING BY VALUE.
*> <*
Alias for COLUMN in screen section layouts. Also an obsolete,
recognized but not supported:
MULTIPLE FILE TAPE CONTAINS file-1 POSITION 1 file-2 POSITION 80
Class condition.
IF amount IS POSITIVE
DISPLAY "Not broke yet" END-DISPLAY
END-IF
Report Writer clause used for optional field and group output.
05 field PIC X(16) PRESENT WHEN sum > 0.
Previous key READ control for INDEXED files.
READ file-1 PREVIOUS RECORD
Special name.
SPECIAL-NAMES.
PRINTER IS myprint
DISPLAY "test" UPON PRINTER END-DISPLAY
Report Writer declarative to SUPPRESS report printing.
The COBOL DIVISION that holds the executable statements. Also used with
INPUT and OUTPUT sort procedures.
Debug module declarative clause.
USE FOR DEBUGGING ON ALL PROCEDURES
Used in ALTER.
ALTER paragraph-1 TO PROCEED TO paragraph-x
The program identifier. Case sensitive, unlike all other OpenCOBOL
identifiers. OpenCOBOL produces C Application Binary Interface
linkable entities and this identifier must conform to those rules.
Dashes in names are replaced by a hex string equivalent.
A data USAGE clause defining a field that can hold the executable
address of a CALL routine.
77 callback USAGE PROGRAM-POINTER.
...
SET callback TO ENTRY a-program-id
CALL callback
Screen section input control.
Unsupported Object COBOL phrase.
Unsupported Object COBOL phrase.
Unsupported Communication Section clause.
Unsupported Communication Section clause.
A figurative constant representing ‘”’.
DISPLAY QUOTE 123 QUOTE END-DISPLAY
Outputs:
A figurative constant representing ‘”’.
01 var PICTURE X(4).
MOVE ALL QUOTES TO var
DISPLAY var END-DISPLAY
Outputs:
Exception handling. There IS support for exceptions in OpenCOBOL but it is
currently fairly limited. See FUNCTION EXCEPTION-LOCATION for a sample.
RAISE is not yet recognized.
Exception handling. There IS support for exceptions in OpenCOBOL but it is
currently limited. RAISING is not yet recognized.
A file access mode. RANDOM access allows seeks to any point in a file,
usually by KEY.
Report writer DATA division, REPORT section descriptor. Currently
unsupported.
DATA DIVISION.
REPORT SECTION.
RD report-1
PAGE LIMIT IS 66 LINES.
A staple of COBOL. Read a record.
READ infile PREVIOUS RECORD INTO back-record
AT END
SET attop TO TRUE
NOT AT END
PERFORM cursor-calculator
END-READ
An unsupported Communication Section clause.
Multiple use phrase.
FD file
RECORD IS VARYING IN SIZE FROM 1 TO 80 CHARACTERS
DEPENDING ON size-field
SELECT file
ASSIGN TO filename
ACCESS MODE IS RANDOM
RECORD KEY IS key-field
ALTERNATE KEY IS alt-key WITH DUPLICATES.
READ infile NEXT RECORD INTO display-rec END-READ
An obsolete, recognized, but ignored file descriptor clause.
FD file
RECORD IS VARYING IN SIZE FROM 1 TO 80 CHARACTERS
DEPENDING ON size-field
RECORDING MODE IS F.
Specifies a PROGRAM-ID as having the recursive attribute. Recursive
sub programs can CALL themselves.
This qualifier has implications on how OpenCOBOL allocates storage.
Normally storage is stacked, recursion can chew through
stack space very quickly. Sub programs marked RECURSIVE are usually
allocated using the memory heap.
PROGRAM-ID nextbigthing IS RECURSIVE.
A very powerful DATA division control alllowing for redefinition
of memory storage, including incompatible data by type.
IDENTIFICATION DIVISION.
PROGRAM-ID. prog.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 X PIC X.
01 G REDEFINES X.
02 A PIC X.
02 B REDEFINES A PIC 9.
PROCEDURE DIVISION.
STOP RUN.
A tape device qualifier
CLOSE file REEL FOR REMOVAL
The default COBOL CALL argument handler. CALL arguments can be
BY REFERENCE
BY CONTENT
BY VALUE
where by reference passes a reference pointer, allowing data modification
inside sub programs.
File organization where the position of a logical record is determined by its
relative record number.
OCOBOL >>SOURCE FORMAT IS FIXED
*> ***************************************************************
*> Author: Brian Tiffin
*> Date: 20110806
*> Purpose: RELATIVE file organization
*> Tectonics: cobc -g -debug -W -x relatives.cob
*> ***************************************************************
identification division.
program-id. relatives.
environment division.
configuration section.
repository.
function all intrinsic.
input-output section.
file-control.
select optional relatives
assign to "relatives.dat"
file status is filestatus
organization is relative
access mode is dynamic
relative key is nicknum.
data division.
file section.
fd relatives.
01 person.
05 firstname pic x(48).
05 lastname pic x(64).
05 relationship pic x(32).
working-storage section.
77 filestatus pic 9(2).
88 ineof value 1 when set to false is 0.
77 satisfaction pic 9.
88 satisfied value 1 when set to false is 0.
77 nicknum pic 9(2).
77 title-line pic x(34).
88 writing-names value "Adding, Overwriting. 00 to finish".
88 reading-names value "Which record? 00 to quit".
77 problem pic x(80).
screen section.
01 detail-screen.
05 line 1 column 1 from title-line erase eos.
05 line 2 column 1 value "Record: ".
05 pic 9(2) line 2 column 16 using nicknum.
05 line 3 column 1 value "First name: ".
05 pic x(48) line 3 column 16 using firstname.
05 line 4 column 1 value "Last name: ".
05 pic x(64) line 4 column 16 using lastname.
05 line 5 column 1 value "Relation: ".
05 pic x(32) line 5 column 16 using relationship.
05 pic x(80) line 6 column 1 from problem.
01 show-screen.
05 line 1 column 1 from title-line erase eos.
05 line 2 column 1 value "Record: ".
05 pic 9(2) line 2 column 16 using nicknum.
05 line 3 column 1 value "First name: ".
05 pic x(48) line 3 column 16 from firstname.
05 line 4 column 1 value "Last name: ".
05 pic x(64) line 4 column 16 from lastname.
05 line 5 column 1 value "Relation: ".
05 pic x(32) line 5 column 16 from relationship.
05 pic x(80) line 6 column 1 from problem.
*> -*********-*********-*********-*********-*********-*********-**
procedure division.
beginning.
*> Open the file and find the highest record number
*> which is a sequential read operation after START
open input relatives
move 99 to nicknum
start relatives key is less than or equal to nicknum
invalid key
move concatenate('NO START' space filestatus)
to problem
move 00 to nicknum
not invalid key
read relatives next end-read
end-start
*> Close and open for i-o
close relatives
open i-o relatives
*> Prompt for numbers and names to add until 00
set writing-names to true
set satisfied to false
perform fill-file through fill-file-end
until satisfied
close relatives
*> Prompt for numbers to view names of until 00
open input relatives
set reading-names to true
set satisfied to false
perform record-request through record-request-end
until satisfied
perform close-shop
.
ending.
goback.
*> get some user data to add
fill-file.
display detail-screen end-display.
accept detail-screen end-accept.
move spaces to problem
if nicknum equal 0
set satisfied to true
go to fill-file-end
end-if.
.
write-file.
write person
invalid key
move concatenate("overwriting: " nicknum) to problem
rewrite person
invalid key
move concatenate(
exception-location() space nicknum
space filestatus)
to problem
end-rewrite
end-write.
display detail-screen end-display
.
fill-file-end.
.
*> get keys to display
record-request.
display show-screen end-display
accept show-screen end-accept
move spaces to problem
if nicknum equals 0
set satisfied to true
go to record-request-end
end-if
.
*> The magic of relative record number reads
read-relation.
read relatives
invalid key
move exception-location() to problem
not invalid key
move spaces to problem
end-read
display show-screen end-display
.
record-request-end.
.
*> get out <*
close-shop.
close relatives.
goback.
.
end program relatives.
with sample screens:
Adding, Overwriting. 00 to finish
Record: 04
First name: Brad____________________________________________
Last name: Tiffin__________________________________________________________
Relation: brother_________________________
allowing for new record additions or overwrites of existing key numbers, and:
Which record? 00 to quit
Record: 03
First name: Brian
Last name: Tiffin
Relation:
where typing in a nicknum record number retrieves the relative record.
Release a record to a SORT. Used with INPUT PROCEDURE of SORT verb.
RELEASE record-1 FROM identifier-1
Access to integer remainders during division.
DIVIDE
hex-val BY 16 GIVING left-nibble REMAINDER right-nibble
END-DIVIDE
A close clause.
CLOSE filename-1 REEL FOR REMOVAL
Specifies that the file is stored on multiple removable tapes/disks. Not all
systems support such devices.
OpenCOBOL supports regrouping of level 02-49 data items with level 66 and
RENAMES.
OCOBOL >>SOURCE FORMAT IS FIXED
*> ***************************************************************
*> Author: Brian Tiffin
*> Date: 20110606
*> Purpose: Demonstration of 66-level datanames
*> Tectonics: cobc
*> ***************************************************************
identification division.
program-id. sixtysix.
data division.
working-storage section.
01 master.
05 field-1 pic s9(9).
05 field-2 pic x(16).
05 field-3 pic x(4).
05 field-4 pic s9(9).
66 sixtysix renames field-2.
66 group-66 renames field-2 through field-4.
*> ***************************************************************
procedure division.
move -66 to field-1
move "sixtysix" to field-2
move "ABCD" to field-3
multiply field-1 by -1 giving field-4 end-multiply
display "master : " master end-display
display "field-1 : " field-1 end-display
display "sixtysix: " sixtysix end-display
display "group-66: " group-66 end-display
goback.
end program sixtysix.
giving:
$ ./sixtysix
master : 00000006vsixtysix ABCD000000066
field-1 : -000000066
sixtysix: sixtysix
group-66: sixtysix ABCD000000066
A COBOL text preprocessing operator.
REPLACE ==MARKER== BY ==DISPLAY "REPLACE EXAMPLE" END-DISPLAY==.
identification division.
program-id. prog.
procedure division.
MARKER
goback.
end program prog.
And then to see how that REPLACE is working, use cobc with the -E argument
# 1 "replacing.cob"
identification division.
program-id. prog.
procedure division.
DISPLAY "REPLACE EXAMPLE" END-DISPLAY
goback.
end program prog.
Unsupported Report Writer section and File descriptor clause.
Unsupported declarative for Report Writer.
Unsupported Report Writer file descriptor clause associating files
with named reports.
A paragraph of the CONFIGURATION SECTION. OpenCOBOL supports the
FUNCTION ALL INTRINSIC clause of the REPOSITORY. Allows source
code to use intrinsic functions without the FUNCTION keyword.
OCOBOL >>SOURCE FORMAT IS FIXED
*> ***************************************************************
*> Author: Brian Tiffin
*> Date: 20110213
*> Purpose: Demonstrate an intrinstric function shortcut
*> Tectonics: cobc -x functionall.cob
*> ***************************************************************
identification division.
program-id. functionall.
environment division.
configuration section.
repository.
function all intrinsic.
*> ***************************************************************
procedure division.
display function pi space function e end-display
display pi space e end-display
goback.
end program functionall.
Sample output:
$ cobc -x functionall.cob
$ ./functionall
3.1415926535897932384626433832795029 2.7182818284590452353602874713526625
3.1415926535897932384626433832795029 2.7182818284590452353602874713526625
Without the repository paragraph:
$ cobc -x functionall.cob
functionall.cob:19: Error: 'pi' undefined
functionall.cob:19: Error: 'e' undefined
Recognized but ignored Screen section field attribute.
Unsupported Report Writer data control field clause.
Unsupported declarative control flow statement.
Unsupported record locking wait and retry clause.
- RETRY n TIMES
- RETRY FOR n SECONDS
- RETRY FOREVER
Return records in a SORT OUTPUT PROCEDURE.
Specify the destination of CALL results.
01 result PIC S9(8).
CALL "libfunc" RETURNING result END-CALL
Specify the return field for a sub-program.
PROCEDURE DIVISION USING thing RETURNING otherthing
SCREEN section field display attribute. Functionality dependent on
terminal and operating system support and settings.
A really cool lyric in the Black Eyed Peas song, “Hey Mama”.
Allow overwrite of records where primary key exists.
write person
invalid key
move concatenate("overwriting: " nicknum) to problem
rewrite person
invalid key
move concatenate(
exception-location() space nicknum
space filestatus)
to problem
end-rewrite
end-write.
Short form for unsupported REPORT FOOTING.
Short form for unsupported REPORT HEADING.
Recognized but not fully supported revert of transactional revert of
file writes. See COMMIT.
Well defined rounding clause applied to arithmetic. Defined well enough
for bank managers to feel comfortable handing their calculations over to
a bunch of nerds.
COMPUTE total-value ROUNDED = 1.0 / 6.0 END-COMPUTE
A stopping point.
Terminates run regardless of nesting depth, returning control (and result) to
operating system. See GOBACK and EXIT PROGRAM for other run unit
terminations.
I-O-CONTROL clause for SAME RECORD AREA.
Screen section.
OCOBOL >>SOURCE FORMAT IS FIXED
*> ************************************************************ <*
*> Author: Brian Tiffin
*> Date: 20110701
*> Purpose: Play with 2.0 screen section
*> Tectonics: cobc
*> ************************************************************ <*
identification division.
program-id. screening.
data division.
working-storage section.
01 some-data pic s9(9).
screen section.
01 detail-screen.
03 line 1 column 1 value "title line".
03 line 2 column 1 value "field: ".
03 line 2 column 16 using some-data.
*> ************************************************************ <*
procedure division.
display detail-screen end-display
accept detail-screen end-accept
goback.
end program screening.
being a poor representation of the plethora of field attribute control
allowed in OpenCOBOL screen section.
Screen field attributes include:
- JUSTIFIED RIGHT
- BLANK WHEN ZERO
- OCCURS integer-val TIMES
- BELL, BEEP
- AUTO, AUTO-SKIP, AUTOTERMINATE
- UNDERLINE
- OVERLINE
- SECURE
- REQUIRED
- FULL
- PROMPT
- REVERSE-VIDEO
- BLANK LINE
- BLANK SCREEN
- ERASE EOL
- ERASE EOS
- SIGN IS LEADING SEPERATE CHARACTER
- SIGN IS TRAILING SEPERATE CHARACTER
- LINE NUMBER IS [PLUS] integer-val
- COLUMN NUMBER IS [PLUS] integer-val
- FOREGROUND-COLOR IS integer-val HIGHLIGHT, LOWLIGHT
- BACKGROUND-COLOR IS integer-val BLINK
- PICTURE IS picture-clause USING identifier
- PICTURE IS picture-clause FROM identifier, literal
- PICTURE IS picture-clause TO identifier
- VALUE is literal
During ACCEPT, USING fields are read/write, FROM fields are read and TO
fields are write.
See What are the OpenCOBOL SCREEN SECTION colour values? for colour values.
SORT file data descriptor.
SD sort-file-1
RECORD CONTAINS 80 CHARACTERS.
A powerful table and file search verb. See Linear SEARCH for an example.
Clause of unsupported read/write RETRY on lock.
COBOL source code is organized in DIVISION, SECTION, paragraphs and
sentences. OpenCOBOL supports user named sections and recognizes the
following list of pre-defined sections.
User defined sections provide for source code organization and use of
PERFORM with THROUGH for tried and true COBOL procedural programming.
SCREEN section field attribute. Displayed as asterisks.
Unsupported Communication section clause.
FILE-CONTROL phrase. Associates files with names, descriptors, and options.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT fileresource
ASSIGN TO external-name
FILE STATUS IS identifier
COLLATING SEQUENCE IS alphabet-name
LOCK MODE IS MANUAL WITH LOCK ON MULTIPLE RECORDS
RECORD DELIMITER IS STANDARD
RESERVE num AREA
SHARING WITH NO OTHER
ORGANIZATION IS INDEX
ACCESS MODE IS DYNAMIC
RECORD KEY IS key-field
ALTERNATE RECORD KEY IS key-field-2 WITH DUPLICATES
ALTERNATE RECORD KEY IS key-field-3.
though, naming a quick file can be as simple as
SELECT myfile ASSIGN TO "name.txt".
which will be a default LINE SEQUENTIAL file.
Unsupported Object COBOL clause.
Unsupported Communication section verb.
An obsolete control flow clause. CONTINUE is preferred to NEXT SENTENCE.
Fine tuned control over leading and trailing sign indicator.
77 field-1 PICTURE S9(8) SIGN IS TRAILING SEPARATE.
Controls COLLATING sequence for character compares, by defining a
character set.
OpenCOBOL supports both fixed length SEQUENTIAL and newline terminated
LINE SEQUENTIAL file access.
- SET ADDRESS OF ptr-var TO var.
- SET ENVIRONMENT “name” TO “value”.
- SET cond-1 TO TRUE
That last one is pretty cool. An 88 level conditional set TRUE will
cause the associated value to change to a value that satifies the
condition as true.
01 field-1 pic 99.
88 cond-1 value 42.
MOVE 0 TO field-1
DISPLAY field-1 END-DISPLAY
SET cond-1 TO TRUE
DISPLAY field-1 END-DISPLAY
00 and 42 are displayed.
File sharing option.
- SHARING WITH NO OTHER
- SHARING WITH ALL OTHER
- SHARING WITH READ ONLY
Functionality dependent on build options and operating system running
OpenCOBOL.
Fine tuned control over leading and trailing sign indicator.
77 field-1 PICTURE S9(8) SIGN IS TRAILING SEPARATE.
OpenCOBOL supports the full gamut of COBOL numeric data storage. SIGNED and
UNSIGNED being part and parcel.
Multi purpose.
OpenCOBOL allows SIZE IS control on CALL arguments.
Arthimetic operations allow for declaritives on size errors.
ADD 1 TO ocobol
ON SIZE ERROR
SET erroneous TO TRUE
NOT ON SIZE ERROR
DISPLAY "Whee, ADD 1 TO COBOL" END-DISPLAY
END-ADD
STRING has a DELIMITED BY SIZE option to include entire fields.
OpenCOBOL supports USING, GIVING as well as INPUT PROCEDURE and OUTPUT
PROCEDURE clauses for the SORT verb.
OCOBOL* OpenCOBOL SORT verb example using standard in and standard out
identification division.
program-id. sorting.
environment division.
input-output section.
file-control.
select sort-in
assign keyboard
organization line sequential.
select sort-out
assign display
organization line sequential.
select sort-work
assign "sortwork".
data division.
file section.
fd sort-in.
01 in-rec pic x(255).
fd sort-out.
01 out-rec pic x(255).
sd sort-work.
01 work-rec pic x(255).
procedure division.
sort sort-work
ascending key work-rec
using sort-in
giving sort-out.
goback.
exit program.
end program sorting.
In the next sample, demonstrating INPUT PROCEDURE and OUTPUT PROCEDURE
take note of the RETURN and RELEASE verbs as they are key to record
by record control over sort operations.
Also, just to complicate things, this sample sorts using a mixed-case
alphabet (but also places capital A out of order to demonstrate special
cases that can codified in an ALPHABET).
OCOBOL >>SOURCE FORMAT IS FIXED
******************************************************************
* Author: Brian Tiffin
* Date: 02-Sep-2008
* Purpose: An OpenCOBOL SORT verb example
* Tectonics: cobc -x sorting.cob
* ./sorting <input >output
* or simply
* ./sorting
* for keyboard and screen demos
******************************************************************
identification division.
program-id. sorting.
environment division.
configuration section.
* This sets up a sort order lower then upper except for A and a
special-names.
alphabet mixed is " AabBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTu
-"UvVwWxXyYzZ0123456789".
input-output section.
file-control.
select sort-in
assign keyboard
organization is line sequential.
select sort-out
assign display
organization is line sequential.
select sort-work
assign "sortwork".
data division.
file section.
fd sort-in.
01 in-rec pic x(255).
fd sort-out.
01 out-rec pic x(255).
sd sort-work.
01 work-rec pic x(255).
working-storage section.
01 loop-flag pic x value low-value.
procedure division.
sort sort-work
on descending key work-rec
collating sequence is mixed
input procedure is sort-transform
output procedure is output-uppercase.
display sort-return end-display.
goback.
******************************************************************
sort-transform.
move low-value to loop-flag
open input sort-in
read sort-in
at end move high-value to loop-flag
end-read
perform
until loop-flag = high-value
move FUNCTION LOWER-CASE(in-rec) to work-rec
release work-rec
read sort-in
at end move high-value to loop-flag
end-read
end-perform
close sort-in
.
******************************************************************
output-uppercase.
move low-value to loop-flag
open output sort-out
return sort-work
at end move high-value to loop-flag
end-return
perform
until loop-flag = high-value
move FUNCTION UPPER-CASE(work-rec) to out-rec
write out-rec end-write
return sort-work
at end move high-value to loop-flag
end-return
end-perform
close sort-out
.
exit program.
end program sorting.
Here is a snippet describing TABLE sorts by [jrls_swla]
table define
01 nbr-of-columns pic 9(4) value zero.
01 tcindex2 usage is index.
01 dbtables.
03 tables-columns occurs 1 to 1000 times
depending on nbr-of-columns
ascending key tcTable, tcColumn
indexed by tcindex.
05 tcTable pic x(64) value spaces.
05 tcColumn pic x(64) value spaces.
05 tcAlias pic x(10) value spaces.
05 tcOrder pic 9(4) value zero.
05 tcType pic x(10) value spaces.
05 tcMaxLen pic 9(4) value zero.
*><*
01 aliasName.
05 pic x value "t".
05 anVal pic 9(3) value zero.
01 showdata.
05 sdTable pic x(17) value spaces.
05 sdColumn pic x(17) value spaces.
05 sdType pic x(10) value spaces.
05 sdOrder pic zzzzz-.
05 sdMaxLen pic zzzzz.
table load
perform varying rows from 1 by 1
until rows > dbNumRows
call "dbNextRow" using by value dbResult,
by reference ColumnBuff,
by reference CbuffDesc
returning dbResult
add 1 to nbr-of-columns
set tcindex up by 1
move cbTable to tcTable(tcindex)
move cbColumn to tcColumn(tcindex)
move cbType to tcType(tcindex)
move cbOrder to tcOrder(tcindex)
move cbMaxLen to tcMaxLen(tcindex)
if nbr-of-columns = 1
add 1 to anVal
else
set tcindex2 to tcindex
set tcindex2 down by 1
if cbTable <> tcTable(tcindex2)
add 1 to anVal
end-if
end-if
move aliasName to tcAlias(tcindex)
end-perform.
table sort
sort tables-columns ascending key tcTable, tcColumn.
display table
perform varying tcindex from 1 by 1
until tcindex > nbr-of-columns
move tcTable(tcindex) to sdTable
move tcColumn(tcindex) to sdColumn
move tcOrder(tcindex) to sdOrder
move tcType(tcindex) to sdType
move tcMaxLen(tcindex) to sdMaxLen
display showdata
end-perform.
Excercise for the audience. Could the above code be simplified by using
MOVE CORRESPONDING cbRecord to table-columns(tcindex)
...
MOVE CORRESPONDING table-columns(tcindex) to showdata
with a few judicious field name changes?
Used in an I-O-CONTROL paragraph with the SAME clause:
SAME SORT-MERGE AREA FOR filename-1.
The SORT-MERGE keyword and SORT keyword are equivalent in this case.
A SPECIAL-REGISTER used by the OpenCOBOL SORT routines.
- +000000000 for success
- +000000016 for failure
A programmer may set SORT-RETURN in an INPUT PROCEDURE.
Compiler directive controlling source code handling.
>>SOURCE FORMAT IS FIXED
>>SOURCE FORMAT IS FREE
OpenCOBOL allows use of this directive at programmer whim. cobc
defaults to FIXED format source handling, so the directive must occur
beyond the sequence and indicator columns unless the -free compile option
is used.
Split keys are a pending feature in OpenCOBOL.
SELECT ...
RECORD KEY IS key-name SOURCE is dname-2 dname-3
Also a pending Report Writer data source clause.
Currently unsupported SOURCES ARE report writer clause.
A figurative constant representing a space character.
A figurative constant representing space characters.
OpenCOBOL supports a fair complete set of the SPECIAL-NAMES in common use.
- CONSOLE IS CRT
- SYSIN IS mnemonic-name-1
- SYSOUT IS
- SYSLIST IS
- SYSLST IS
- PRINTER IS
- SYSERR IS
- CONSOLE IS mnemonic-name-7
- SWITCH-1 IS mnemonic-name-n
ON STATUS IS condition-name-1
OFF STATUS IS condition-name-2
- SWITCH-2
- ...
- SWITCH-8 IS ...
- C01 IS mnemonic-name-m
- ...
- C12 IS
- ALPHABET alphabet-name IS
NATIVE, STANDARD-1, STANDARD-2, EBCDIC
literal-1 THRU literal-2 [ALSO literal-3]
- SYMBOLIC CHARACTERS symbol-character IS integer-1
IN alphabet-name
- CLASS class-name IS literal THRU literal-2
- LOCALE locale-name IS identifier-1
- CURRENCY SIGN IS literal
- DECIMAL-POINT IS COMMA
- CURSOR IS identifier-1
- CRT STATUS IS identifier-1
- SCREEN CONTROL IS identifier-1 PENDING
- EVENT STATUS IS identifier-1 PENDING
- LABEL RECORDS ARE STANDARD
- ALPHABET IS STANDARD-1
- RECORD DELIMITER IS STANDARD-1
equivalent to ASCII
- ALPHABET IS STANDARD-1
- RECORD DELIMITER IS STANDARD-1
equivalent to ASCII
Sets internal file fields that will influence sequential READ NEXT
and READ PREVIOUS for INDEXED files. Can also be used to seek
to the FIRST or LAST record of a file for SEQUENTIAL access modes.
start indexing
key is less than
keyfield of indexing-record
invalid key
display
"bad start: " keyfield of indexing-record
end-display
set no-more-records to true
not invalid key
read indexing previous record
at end set no-more-records to true
end-read
end-start
The conditionals are quite powerful.
KEY IS GREATER THAN
KEY IS >
KEY IS LESS THAN
KEY IS <
KEY IS EQUAL TO
KEY IS =
KEY IS NOT GREATER THAN
KEY IS NOT >
KEY IS NOT LESS THAN
KEY IS NOT <
KEY IS NOT EQUAL TO
KEY IS NOT =
KEY IS <>
KEY IS GREATER THAN OR EQUAL TO
KEY IS >=
KEY IS LESS THAN OR EQUAL TO
KEY IS <=
See Does OpenCOBOL support ISAM? for some example source code.
Multi-purpose.
- CRT STATUS IS
- FILE STATUS IS
- EVENT STATUS IS
- SWITCH-1 IS thing ON STATUS IS conditional-1
Unsupported Report Writer OCCURS subclause.
End a run and return control to the operating system.
Forms include:
- STOP RUN
- STOP RUN RETURNING stat
- STOP RUN GIVING stat
- STOP literal
- STOP RUN WITH ERROR STATUS stat
- STOP RUN WITH NORMAL STATUS stat
String together a set of variables with controlled delimiters.
01 var PICTURE X(5).
STRING
"abc" DELIMITED BY "b"
"def" DELIMITED BY SIZE
"ghi" DELIMITED BY "z"
INTO var
ON OVERFLOW
DISPLAY "var is full at" SPACE LENGTH OF var END-DISPLAY
END-STRING
DISPLAY var END-DISPLAY
Outputs:
OpenCOBOL also fully supports the WITH POINTER clause to set the initial
and track the position in the output character variable.
Unsupported Communication section clause.
Unsupported Communication section clause.
Unsupported Communication section clause.
Arithmetic operation.
SUBTRACT a b c FROM d ROUNDED END-SUBTRACT
SUBTRACT a FROM b GIVING c
ON SIZE ERROR
SET math-error TO TRUE
NOT ON SIZE ERROR
SET math-error TO FALSE
END-SUBTRACT
SUBTRACT CORRESPONDING record-a FROM record-b ROUNDED
ON SIZE ERROR
SET something-wrong TO TRUE
END-SUBTRACT
A REPORT SECTION control break summation field clause. Unsupported.
Unsupported Object COBOL clause.
Unsupported declarative to suppress printing.
Control padding inside record definitions, in particular to match C structures.
01 infile.
03 slice occurs 64 times depending on slices.
05 stext usage pointer synchronized.
05 val float-long synchronized.
05 ftext usage pointer synchronized.
OBJECT-COMPUTER clause for locale support.
CHARACTER CLASSIFICATION IS SYSTEM-DEFAULT
Unsupported keyword, but OpenCOBOL fully supports tables, including SORT.
INSPECT clause for counting occurances of a literal.
INSPECT record-1 TALLYING ident-1 FOR LEADING "0"
Unsupported Comminication section clause.
Currently unsupported Report Writer verb to finish up a report. See
INITIATE.
Allows control over when loop conditionals are tested. WITH TEST BEFORE is the
default. WITH TEST AFTER will always evaluate the body of the loop at least
once.
perform
with test after
varying x from 1 by xstep
until x >= function e
if x > function e
move function e to x-value
else
move x to x-value
end-if
compute recip = 1 / x end-compute
move recip to y-value
write outrec end-write
end-perform
Unsupported Communication section clause.
Part of the conditional clauses for readability.
IF A GREATER THAN 10
DISPLAY "A > 10" END-DISPLAY
END-IF
A somewhat disdained keyword that is part of the IF THEN ELSE
control structure.
IF A > 10 THEN
DISPLAY "A GREATER THAN 10" END-DISPLAY
ELSE
DISPLAY "A LESS THAN OR EQUAL TO 10" END-DISPLAY
END-IF
Used in definitions for alphabets in SPECIAL-NAMES and a procedural clause
allowing PERFORM from one label THROUGH (inclusive) to another label and
all paragraphs in between. Also used to specify grouping with RENAMES.
PERFORM 100-open-files THROUGH 100-files-end
An ACCEPT FROM source. Allows access to current clock.
01 current-time.
05 ct-hours pic 99.
05 ct-minutes pic 99.
05 ct-seconds pic 99.
05 ct-hundredths pic 99.
ACCEPT current-time FROM TIME
A counted loop.
PEFORM 5 TIMES
DISPLAY "DERP" END-DISPLAY
END-PERFORM
Multi-purpose destination specifier.
ADD 1 TO cobol GIVING OpenCOBOL
ON SIZE ERROR
DISPLAY "Potential exceeds expectations" END-DISPLAY
END-ADD
Multi-purpose. FUNCTION TRIM allows a TRAILING keyword. An INSPECT
TALLYING subclause.
A SET target. Used in EVALUATE to control when the operation succeeds.
When used with a conditional 88 level name, will set the corresponding
field to a listed VALUE.
01 field-1 pic x.
88 cond-1 values 'a','b','c'.
SET cond-1 TO TRUE
DISPLAY field-1 END-DISPLAY
An unsupported Report Writer report group clause. Also unsupported data
description clause.
Unsupported data description clause that will allow user defined record
layouts.
Currently unsupported Universal Character Set alphabet. UCS-4 would
store international code points in 4 bytes.
SCREEN section field attribute.
A close option, alias for REEL.
CLOSE file-1 UNIT WITH NO REWIND
Unsupported Object COBOL exception object clause.
Manual record unlock and buffer write sync.
UNLOCK filename-1 RECORDS
Usage clause specifing that a value will not include any sign and therefore
can’t be negative.
A powerful string decomposition verb.
UNSTRING Input-Address
DELIMITED BY "," OR "/"
INTO
Street-Address DELIMITER D1 COUNT C1
Apt-Number DELIMITER D2 COUNT C2
City DELIMITER D3 COUNT C3
State DELIMITER D4 COUNT C4
Zip-Code DELIMITER D5 COUNT C5
WITH POINTER ptr-1
ON OVERFLOW
SET more-fields TO TRUE
END-UNSTRING
Sets a loop conditional.
PERFORM VARYING ident-1 FROM 1 BY 1 UNTIL ident-1 > 10
CALL "thing" USING BY VALUE ident-1 END-CALL
END-PERFORM
Index and pointer modification.
SET ptr-1 UP BY 4
SET ind-1 UP BY 1
SCREEN section field attribute.
OpenCOBOL uses standard big-endian internal storage by default. USAGE
clauses influence the data representation. The INTEL architecture uses
little-endian form and OpenCOBOL programmers developing for this common
chipset may need to pay heed to this for performance purposes. As per
the standards, OpenCOBOL supports COMPUTATIONAL-5 native usage.
OpenCOBOL enables use of one to eight byte binary representations in both
big and little endian forms.
Along with full support of all common COBOL PICTURE clauses both storage
and display, OpenCOBOL supports USAGE clauses of:
- BINARY
- COMPUTATIONAL, COMP
- COMP-1
- COMP-2
- COMP-3
- COMP-4
- COMP-5
- COMP-X
- FLOAT-LONG
- FLOAT-SHORT
- DISPLAY
- INDEX
- PACKED-DECIMAL
- POINTER
- PROGRAM-POINTER
- SIGNED-SHORT
- SIGNED-INT
- SIGNED-LONG
- UNSIGNED-SHORT
- UNSIGNED-INT
- UNSIGNED-LONG
- BINARY-CHAR SIGNED
- BINARY-CHAR UNSIGNED
- BINARY-CHAR
- BINARY-SHORT SIGNED
- BINARY-SHORT UNSIGNED
- BINARY-SHORT
- BINARY-LONG SIGNED
- BINARY-LONG UNSIGNED
- BINARY-LONG
- BINARY-DOUBLE SIGNED
- BINARY-DOUBLE UNSIGNED
- BINARY-DOUBLE
- BINARY-C-LONG SIGNED
- BINARY-C-LONG UNSIGNED
- BINARY-C-LONG
Sets up DECLARATIVES paragraphs.
- USE BEFORE DEBUGGING
- USE AFTER EXECEPTION
OBJECT-COMPUTER clause for locale support.
CHARACTER CLASSIFICATION IS USER-DEFAULT
Specifies arguments to CALL and in PROCEDURE declarations.
- BY REFERENCE (default, pointer to modifiable data is passed)
- BY CONTENT (reference to a copy of the data)
- BY VALUE (actual dereferenced value is placed into call frame)
Unsupported internationalization clause.
Unsupported internationalization clause.
Unsupported data validation verb.
Unsupported clause of the VALIDATE statement.
An CALL frame argument modifier. Sets values in data descriptions as well
as values used with 88 level conditional names.
Plural of VALUE when more than one entry is used in an 88 conditional name.
Sets a looping variable.
PERFORM VARYING loop-counter FROM 1 BY 1 UNTIL loop-counter > 10
DISPLAY loop-counter END-DISPLAY
END-PERFORM
A very powerful keyword used in EVALUATE phrases for specifying
conditional expressions.
EVALUATE TRUE
WHEN A = 10
DISPLAY "A = 10" END-DISPLAY
WHEN A = 15
PERFORM A-IS-15
WHEN B IS EQUAL 6
PERFORM B-IS-6
WHEN C IS GREATER THAN 5
DISPLAY "C > 5" END-DISPLAY
WHEN OTHER
DISPLAY "Default imperative" END-DISPLAY
END-EVALUATE
Multi-purpose.
- WITH LOCK
- DISPLAY WITH screen-attribute
- WITH ROLLBACK (pending)
A DATA division section. Unless BASED, all fields are allocated and
fixed in memory (for the running program within a module).
Record write. Unlike READ that uses filenames syntax, WRITE uses
record buffer syntax which must be related to the file through the FD
file descriptor. OpenCOBOL supports LINAGE and WRITE has support
for ‘report’ paging and line control.
WRITE record-buff END-WRITE
WRITE record-name-1 AFTER ADVANCING PAGE END-WRITE.
WRITE record-name-1
AT END-OF-PAGE
DISPLAY "EOP" END-DISPLAY
END-WRITE
Modifies ACCEPT var FROM DAY to use full 4 digit year for the Julian
date retrieval.
ACCEPT date-var FROM DAY YYYYDDD
Modifies ACCEPT var FROM DATE to use full 4 digit year.
ACCEPT date-var FROM DATE YYYYMMDD
Figurative and numeric constant for the value 0.
Alternate spelling for ZEROES.
Yes, many. As of the July 2008 1.1 pre-release
ABS, ACOS, ANNUITY, ASIN, ATAN, BYTE-LENGTH, CHAR, CONCATENATE, COS,
CURRENT-DATE, DATE-OF-INTEGER, DATE-TO-YYYYMMDD, DAY-OF-INTEGER,
DAY-TO-YYYYDDD, E, EXCEPTION-FILE, EXCEPTION-LOCATION, EXCEPTION-STATEMENT,
EXCEPTION-STATUS, EXP, EXP10, FACTORIAL, FRACTION-PART, INTEGER,
INTEGER-OF-DATE, INTEGER-OF-DAY, INTEGER-PART, LENGTH, LOCALE-DATE,
LOCALE-TIME, LOG, LOG10, LOWER-CASE, MAX, MEAN, MEDIAN, MIDRANGE, MIN, MOD,
NUMVAL, NUMVAL-C, ORD, ORD-MAX, ORD-MIN, PI, PRESENT-VALUE, RANDOM, RANGE, REM,
REVERSE, SECONDS-FROM-FORMATTED-TIME, SECONDS-PAST-MIDNIGHT, SIGN, SIN, SQRT,
STANDARD-DEVIATION, STORED-CHAR-LENGTH, SUBSTITUTE, SUBSTITUTE-CASE, SUM, TAN,
TEST-DATE-YYYYMMDD, TEST-DAY-YYYYDDD, TRIM, UPPER-CASE, VARIANCE,
WHEN-COMPILED, YEAR-TO-YYYY
Absolute value of numeric argument
DISPLAY FUNCTION ABS(DIFFERENCE).
The ACOS function returns a numeric value (in radians) that
approximates the arccosine of the argument.
The domain of the arccosine function is -1 to +1. Domain errors
return a result of 0. The inverse cosine function returns a range
of 0 thru π
DISPLAY FUNCTION ACOS(-1).
Compute the ratio of an annuity paid based on arguments of interest
and number of periods.
WORKING-STORAGE SECTION.
77 INTEREST PIC S9V9999 VALUE 0.08.
77 MONTHLY PIC S9V9999 VALUE ZERO.
77 PERIODS PIC 99 VALUE 36.
77 ANNUITY-VALUE PIC S9V9999 VALUE ZERO.
PROCEDURE DIVISION.
COMPUTE MONTHLY ROUNDED = INTEREST / 12
COMPUTE ANNUITY-VALUE ROUNDED =
FUNCTION ANNUITY (MONTHLY PERIODS)
DISPLAY "Monthly rate: " MONTHLY
" Periods: " PERIODS
" Annuity ratio: " ANNUITY-VALUE
END-DISPLAY.
Outputs:
Monthly rate: +0.0067 Periods: 36 Annuity ratio: +0.0314
The ASIN function returns a numeric value (in radians) that
approximates the arcsine of the argument.
The domain of the arcsine function is -1 to +1. Domain errors
return a result of 0. The inverse sine function returns a range
of -π/2 thru π/2
DISPLAY FUNCTION ASIN(-1).
The ATAN function returns a numeric value (in radians) that
approximates the arctangent of the argument.
The domain of the arctangent function is all real numbers.
The inverse tangent function returns a range
of -π/2 thru π/2
DISPLAY FUNCTION ATAN(1).
The BYTE-LENGTH function returns an integer that is the internal
storage length of the given argument.
COBOL >>SOURCE FORMAT IS FIXED
******************************************************************
* Purpose: demonstrate intrinsic FUNCTION BYTE-LENGTH
******************************************************************
identification division.
program-id. bytelength.
data division.
working-storage section.
01 char-var usage binary-char.
01 short-var usage binary-short.
01 long-var usage binary-long.
01 double-var usage binary-double.
01 num1-var pic 9.
01 num4-var pic 99v99.
01 num9-var pic s9(9).
01 num18-var pic s9(18).
01 num18c-var pic s9(18) usage comp.
01 num18p-var pic s9(18) usage comp-3.
01 edit-var pic $zzzz9.99.
01 string-var pic x(10) value "abc".
01 newline pic x value x'0a'.
procedure division.
display
"num1-var len = " function byte-length(num1-var) newline
"num4-var len = " function byte-length(num4-var) newline
"num9-var len = " function byte-length(num9-var) newline
"num18-var len = " function byte-length(num18-var) newline
"num18c-var len = " function byte-length(num18c-var) newline
"num18p-var len = " function byte-length(num18p-var) newline
"edit-var len = " function byte-length(edit-var) newline
"12 len = " function byte-length(12) newline
"12.12 len = " function byte-length(12.12) newline
"1234567890.123 = " function
byte-length(1234567890.123) newline
"string-var len = " function byte-length(string-var) newline
"trim string = " function
byte-length(function trim(string-var)) newline
"char-var len = " function byte-length(char-var) newline
"short-var len = " function byte-length(short-var) newline
"long-var len = " function byte-length(long-var) newline
"double-var len = " function byte-length(double-var)
end-display
goback.
exit program.
Outputs:
num1-var len = 1
num4-var len = 4
num9-var len = 9
num18-var len = 18
num18c-var len = 8
num18p-var len = 10
edit-var len = 9
12 len = 2
12.12 len = 4
1234567890.123 = 13
string-var len = 10
trim string = 00000003
char-var len = 1
short-var len = 2
long-var len = 4
double-var len = 8
The CHAR function returns a ONE character alphanumeric field
whose value is the character in the current collating sequence
having the ordinal position equal to the value of the integer
argument. The argument must be greater than 0 and less than or
equal to the number of positions in the collating sequence.
Errors in the argument range return 0 (the LOW-VALUE by default).
See ASCII or EBCDIC and details of the ALPHABET clause.
DISPLAY FUNCTION CHAR(66).
Would output A in the ASCII character set. Note this may
be different than what some expect. OpenCOBOL CHAR is 1 thru 128
not 0 thru 127 as a C programmer may be used to.
And to add a little confusion, most personal computers use an
extended character set, usually erroneously called ASCII with a
range of 0 to 255. A more appropriate name may be ISO-8859-1
Latin 1. See ASCII for more accurate details. This author
is often guilty of this misnomer of the use of the term ASCII.
Returns a common datetime form from integer date (years and days from 1600 to
10000) and numeric time arguments (seconds in day). Date should be from 1 to
3067671 and time should be from 1 to 86400. The character string returned is in
the form 7.5.
DISPLAY FUNCTION COMBINED-DATETIME(1; 1) END-DISPLAY
Outputs:
Concatenate the given fields. CONCATENATE is an OpenCOBOL extension.
MOVE "COBOL" TO stringvar
MOVE FUNCTION CONCATENATE("Open"; stringvar) TO goodsystem
DISPLAY goodsystem END-DISPLAY
The COS function returns a numeric value that
approximates the cosine of the argument (in radians).
The domain of the cosine function is all real numbers, with
a nominal domain of 0 thru π with a zero returned at π/2.
The cosine function returns a range of -1 thru +1.
DISPLAY FUNCTION COS(1.5707963267949).
Returns an alphanumeric field of length 21 with the current date,
time and timezone information in the form
YYYYMMDDhhmmsscc±tznn
DISPLAY FUNCTION CURRENT-DATE.
Example Output:
Converts an integer date, days on the Gregorian since December 31
1600 to YYYYMMDD form
DISPLAY DATE-OF-INTEGER(1)
DISPLAY DATE-OF-INTEGER(50000)
Outputs:
50,000 days after December 31, 1600 being November 23rd, 1737.
Converts a two digit year date format to four digit year form using
a sliding window pivot of the optional second argument. The pivot
defaults to 50.
The OpenCOBOL implementation of DATE-TO-YYYYMMDD also accepts an
optional third argument, replacing the default century value of
1900 and is treated as the years added to the given year portion of
the first argument and modified by the sliding 100 window pivot.
Domain errors occur for year values less than 1600 and greater than
999,999. There is no validation of the input date.
Because of the sliding window, this function is dependent on the date of
evaluation
DISPLAY FUNCTION DATE-TO-YYYYMMDD(000101)
DISPLAY FUNCTION DATE-TO-YYYYMMDD(500101)
DISPLAY FUNCTION DATE-TO-YYYYMMDD(610101)
DISPLAY FUNCTION DATE-TO-YYYYMMDD(990101)
DISPLAY FUNCTION DATE-TO-YYYYMMDD(990101, 50, 1900)
DISPLAY FUNCTION DATE-TO-YYYYMMDD(990101, -10, 1900)
DISPLAY FUNCTION DATE-TO-YYYYMMDD(990101, 50, 2000)
DISPLAY FUNCTION DATE-TO-YYYYMMDD(990101, 50, 2100)
When run in August, 2008 produces:
20000101
20500101
19610101
19990101
18990101
17990101
19990101
20990101
Converts a Gregorian integer date form to Julian date form (YYYDDD)
based on days since December 31, 1600. Errors return 0
DISPLAY FUNCTION DAY-OF-INTEGER(97336).
1867182
97,336 days after 16001231 being the 182nd day of the year 1867.
Canada’s date of Confederation and recognized birthday.
Converts a Julian 2 digit year and three digit dat integer to a four digit year
form. See FUNCTION DATE-TO-YYYYMMDD for some of the details of the
calculations involved.
Returns Euler’s number as an alphanumeric field to 34 digits of accuracy
after the decimal. E forms the base of the natural logarithms. It has
very unique and important properies such as:
- the derivative of ex is ex
- and the area below the curve of y = 1/x for 1 <= x <= e is exactly 1.
- making it very useful in calculations of Future Value with compound interest.
DISPLAY FUNCTION E END-DISPLAY
outputs:
2.7182818284590452353602874713526625
A small graph to show the magic area.
OCOBOL >>SOURCE FORMAT IS FIXED
*> ***************************************************************
*> Author: Brian Tiffin
*> Date: 29-May-2009, Modified 20110505 to add e tic mark
*> Purpose: Plot Euler's number (using integral of 1 over x)
*> Tectonics: requires access to gnuplot. http://www.gnuplot.info
*> cobc -Wall -x ploteuler.cob
*> OVERWRITES ocgenplot.gp, ocgpdata.txt and images/euler.png
*> ***************************************************************
identification division.
program-id. ploteuler.
environment division.
input-output section.
file-control.
select scriptfile
assign to "ocgenplot.gp"
organization is line sequential.
select outfile
assign to "ocgpdata.txt"
organization is line sequential.
data division.
file section.
fd scriptfile.
01 gnuplot-command pic x(82).
fd outfile.
01 outrec.
03 x-value pic -z9.999.
03 filler pic x.
03 y-value pic -z9.999.
working-storage section.
01 xstep pic 9v99999.
01 x pic 9v99999.
01 recip pic 9v99999.
*> The plot command is xrange 0:3, y 0:2 data col 1 for x 2 for y
01 gpcmds pic x(400) value is
"set style fill solid 1.0; " &
"set grid; " &
"set xtics add ('e' 2.718281); " &
"plot [0:3] [0:2] 'ocgpdata.txt' using 1:2 \ " &
" with filledcurves below x1 title '1/x'; " &
"set terminal png; " &
"set output 'images/euler.png'; " &
"replot ".
01 line-cnt pic 999.
01 gptable.
05 gpcmd pic x(50) occurs 8 times.
01 gplot pic x(40) value is 'gnuplot -persist ocgenplot.gp'.
01 result pic s9(9).
*> ***************************************************************
procedure division.
display function e end-display
*><* Create the script to plot the area of Euler's number
open output scriptfile.
move gpcmds to gptable
perform varying line-cnt from 1 by 1 until line-cnt > 8
move gpcmd(line-cnt) to gnuplot-command
write gnuplot-command end-write
end-perform
close scriptfile
*><* Create the reciprocal data
open output outfile
move spaces to outrec
compute xstep = function e / 100 end-compute
perform
with test after
varying x from 1 by xstep
until x >= function e
if x > function e
move function e to x-value
else
move x to x-value
end-if
compute recip = 1 / x end-compute
move recip to y-value
write outrec end-write
end-perform
close outfile
*><* Invoke gnuplot
call "SYSTEM" using gplot returning result end-call
if result not = 0
display "Problem: " result end-display
stop run returning result
end-if
goback.
end program ploteuler.
The area in red is exactly 1. Well, not on this plot exactly, as it
is somewhat sloppy with the xstep end case and the precisions.
See
Can OpenCOBOL be used for plotting? for some details on plotting.
This special-register holds the error number and name of the source file that
caused an input output exception. See FUNCTION EXCEPTION-STATUS for an
example.
This special-register can be queried for the location of the last
exception. See FUNCTION EXCEPTION-STATUS for example source code.
Note: This feature requires compilation with -fsource-location
compiler switch. This option is also turned on with -g and -debug
debugging info compiles. Information includes PROGRAM-ID, section and
source line.
This special-register holds the statement that was executing when
the latest exception was raised. See FUNCTION EXCEPTION-STATUS
for an example. Note: This feature requires compilation with
-fsource-location compiler switch. This option is also turned on
with -g debugging info compiles.
This FUNCTION returns the current exception status. The example
below is courtesy of Roger While, from a post he made announcing
the FUNCTION EXCEPTION- features.
Source format is free, compile with cobc -x -g -free except.cob
IDENTIFICATION DIVISION.
PROGRAM-ID. MINIPROG.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SOURCE-COMPUTER. LINUX.
OBJECT-COMPUTER. LINUX.
SPECIAL-NAMES.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT PRINTFILE ASSIGN TO "XXRXWXX"
FILE STATUS RXWSTAT.
DATA DIVISION.
FILE SECTION.
FD PRINTFILE.
01 PRINTREC PIC X(132).
WORKING-STORAGE SECTION.
01 RXWSTAT PIC XX.
PROCEDURE DIVISION.
A00-MAIN SECTION.
001-MAIN-PROCEDURE.
OPEN INPUT PRINTFILE.
DISPLAY "File Status: " RXWSTAT.
DISPLAY "EXCEPTION-FILE: " FUNCTION EXCEPTION-FILE.
DISPLAY "Return Length: "
FUNCTION LENGTH (FUNCTION EXCEPTION-FILE).
DISPLAY "EXCEPTION-STATUS: " FUNCTION EXCEPTION-STATUS.
DISPLAY "EXCEPTION-STATEMENT: " FUNCTION EXCEPTION-STATEMENT.
STRING "TOOLONG" DELIMITED SIZE INTO RXWSTAT.
DISPLAY "EXCEPTION-STATUS: " FUNCTION EXCEPTION-STATUS.
DISPLAY "EXCEPTION-STATEMENT: " FUNCTION EXCEPTION-STATEMENT.
DISPLAY "EXCEPTION-LOCATION: " FUNCTION EXCEPTION-LOCATION.
STOP RUN.
Example output:
File Status: 35
EXCEPTION-FILE: 35PRINTFILE
Return Length: 00000011
EXCEPTION-STATUS: EC-I-O-PERMANENT-ERROR
EXCEPTION-STATEMENT: OPEN
EXCEPTION-STATUS: EC-OVERFLOW-STRING
EXCEPTION-STATEMENT: STRING
EXCEPTION-LOCATION: MINIPROG; 001-MAIN-PROCEDURE OF A00-MAIN; 29
Tip
See the source file libcob/exception.def for a list of the plethora of
run-time exceptions supported by OpenCOBOL.
Returns an approximation of Euler’s number (see FUNCTION E) raised to the
power of the numeric argument.
DISPLAY FUNCTION EXP(1) END-DISPLAY
outputs:
Note
Be aware that this approximation seems accurate to “only”
15 decimal places. Diligent programmers need to be aware
of the foibles of floating point mathematics and take these
issues into consideration.
Returns an approximation of the value 10 raised to the power of the numeric
argument.
DISPLAY FUNCTION EXP10(1.0) END-DISPLAY
DISPLAY FUNCTION EXP10(1.2) END-DISPLAY
DISPLAY FUNCTION EXP10(10) END-DISPLAY
Outputs:
10.000000000000000000
15.848931924611132871
10000000000.000000000000000000
Computes the factorial of the integral argument. Valid Range of 0 to 19
with a domain of 1 to 121645100408832000.
OCOBOL*> ***************************************************************
*> Program to find range and domain of FUNCTION FACTORIAL
identification division.
program-id. fact.
data division.
working-storage section.
01 ind pic 999.
01 result pic 9(18).
*> ***************************************************************
procedure division.
perform varying ind from 0 by 1 until ind > 20
add zero to function factorial(ind) giving result
on size error
display "overflow at " ind end-display
end-add
display ind " = " function factorial(ind) end-display
end-perform
goback.
end program fact.
Outputs:
000 = 000000000000000001
001 = 000000000000000001
002 = 000000000000000002
003 = 000000000000000006
004 = 000000000000000024
005 = 000000000000000120
006 = 000000000000000720
007 = 000000000000005040
008 = 000000000000040320
009 = 000000000000362880
010 = 000000000003628800
011 = 000000000039916800
012 = 000000000479001600
013 = 000000006227020800
014 = 000000087178291200
015 = 000001307674368000
016 = 000020922789888000
017 = 000355687428096000
018 = 006402373705728000
019 = 121645100408832000
overflow at 020
020 = 432902008176640000
Kind of the same thing, with some zero out formatting.
OCOBOL*> ***************************************************************
*> Program to find range and domain of FUNCTION FACTORIAL
identification division.
program-id. fact.
data division.
working-storage section.
01 ind pic 99.
01 z-ind pic z9.
01 result pic 9(18).
01 pretty-result pic z(17)9.
*> ***************************************************************
procedure division.
perform varying ind from 0 by 1 until ind > 21
add zero to function factorial(ind) giving result
on size error
display
"overflow at " ind ", result undefined: "
function factorial(ind)
end-display
not on size error
move ind to z-ind
move result to pretty-result
display
"factorial(" z-ind ") = " pretty-result
end-display
end-add
end-perform
goback.
end program fact.
Which outputs:
factorial( 0) = 1
factorial( 1) = 1
factorial( 2) = 2
factorial( 3) = 6
factorial( 4) = 24
factorial( 5) = 120
factorial( 6) = 720
factorial( 7) = 5040
factorial( 8) = 40320
factorial( 9) = 362880
factorial(10) = 3628800
factorial(11) = 39916800
factorial(12) = 479001600
factorial(13) = 6227020800
factorial(14) = 87178291200
factorial(15) = 1307674368000
factorial(16) = 20922789888000
factorial(17) = 355687428096000
factorial(18) = 6402373705728000
factorial(19) = 121645100408832000
overflow at 20, result undefined, 432902008176640000
overflow at 21, result undefined, 197454024290336768
Returns a numeric value that is the fraction part of the argument. Keeping
the sign.
DISPLAY FUNCTION FRACTION-PART(FUNCTION E) END-DISPLAY
DISPLAY FUNCTION FRACTION-PART(-1.5) END-DISPLAY
DISPLAY FUNCTION FRACTION-PART(-1.0) END-DISPLAY
DISPLAY FUNCTION FRACTION-PART(1) END-DISPLAY
Outputs:
+.718281828459045235
-.500000000000000000
+.000000000000000000
+.000000000000000000
Returns the greatest integer less than or equal to the numeric argument.
DISPLAY
FUNCTION INTEGER (-3) SPACE
FUNCTION INTEGER (-3.141)
END-DISPLAY
DISPLAY
FUNCTION INTEGER (3) SPACE
FUNCTION INTEGER (3.141)
END-DISPLAY
DISPLAY
FUNCTION INTEGER (-0.3141) SPACE
FUNCTION INTEGER (0.3141) SPACE
FUNCTION INTEGER (0)
END-DISPLAY
Outputs:
-000000000000000003 -000000000000000004
+000000000000000003 +000000000000000003
-000000000000000001 +000000000000000000 +000000000000000000
Note the -4, greatest integer less than or equal to the argument.
Converts a date in the Gregorian calender to an integer form. Expects a
numeric argument in the form YYYYMMDD based on years greater than or equal to
1601 and less than 10000. Month values range from 1 to 12. Days range from 1
to 31 and should be valud for the specified month and year. Invalid input
returns unpredictable results and sets the exception EC-ARGUMENT-FUNCTION to
exist. See FUNCTION DATE-OF-INTEGER for the converse function.
Converts a Julian date of YYYYDDD to integer date form.
See FUNCTION DAY-OF-INTEGER for the converse intrinsic function.
Invalid arguments return an undefined result and set the
exception EC-ARGUMENT-FUNCTION to exist.
Returns the integer part of the numeric argument. Similar to
FUNCTION INTEGER but returns different values for negative arguments.
DISPLAY
FUNCTION INTEGER-PART (-3) SPACE
FUNCTION INTEGER-PART (-3.141)
END-DISPLAY
DISPLAY
FUNCTION INTEGER-PART (3) SPACE
FUNCTION INTEGER-PART (3.141)
END-DISPLAY
DISPLAY
FUNCTION INTEGER-PART (-0.3141) SPACE
FUNCTION INTEGER-PART (0.3141) SPACE
FUNCTION INTEGER-PART (0)
END-DISPLAY
Outputs:
-000000000000000003 -000000000000000003
+000000000000000003 +000000000000000003
+000000000000000000 +000000000000000000 +000000000000000000
Returns an integer that is the length in character positions of the given
argument.
working storage.
01 nat pic n(10).
01 cha pic x(10).
01 bin constant as h'ff'.
01 num pic s9(8)v9(8).
01 form pic $-z(7)9.9(8).
procedure division.
display
function length(nat) space
function length(cha) space
function length(bin)
end-display
display
function length(num) space
function length(form)
end-display
Outputs:
Returns a culturally appropriate date given an alphanumeric of 8 character
positions in the form “YYYYMMDD” and an optional locale name that has been
associted with a locale in the SPECIAL-NAMES paragraph.
See http://en.wikipedia.org/wiki/Locale for a start at the very detail rich
computational requirements of LOCALE.
Will set EC-ARGUMENT-FUNCTION to exist for invalid input.
OCOBOL >>SOURCE FORMAT IS FIXED
*> ***************************************************************
*> Author: Brian Tiffin
*> Date: 20120116
*> Purpose: Demonstrate locale functions
*> Tectonics: cobc -x locales.cob
*> ***************************************************************
identification division.
program-id. locales.
environment division.
configuration section.
repository.
function all intrinsic.
*> -*********-*********-*********-*********-*********-*********-**
procedure division.
*> Display cultural norm date and times as set in environment.
*> Google LC_ALL.
*> 20120622 represents June 22 2012
*> 141516 represents 2pm (14th hour), 15 minutes, 16 seconds
*> 39600 represents 11 hours in seconds
display locale-date(20120622) end-display
display locale-time(141516) end-display
display locale-time-from-seconds(39600) end-display
goback.
end program locales.
Which produced:
[btiffin@home cobol]$ cobc -x locales.cob
[btiffin@home cobol]$ ./locales
06/22/2012
02:15:16 PM
11:00:00 AM
I live in Canada, but usually run Fedora with LANG=en_US.utf8
and so
[btiffin@home cobol]$ export LANG='en_CA.utf8'
[btiffin@home cobol]$ ./locales
22/06/12
02:15:16 PM
11:00:00 AM
Boo, day month year form. Sad, 2 digit year? What kinda backwater land do I
live in? Time to write strongly worded letters to some committees. :)
I just looked, and it seems Canada is listed as DD/MM/YY; I’m moving to
Germany.
[btiffin@home cobol]$ export LANG=en_DK.utf8
[btiffin@home cobol]$ ./locales
2012-06-22
14:15:16
11:00:00
Joy. year month day. Hmm, what about Hong Kong?
[btiffin@home cobol]$ LANG=en_HK.utf8 ./locales
Sunday, June 22, 2012
02:15:16 EST
11:00:00 EST
Nice.
If you want to run your system through its locales, try
$ locs=( $(locale -a) )
$ for l in ${locs[@]}; do echo $l; LANG=$l ./locales; done
and expect some unicode in the output.
Oh, and along with FUNCTION EXCEPTION-STATUS you can detect invalid
arguments.
000100 >>SOURCE FORMAT IS FIXED
000200*> ***************************************************************
000300*> Author: Brian Tiffin
000400*> Date: 20120116
000500*> Purpose: Demonstrate locale function invalid arguments
000600*> Tectonics: cobc -x -g -debug locales.cob
000700*> ***************************************************************
000800 identification division.
000900 program-id. locales.
001000
001100 environment division.
001200 configuration section.
001300 repository.
001400 function all intrinsic.
001500
001600*> -*********-*********-*********-*********-*********-*********-**
001700 procedure division.
001800
001900*> Display cultural norm date and times as set in environment.
002000*> Google LC_ALL.
002100*> 20120622 represents June 22 2012
002200*> 141516 represents 2pm (14th hour), 15 minutes, 16 seconds
002300*> 39600 represents 11 hours in seconds
002400
002500 display locale-date(20120622) end-display
002600 display locale-time(141516) end-display
002700 display locale-time-from-seconds(39600) end-display
002800
002900*> invalid arguments are detected through EXCEPTION-STATUS
003000 display locale-date(20120699) end-display
003100 DISPLAY "EXCEPTION-STATUS: " EXCEPTION-STATUS
003200 DISPLAY "EXCEPTION-STATEMENT: " EXCEPTION-STATEMENT
003300 DISPLAY "EXCEPTION-LOCATION: " EXCEPTION-LOCATION
003400
003500 display locale-time(941516) end-display
003600 DISPLAY "EXCEPTION-STATUS: " EXCEPTION-STATUS
003700 DISPLAY "EXCEPTION-STATEMENT: " EXCEPTION-STATEMENT
003800 DISPLAY "EXCEPTION-LOCATION: " EXCEPTION-LOCATION
003900
004000 display locale-time-from-seconds(-39600) end-display
004100
004200 goback.
004300 end program locales.
giving:
$ ./locales
06/22/2012
02:15:16 PM
11:00:00 AM
EXCEPTION-STATUS: EC-ARGUMENT-FUNCTION
EXCEPTION-STATEMENT: DISPLAY
EXCEPTION-LOCATION: locales; MAIN PARAGRAPH OF MAIN SECTION; 30
EXCEPTION-STATUS: EC-ARGUMENT-FUNCTION
EXCEPTION-STATEMENT: DISPLAY
EXCEPTION-LOCATION: locales; MAIN PARAGRAPH OF MAIN SECTION; 35
-11:00:00 AM
Returns a culturally appropriate date given an alphanumeric of 6 character
positions in the form “HHMMSS” and an optional locale name that has been
associted with a locale in the SPECIAL-NAMES paragraph. See
http://en.wikipedia.org/wiki/Locale for a start at the very detail rich
computational requirements of LOCALE.
Will set EC-ARGUMENT-FUNCTION to exist for invalid input.
See FUNCTION LOCALE-DATE.
Returns a culturally appropriate date given an alphanumeric number of seconds
and an optional locale name that has been associted with a locale in the
SPECIAL-NAMES paragraph.
See http://en.wikipedia.org/wiki/Locale for a start
at the very detail rich computational requirements of LOCALE.
Will set EC-ARGUMENT-FUNCTION to exist for invalid input.
See FUNCTION LOCALE-DATE.
Returns an approximation of the natural logarithmic value of the
given numeric argument. Uses a base of FUNCTION E.
DISPLAY FUNCTION LOG(100) END-DISPLAY
DISPLAY FUNCTION LOG(FUNCTION E) END-DISPLAY
gives:
4.60517018598809137
000000001
Returns an approximation of the base-10 logarithmic value of
the given numeric argument.
DISPLAY FUNCTION LOG10(100) END-DISPLAY
gives:
Convert any uppercase character values (A-Z) in the argument to
lowercase (a-z).
Returns the maximum value from the list of arguments.
DISPLAY FUNCTION MAX ( "def"; "abc";) END-DISPLAY
DISPLAY FUNCTION MAX ( 123.1; 123.11; 123) END-DISPLAY
Outputs:
Returns the arithmetic mean (average) of the list of numeric arguments.
DISPLAY FUNCTION MEAN(1; 2; 3; 4; 5; 6; 7; 8; 9) END-DISPLAY
Outputs:
Returns the arithmetic mean (average) of the minimum and maximum argument
from the list of numeric arguments.
DISPLAY FUNCTION MIDRANGE(1; 2; 3; 4; 5; 6; 7; 8; 9) END-DISPLAY
Outputs:
Returns the minimum value from the list of arguments.
DISPLAY FUNCTION MIN ( "def"; "abc";) END-DISPLAY
DISPLAY FUNCTION MIN ( 123.1; 123.11; 123) END-DISPLAY
Outputs:
Returns an integer value of that is the
first-argument modulo second-argument.
DISPLAY FUNCTION MOD(123; 23) END-DISPLAY
Outputs:
Returns the numeric value represented by the character string argument.
OCOBOL IDENTIFICATION DIVISION.
PROGRAM-ID. prog.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 X PIC X(12) VALUE " -9876.1234 ".
01 F PIC X(12) VALUE "B-9876.1234 ".
PROCEDURE DIVISION.
DISPLAY FUNCTION NUMVAL ( X )
DISPLAY FUNCTION NUMVAL ( F )
END-DISPLAY.
STOP RUN.
gives:
The “B” in field F, breaks the numeric conversion. NUMVAL is actually
fairly complicated and forgiving of inputs, but will return 0 on invalid
numeric conversions.
OpenCOBOL 2 will also provide FUNCTION TEST-NUMVAL.
Returns the numeric value represented by the culturally appropriate
currency specification argument.
OCOBOL IDENTIFICATION DIVISION.
PROGRAM-ID. prog.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 X PIC X(14) VALUE " % -9876.1234 ".
PROCEDURE DIVISION.
DISPLAY FUNCTION NUMVAL-C ( X , "%" )
END-DISPLAY.
STOP RUN.
gives:
in a LOCALE that uses the percent sign as a currency symbol.
OpenCOBOL 2 will also provide FUNCTION TEST-NUMVAL-C.
Returns the integer value that is the ordinal position of the character
argument in the program’s collating sequence. COBOL uses 1 as the
lowest ordinal for character sequencing.
DISPLAY FUNCTION ORD("J") END-DISPLAY
Outputs (on an ASCII system with no ALPHABET clause):
Note that COBOL uses 1 as the first value for collating.
So ASCII 74 is ORD 75 for “J”.
Returns the integer that is the ordinal position of the maximum value
of the given argument list.
DISPLAY ORD-MAX(9; 8; 7; 6; 5; 4; 3; 2; 1) END-DISPLAY
DISPLAY ORD-MAX('abc'; 'def'; 'ghi') END-DISPLAY
Outputs:
Returns the integer that is the ordinal position of the minimum value
from the argument list.
OCOBOL >>SOURCE FORMAT IS FIXED
*> ***************************************************************
*> Author: Brian Tiffin
*> Date: 20090531
*> Purpose: Demonstration of FUNCTION ORD-MIN and REPOSITORY
*> Tectonics: cobc -x ordmin.cob
*> ***************************************************************
identification division.
program-id. ordmin.
environment division.
configuration section.
repository.
function all intrinsic.
data division.
working-storage section.
01 posmin pic 9(8).
*> ***************************************************************
procedure division.
move ord-min (9; 8; 7; 6; 5; 4; 3; 2; 1; 2; 3; 4; 5) to posmin
display posmin end-display
move ord-min ("abc"; "def"; "000"; "def"; "abc") to posmin
display posmin end-display
goback.
end program ordmin.
Outputs:
Notice how ord-min did not require FUNCTION, as the REPOSITORY entry
allows this to be skipped in the source codes.
Returns an approximation of the ratio of the circumference by the
diameter of a circle. It returns an alphanumeric with 34 digits
after the decimal. Please be aware of the limitations of using
these types of approximated values in computations.
OCOBOL >>SOURCE FORMAT IS FIXED
*> ***************************************************************
*> Author: Brian Tiffin
*> Date: 20101030
*> Purpose: Demonstrate PI
*> Tectonics: cobc -x pi-demo.cob
*> ***************************************************************
identification division.
program-id. pi-demo.
data division.
working-storage section.
01 args pic x(80).
01 diameter pic 999 value 1.
01 show-diameter pic zz9.
01 circumference usage float-long.
01 plural pic xx.
01 plural-length pic 9 value 1.
01 newline pic x value x'0a'.
*> ***************************************************************
procedure division.
accept args from command-line end-accept
if args not equal spaces
move args to diameter
end-if
if diameter not equal 1
move "s " to plural
move 2 to plural-length
else
move " " to plural
move 1 to plural-length
end-if
move diameter to show-diameter
display "FUNCTION PI is " function pi newline end-display
compute circumference = function pi * diameter end-compute
display
"A wheel, " show-diameter " metre" plural(1:plural-length)
"wide will roll, very close to but only approximately, "
newline circumference " metres in ONE full rotation."
newline
end-display
goback.
end program pi-demo.
Outputs:
$ cobc -x pi-demo.cob && ./pi-demo && ./pi-demo 42
FUNCTION PI is 3.1415926535897932384626433832795029
A wheel, 1 metre wide will roll, very close to but only approximately,
3.14159265358979312 metres in ONE full rotation.
FUNCTION PI is 3.1415926535897932384626433832795029
A wheel, 42 metres wide will roll, very close to but only approximately,
131.946891450771318 metres in ONE full rotation.
Returns an approximation of the present value from a discount rate and
list of future period end amounts. It attempts to reflect the future
value of $1.00 given time, inflation and interest.
OCOBOL >>SOURCE FORMAT IS FIXED
*> ***************************************************************
*> Author: Brian Tiffin
*> Date: 20101030
*> Purpose: Demo of PRESENT-VALUE
*> Tectonics: cobc -x present-value-demo.cob
*> ***************************************************************
identification division.
program-id. present-value-demo.
data division.
working-storage section.
01 args pic x(80).
01 newline pic x value x'0a'.
01 rate pic s9v9999 value 0.7000.
01 the-value pic s9(6)v99.
*> ***************************************************************
procedure division.
accept args from command-line end-accept
if args not equal to spaces
move args to rate
end-if
compute the-value rounded =
function present-value(rate; 1000, 1010, 1000, 1100)
end-compute
display
"A discount rate of " rate " gives a PRESENT-VALUE of "
the-value " given" newline
"end-amounts of 1000, 1010, 1000 and 1100"
end-display
compute the-value rounded =
function present-value(rate; 1000, 1000, 1000, 1000)
end-compute
display
"A discount rate of " rate " gives a PRESENT-VALUE of "
the-value " given" newline
"end-amounts of 1000, 1000, 1000 and 1000"
end-display
goback.
end program present-value-demo.
Outputs:
$ ./present-value-demo
A discount rate of +0.7000 gives a PRESENT-VALUE of +001272.96 given
end-amounts of 1000, 1010, 1000 and 1100
A discount rate of +0.7000 gives a PRESENT-VALUE of +001257.53 given
end-amounts of 1000, 1000, 1000 and 1000
$ ./present-value-demo 0.333
A discount rate of +0.3330 gives a PRESENT-VALUE of +002089.18 given
end-amounts of 1000, 1010, 1000 and 1100
A discount rate of +0.3330 gives a PRESENT-VALUE of +002051.88 given
end-amounts of 1000, 1000, 1000 and 1000
$ ./present-value-demo 0.935
A discount rate of +0.9350 gives a PRESENT-VALUE of +001003.03 given
end-amounts of 1000, 1010, 1000 and 1100
A discount rate of +0.9350 gives a PRESENT-VALUE of +000993.23 given
end-amounts of 1000, 1000, 1000 and 1000
For details, talk to a professional.
rant Any COBOL programmer using financial functions for use by others
HAS to attain some level of domain expertise in the mathematics at work,
as well as a level of technical competence to read through and defend both
the COBOL source code and the generated C code that OpenCOBOL emits before
compiling. rant over
Returns a pseudo-random number given a numeric seed value as argument.
DISPLAY FUNCTION RANDOM(1) END-DISPLAY
DISPLAY FUNCTION RANDOM(1) END-DISPLAY
DISPLAY FUNCTION RANDOM() END-DISPLAY
Outputs:
+00000000.1804289383
+00000000.1804289383
+000000000.846930886
Returns the value of the minimum argument subtracted from the maximum
argument from the list of numeric arguments.
DISPLAY FUNCTION RANGE(1; 2; 3; 4; 5; 6; 7; 8; 9) END-DISPLAY
Outputs:
Returns the numeric remainder of the first argument divided by the second.
DISPLAY FUNCTION REM(123; 23) END-DISPLAY
Outputs:
Returns the reverse of the given character string.
DISPLAY FUNCTION REVERSE("abc") END-DISPLAY
Outputs:
Returns the seconds past midnight from the current system time.
Returns +1 for positive, 0 for zero and -1 for a negative numeric argument.
Returns an approximation for the trigonometric sine of the given numeric angle
(expressed in radians) argument. See Can OpenCOBOL be used for plotting? for
a sample graph using gnuplot.
Returns an approximation of the square root of the given numeric argument.
DISPLAY FUNCTION SQRT(-1) END-DISPLAY
CALL "perror" USING NULL END-CALL
DISPLAY FUNCTION SQRT(2) END-DISPLAY
Outputs:
0.000000000000000000
Numerical argument out of domain
1.414213562373095145
Note: CALL “perror” reveals a bug in OpenCOBOL versions packaged before
June 2009 where the stack will evetually underflow due to improper handling
of the void return specification. Versions supporting RETURNING NULL fix
this problem. An actual application that needed to verify the results of
square roots or other numerical function would be better off placing a small
C wrapper to set and get the global errno.
Returns an approximation of the standard deviation from the given list
of numeric arguments.
DISPLAY
FUNCTION STANDARD-DEVIATION(1 2 3 4 5 6 7 8 9 10) SPACE
FUNCTION STANDARD-DEVIATION(1 2 3 4 5 6 7 8 9 100)
END-DISPLAY
2.872281323269014308 28.605069480775604518
Returns the numeric value of the internal storage length of the given
argument in bytes, not counting spaces.
FUNCTION SUBSTITUTE is an OpenCOBOL extension to the suite of intrinsic
functions.
DISPLAY
FUNCTION SUBSTITUTE("this is a test",
"this", "that",
"is a", "was",
"test", "very cool!")
END-DISPLAY
Will display:
having changed this for that, is a for was and test with very cool!
The new intrinsic accepts:
SUBSTITUTE(subject, lit-pat-1, repl-1 [, litl-pat-2, repl-2, ...])
where lit-pat just means the scan is for literals, not that you have to
use literal constants. WORKING-STORAGE identifiers are fine
for any of the subject, the search patterns or the replacements.
As with all intrinsics, you receive a new field and the subject is untouched.
Note
The resulting field can be shorter, the same length or
longer than the subject string.
This is literal character global find and replace, and there are no
wildcards or other pattern expressions. Unlike INSPECT, this function
does not require same length patterns and replacements. Each pattern
replacement pair uses the original subject, not any intermediate in
progress result.
As this is an alphanumeric operation, a reference modification is also
allowed
MOVE FUNCTION SUBSTITUTE(subject, pat, repl)(2:4) TO xvar4
to result in 4 characters starting at the second position after the
substitution.
Similar to SUBSTITUTE, but ignores upper and lower case of subject
when matching patterns.
Returns the numeric value that is the sum of the given list of
numeric arguments.
Returns an approximation for the trigonometric tangent of the given numeric angle
(expressed in radians) argument. Returns ZERO if the argument would cause an
infinity or other size error.
Test for valid date in numeric yyyymmdd form.
Test for valid date in numeric yyyyddd form.
Returns a character string that is the argument trimmed of spaces.
Defaults to trimming both ends, but can be passed LEADING or TRAILING
qualifier arguments.
DISPLAY '"' FUNCTION TRIM(" abc ") '"' END-DISPLAY
DISPLAY '"' FUNCTION TRIM(" abc " LEADING) '"' END-DISPLAY
DISPLAY '"' FUNCTION TRIM(" abc " TRAILING) '"' END-DISPLAY
Outputs:
Returns a copy of the alphanumeric argument with any lower case letters
replaced by upper case letters.
DISPLAY FUNCTION UPPER-CASE("# 123 abc DEF #") END-DISPLAY
Outputs:
Returns the variance of a series of numbers. The variance is defined
as the square of the FUNCTION STANDARD-DEVIATION
DISPLAY FUNCTION VARIANCE(1 2 3 4 5 6 7 8 9 100) END-DISPLAY.
Returns a 21 character alphanumeric field of the form
YYYYMMDDhhmmsscc±zzzz e.g. 2008070505152000-0400
representing when a module or executable is compiled. The
WHEN-COMPILED special register reflects when an object module was
compiled
program-id. whenpart1. procedure division.
display "First part :" FUNCTION WHEN-COMPILED end-display.
program-id. whenpart2. procedure division.
display "Second part:" FUNCTION WHEN-COMPILED end-display.
program-id. whenshow. procedure division.
call "whenpart1" end-call.
call "whenpart2" end-call.
display "Main part :" FUNCTION WHEN-COMPILED end-display.
For a test
$ cobc -c whenpart1.cob && sleep 15 && cobc -c whenpart2.cob &&
> sleep 15 && cobc -x whenshow.cob whenpart1.o whenpart2.o
$ ./whenshow
gives:
First part :2008082721391500-0400
Second part:2008082721393000-0400
Main part :2008082721394500-0400
Converts a two digit year to a sliding window four digit year.
The optional second argument (default 50) is added to the date
at execution time to determine the ending year of a 100 year
interval.