Maps in COBOL

COBOL by Example: Maps

Maps are COBOL’s way of handling associative data, which are sometimes referred to as hashes or dictionaries in other languages.

To define a map in COBOL, you use the table structure. Here’s how to perform various operations on maps in COBOL:

IDENTIFICATION DIVISION.
PROGRAM-ID. MapsExample.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 map.
   03 k1 PIC X(10) VALUE SPACES.
   03 v1 PIC 9(5) VALUE 0.
   03 k2 PIC X(10) VALUE SPACES.
   03 v2 PIC 9(5) VALUE 0.

PROCEDURE DIVISION.
   MOVE "k1" TO k1
   MOVE 7 TO v1
   MOVE "k2" TO k2
   MOVE 13 TO v2

   DISPLAY "map: k1=" k1 " v1=" v1 " k2=" k2 " v2=" v2

   DISPLAY "Value for k1:"
   DISPLAY v1

   DISPLAY "Value for non-existing key k3:"
   DISPLAY 0  *> COBOL returns 0 for missing numeric values

   DISPLAY "Number of key/value pairs:"
   DISPLAY 2  *> Since we have manually added two key/value pairs

   *> Deleting key/value pair k2
   MOVE SPACES TO k2
   MOVE 0 TO v2
   DISPLAY "map after deleting k2: k1=" k1 " v1=" v1

   *> Clearing the entire map
   MOVE SPACES TO k1
   MOVE 0 TO v1
   DISPLAY "map after clearing all: k1=" k1 " v1=" v1

   STOP RUN.

The map appears in the form k:v when printed with DISPLAY in COBOL.

map: k1=k1        v1=7 k2=k2        v2=13
Value for k1: 7
Value for non-existing key k3: 0
Number of key/value pairs: 2
map after deleting k2: k1=k1        v1=7
map after clearing all: k1=  v1=0

Next example: Functions.