Saturday, November 17, 2012

COBOL: How Do I Use Evaluate?


EVALUATE can be used in place of IF statements, it can often make the program more readable when you have complex nested conditions.

 In it's simplest form the EVALUATE statement goes something like this:


EVALUATE condition
   WHEN value
        imperative-statements
   WHEN value
        imperative statements
...........
END-EVALUATE.


Here's a simple example:

EVALUATE WS-X
   WHEN 1
        ADD 15 TO WS-TOTAL
        PERFORM A-100-REPORT
   WHEN 2
        ADD 16 TO WS-TOTAL
        MOVE 'WS-X IS 2' TO WS-DISPLAY
        PERFORM A-200-REPORT
   WHEN OTHER
        PERFORM X-100-ERROR
END-EVALUATE.


This will check the value of the variable WS-X and execute the statements depending on the value. Note the use of WHEN OTHER this will be executed if WS-X does not match any of the values, so in the example if WS-X is not equal to 1 or 2 then PERFORM X-100-ERROR will be executed.

 Sometimes you will want to have multiple conditions with lots of ANDs and ORs in an EVALUATE statement as you would in an IF statement. To do this with EVALUATE requires a slightly different approach. One way is to use EVALUATE TRUE (or EVALUATE FALSE). for example
 

EVALUATE TRUE
   WHEN WS-X = 1 AND WS-Y = 2
        PERFORM X-100-PROCESS1
   WHEN WS-X =1 AND WS-Y NOT = 2
        PERFORM X-200-PROCESS2
END-EVALUATE.
 


Here, the whole condition on the WHEN statement is checked and if it is TRUE then the associated statement(s) are executed.

 The second way to do this is using EVALUATE ... ALSO.
 

EVALUATE WS-AGE ALSO WS-SEX ALSO WS-WEIGHT
   WHEN 21 ALSO 'M' ALSO 150
        PERFORM A-200-ACCEPT
   WHEN OTHER
        PERFORM A-300-DECLINE
END-EVALUATE.


In this example if WS-AGE is 21 AND WS-SEX is 'M' AND WS-WEIGHT is 150 then PERFORM A-200-ACCEPT is executed, if not then PERFORM A-300-DECLINE is executed.

 You can combine ALSO with the TRUE and FALSE conditions, so you could have EVALUATE TRUE ALSO FALSE for example.
 




No comments:

Post a Comment

Note: Only a member of this blog may post a comment.