Redefines

25 Apr

Redefines is a nifty clause that puts two seemingly different things in the same place at the same time.  I use it most commonly to define a field both as a numeric and a text field.  There are some strict COBOL laws regarding the REDEFINES clause, though, and you must be aware of them:

  •  The redefining level must be the same as the original defining level
  •  The REDEFINES clause must immediately follow the field it is redefining
  •  The REDEFINES clause cannot be used on an item with a VALUE clause.
  •  Size matters.  You can redefine a field to make it smaller, but you cannot redefine      anything to make it bigger.

So here’s how I use it most:

01  PRICE-EACH                  PIC 9(3)V99.
01  PRICE-EACH-TEXT REDEFINES PRICE-EACH    PIC X(5).
01  TEXT-FIELD                  PIC X(10).
01  TEXT-SUB                    PIC 99.
01  TEXT-FIELD2                PIC X(10).
01  TEXT-SUB2                   PIC 99.

So let’s say our price is 10.98.  It will be stored in the field PRICE-EACH as 010.98, with the decimal point being implied. It will be stored in PRICE-EACH-TEXT as 01098.  This is very useful when you need to move a numeric field to a text field. How to do it?

MOVE PRICE-EACH-TEXT (1:3) TO TEXT-FIELD (1:3).
MOVE “.” TO TEXT-FIELD (4:1).
MOVE PRICE-EACH-TEXT (4:2) TO TEXT-FIELD (5:2).

So now the value of TEXT-FIELD is 010.98.   Including that leading zero might not be what we want.   How do we get rid of it? You can try this:

INSPECT TEXT-FIELD REPLACING LEADING ZEROES BY NULL.

That will work in some versions of COBOL, but not all.  How about this:

INSPECT TEXT-FIELD REPLACING LEADING ZEROES BY SPACES.

Hmmmm….   Now we have a leading space rather than a leading zero.  Still not optimal.

Here’s how I would handle this:

Of course, there are many other ways in COBOL that you could accomplish this same task, but COBOL programmers tend to develop one algorithm and use it over and over.   This is my algorithm.

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *