Professional Documents
Culture Documents
REXX Programming
For TSO and CMS
Dan O’Dea
December 30, 2004
1
2
Table of Contents
References, Page 90
Appendix A, page 92: examples of REXX code
Appendix B, page 96: answers to questions
Appendix C, Page 106: solutions to exercises
Appendix D: complete list of REXX built-in functions (with
separate page numbers and TOC).
2
3
Introduction
There are two basic types of programming languages: compiled and interpreted. The
first kind, such as COBOL or Assembler, must pass through two steps. The first step
converts text (your source code) into object code, something the machine can understand.
The second step converts the object code into an executable module. Only then can you
see if your program runs.
TSO CLISTs and the original BASIC language are interpreted. An interpreted
language runs the source code directly, one line at a time.
You can do a lot with CLISTs, but they have some annoying quirks. There are also
some things you just can’t do in a CLIST. On the other hand, COBOL works with
machine and data files and doesn’t have “user friendly” interfaces. Assembler, while
extremely powerful, is somewhat obtuse.
3
4
When you complete the course, you will be able to do the following.
Understand how the TSO stack works and how to use it.
4
5
Create complete applications. In some cases the application might be better done
in COBOL or assembler, but in most cases the REXX version is efficient enough
to leave as-is.
5
6
6
7
A CLIST starts in no special way, because it’s just a string of commands. A REXX
exec must start with the word REXX somewhere on the first line. That tells the
command interpreter how to run the commands. Here’s an example of two ways to do
the same thing.
CLIST
PROC 1 DSN
ALLOCATE FILE(A) DA(‘&DSN’)
REXX
/* REXX program */
Arg DSN
“ALLOCATE FILE(A) DA(‘”DSN”’)”
Trivia
7
8
User variables.
Simple punctuation.
REXX can be coded in upper and lower case, your choice. See the second
course on programming style for more on this option.
8
9
REXX’s many powerful built-in functions allow for fewer instructions to create
certain data structures.
You can code compound variables (arrays) and matrixes (like COBOL
“OCCURS” clauses) in REXX.
Questions
9
10
You can allocate a single dataset to hold one REXX exec. That is fine for a one-time
run of the exec. No DD concatenation is needed to run the command, and compression is
never needed. That being said, running a single REXX exec is clumsy. I recommend
creating a PDS.
Some REXX PDS datasets use RECFM=FB, LRECL=80, allocated to the DD name
SYSEXEC. Some data centers choose to connect their REXX datasets to the DD name
SYSPROC. Concatenated datasets must have the same LRECL. If the PDS is to be
connected to SYSPROC, it must be defined as RECFM=VB, LRECL=255, the same as a
CLIST PDS, even if it is named **.EXEC. I recommend the latter use, as datasets
allocated to SYSPROC are accessed before datasets allocated to SYSEXEC.
Let’s create a PDS for your REXX execs and connect it to your session. Once you’ve
done that, running a REXX program is as simple as typing its name on the command line.
Please follow the SYSPROC convention, and define the PDS with RECFM=VB,
LRECL=255.
EXECUTIL SEARCHDD(YES)
10
11
ISPF 3.2
ISPF Library:
Project . .
Group . . .
Type . . . .
11
12
ISPF 3.2
Fill in as shown:
Five tracks are enough for this class. My own current REXX PDS is only two
cylinders.
Ten directory blocks is forty members or so.
RECFM = VB, LRECL = 255.
12
13
Go into ISPF Edit on the file you just created, choose a member name, and edit the
member. Type the three lines of code below.
File Edit Edit_Settings Menu Utilities Compilers Test Help
-------------------------------------------------------------------------------
EDIT ISDODEA.MY.REXX.EXEC(REXXPGM) Columns 00001 00072
Command ===> Scroll ===> CSR
****** ***************************** Top of Data ******************************
000001 /* REXX program */
000002 SAY "Hello world!"
000003 EXIT
****** **************************** Bottom of Data ****************************
Now save the program. Congratulations, you’ve written your first REXX exec!
In your startup CLIST, you should add an allocation line for this file. If you do that,
you can run programs as their member names rather than typing the entire PDS and
member name.
If you’d rather concatenate your library as part of your first TSO command, you can
do so. In your first TSO command, or in READY mode, type the following two
commands, hitting ENTER after each one:
From this point, your REXX PDS is in the search list for commands and programs to
run under TSO. Use SYSPROC as the DD name if you planned for that.
13
14
You may be itching to get programming for real. So, off we go.
REXX does not have line numbers per se. The REXX interpreter keeps track of line
numbers, which may be displayed when an error message occurs. When editing a REXX
exec, your edit profile should be “NUMBER OFF”.
Remember, a REXX exec must have the word REXX somewhere on Line 1. It
doesn’t have to be first, although that is a typical convention.
Comments in REXX begin with a “/*”, and must end with a “*/”. REXX does not
“close” the comment until it finds a “*/”. For example, this is a long comment line:
Line 5 displays
The answer is 3
on the terminal.
14
15
EXIT 10
You can test this with the WHEN TSO command, or as a variable.
Questions
/* REXX */
X = 10
Y = 20
Z = Y - X
Say “The answer is” Z
15
16
Comments are started by “/*” and ended with “*/”. They can go anywhere in the
program. For example, this is a wing comment:
This is a box comment. Note each line is not closed. Only the first and last lines have
slashes; the first slash starts the comment, and the last finishes it.
REXX execs have one statement per line. You can continue a statement on a second
line by ending the first part with a comma:
Say,
“Next?”
You can also have multiple statements on a line by separating each statement with a
semicolon:
You can end a line with a semicolon, but it’s not necessary.
You can mix upper and lower case. When the REXX interpreter gets a line it forces
the commands, variable names, etc. into upper case. For example, the following are all
the same variable:
DataSetName
datasetNAME
DATASETNAME
16
17
17
18
REXX Keywords
Assignments: A = B
A literal is itself. It doesn’t stand for anything. Unassigned variables are considered
literals. For example this program produces two lines of output, shown below.
/* REXX */
Say Curley
Curley = 2
Say Curley
READY
<rexx name>
Curley
2
READY
18
19
REXX Variables
Variables contain information. They stand for another thing. For example, in this
statement
A + B
A and B are variables containing numbers (you can’t add “A” and “B”).
Anything starting with a word REXX does not understand is taken to be a TSO
command and given to TSO.
To send something directly to TSO, put quotes around it and put it first on the line (or
after an IF). For example, these REXX statements do the same thing:
The type of quotes does not matter, as long as the start and end quote characters
match. As a general rule, I use double quotes because fully-qualified dataset names use
single quotes. At times the type of quotes does matter. We’ll cover those instances as we
continue.
REXX Labels
COMPUTE: C = A + B
COMPUTE:
C = A + B
19
20
Questions
Do these use the correct syntax? If not, what’s wrong with them?
2 – Say “Hey”;
Say;
“Man”
3 - Compute; C = Y - A
True or false: the EXIT statement must always be the very last line in the program.
BARK “Hello”
Exercise #1
TIME
SEND ‘Sample REXX ‘ U(*)
Execute the REXX statement below, but use a continuation character and two lines.
20
21
Although literals can be used without quotes, you should use quotes (unless it’s a
number) to avoid confusion.
Single or double quotes are equally good, as long as you use them consistently. For
example, see the results of the following statements.
If you forget quotes, it usually works anyway. REXX checks to see if it’s a variable.
If something has been assigned to it, that’s what you get. If there is nothing assigned to
it, REXX assumes you meant a literal.
“LISTCAT”
Numeric literals may have quotes, unlike COBOL. These are all valid:
A = “1”
B = ‘2’
C = A + B + “3” “C” contains 6.
If there’s an “E” in the number, it’s scientific notation. For example, 2E+4 is 2 times
10 to the fourth power, or 20,000.
Literals can be hex strings. Hex characters must be in quotes, with an “X” after the
last quote. For example,
Say ‘F1F2F3’X
21
22
A Pitfall
Anytime you put an “X” after a string, REXX takes it as a hex string. Look at this
example.
X = 5 + 6
Say “The answer is “X /* Not this, error */
Say “The answer is“ X /* This is correct */
Literal Questions
/* REXX TRY ME */
Say Greeting
What does this program do (I don’t expect you to know)? Try it at a terminal.
Exercise #2
3 + 1 is 4
‘3 + 1 is 4’
O’Brien
22
23
The SAY instruction sends data to the terminal. SAY can do math and display the
answer.
Say 5 - 3
SAY “5 – 3”
SAY “5” – 3
23
24
The Variable
Variables:
Contain information.
24
25
1. 1_time_only
2. ProGraMmer_NamE
3. Last_Name”
4. input-data
5. Say
/* REXX exec */
MESSAGE = MESSAGE
SAY MESSAGE
EXIT
Exercise #3
25
26
Concatenation
To display or connect variables you can just put them next to each other. If they are
separated by any number of spaces, they are connected by a single space. For example:
If you don’t specify spaces in between the values, you get no space between the
results. However, you do get an extra quote.
The double quote appears in the middle because REXX interprets a doubled quote as
meaning a single quote.
You cannot concatenate variables directly. For example this doesn’t work as you think
it might.
Salary = “10000”
Person = “Barney”
Say SalaryPerson
26
27
More on Concatenation
The concatenation operator is two vertical bars: ||. Here are some examples of
concatenation, both with and without the bars:
1.Var1 = “Up”
2.Var2 = “Away”
3.Var3 = “per”
4.Var4 = “son”
5.Say Var1 Var1 “and” Var2
6.Say Var1 Var1“ and ”Var2
7.Say Var1 Var1 “ and ” Var2
8.Say Var2 Var3 Var4
9.Say Var2 Var3||Var4
10. Say Var2 Var1||Var3 Var4
The concatenation operator is needed only when concatenating two variables. There
is no need to use it when concatenating literals with variables.
When this prints, how many spaces are between Elle and Woody?
When this prints, how many spaces are between Elle and Woody?
27
28
Conditional Operators
If expression
Then one instruction
Else one instruction
The REXX verb NOP (No OPeration) tells REXX to do nothing. Here is an example
of a complete IF statement:
If Marital_Status = “MARRIED”
Then NOP
Else Say “Say, I was wondering....”
You must use the symbols. For example, you cannot code
If A greater than B
28
29
If you want more than one instruction after the IF statement, use a DO … END group.
All of the instructions in the DO group are performed one after another. Every DO must
be matched by an END. It’s a good idea to indent so the program is readable. Here are a
couple of examples.
If A = B Then Do
A = B – 1
Say “A was equal to B, but now it’s not.”
End
If A = B
Then Do
Say “A is equal to B.”
Say “B is equal to A.”
End
Else Say “A is not equal to B.”
DO groups are quite flexible, may be nested, and can be run multiple times. We’ll talk
more about DO groups later in the course.
29
30
Inexact Comparisons
1000.0001 is pretty close to 1000. In normal mathematics, the two are not equal.
With the REXX instruction NUMERIC FUZZ, they can be equal. The syntax of the
FUZZ instruction is:
9 significant digits is the default. REXX normally looks at all significant digits.
FUZZ tells REXX to ignore the least significant digit or digits. Here are some examples:
Exercise #4
30
31
Boolean Operators
Boolean operators allow more than one compare on one statement. The standard
operators are:
&& is Exclusive OR, one or the other is true, but not both.
Evaluation of Expressions
Be careful!
A = B = 2
31
32
A Specific Example
Here’s something you wouldn’t do, but it shows how REXX works.
“ABC” = “CDE”
32
33
When you execute a program, you can pass it information on the command line after
the name of the program. Any information on the command line is passed to the
program. REXX picks this information up with the ARG command. Thus, the above
program produces:
Spaces separate arguments. Do not use commas between arguments. When calling
subroutines or functions you would use commas.
Exercise #5
Write an exec to execute the LISTCAT ENTRY(dsn) command. Pass the DSN using
ARG. Make sure it works on your own datasets and datasets not belonging to you.
33
34
Extra variables contain nulls. For example, the variable SCHOOL contains nothing.
Anna Conda at
Extra items are all sent to the last variable. For example, the variable SCHOOL would
contain both the “La” and the “Salle”.
You can choose to drop extra items. By placing a period at the end of the ARG
statement, the extra items are ignored. Using the same arguments, then, the results of this
would be “Anna Conda La”. The “Salle” goes away, never to return.
Anna Conda at La
34
35
Exercise #6
Write an exec to accept three pieces of information and display them in reverse order
of entry. If more than three are entered, display an error message.
Exercise #7
Write an exec to examine information passed to it. Perform the following checks.
35
36
Possible origins are ARG, VAR, PULL, SOURCE, VALUE, and EXTERNAL. The
pairings of origin and location are listed here.
The template is a mask or filter through which data must pass before being distributed
to the variables. The template may be:
All forms of PARSE place the information into variables. They all work the same
way, the only difference being the origin of the data. All the variables in the template are
changed.
36
37
Literals in a Template
All the templates we’ve seen so far were just a list of variables. You can tell REXX
how to distribute information into variables. That gives you more control over how
information is passed to the exec. Consider this:
ONE = HOW;
TWO = ARE;
THREE = “YOU TODAY”
REST = “HOT ISN’T IT?”
Anything before the literal is stored into the leading variable(s). Anything after the
literal goes into the trailing variable(s).
SLSH = “/”
PARSE ARG ONE TWO THREE (SLSH) REST
ONE = THERE;
TWO = ARE;
THREE = “TWO AND 1”
REST = “2 DOZEN EGGS.”
37
38
Question
If you execute the exec with the command shown, what are the results?
/* REXX Runme */
Arg YOUR_NAME ADDRESS “/” JUNK
Say “Your name is” YOUR_NAME
Say “You live at” ADDRESS
Exercise #8
Write an exec to accept two arguments: the day of the week and the weather. If the
day is Friday and the weather is rainy, display “Head for office!”. If the day is Friday and
the weather is not rainy, display “Go Rock Cats!”.
38
39
User interactions happen at the terminal. We already know how to send messages to
the terminal; now it’s time to learn how to get data from the terminal. The REXX verb to
do that is PULL
PULL is short for PARSE UPPER PULL. Information comes from the terminal or
from the TSO stack. For now we’ll just concentrate on the terminal and revisit the TSO
stack later.
Please, do a SAY first. Otherwise the keyboard unlocks and the poor user won’t know
what to do. For example:
Be careful. If there is something in the TSO stack, PULL takes that and you won’t get
what was typed at the terminal. There is a way to get around that, shown below. Don’t
worry; we’ll get more into the stack later. For now just be aware of it.
The PARSE EXTERNAL command gets the line directly from the terminal. That
means you don’t have to worry about what’s in the stack. The syntax is:
As with other PARSE commands, you can use multiple variables. The command line
is parsed by spaces, with extra data in the last variable and extra variables set to null.
39
40
Question
You want the user to enter three, and only three, items of information separated by
spaces. What does your PULL look like?
Exercise #9
Write an exec to ask for three, and only three, words and display them in reversed
order.
Exercise #10
Write a front end exec for the DELETE command. Have it ask, “Are you sure?”. If
the dataset name is “junk.data”, don’t ask.
Exercise #11
Write an exec to compute the percent increase of one number over another. Ask for
the two amounts from the terminal. The formula is:
Imagine your old salary was $34,000 and your new salary is $80,000. You would
calculate your percent increase as:
Exercise #12
Ask for the weather and the day of the week from the terminal. If it’s raining, ask how
many inches are expected.
If it’s Friday and sunny or cloudy, display “Head for the golf course!”
If it’s Saturday and less than .5 inches, display “Fishing pole, please!”
40
41
Interactive Debugger
Before we get further into REXX code, you should know REXX has an interactive
debugger. It must be invoked for each execution, so you have to turn it on every time.
The TSO command EXECUTIL TS turns on interactive debugging, as does the REXX
statement TRACE ?.
During interactive debugging you can interrupt using the PA1 or ATTN keys, and then
use one of the immediate keys:
If you just press ENTER after PA1 or ATTN, the exec continues.
You can trace the execution of your exec. There are many options to trace; these are
described on the next page.
You can code most trace options (including EXECUTIL statements) inside a REXX
exec. You’d probably remove them when the exec has been released to the general
public.
Both the “!” and “?” trace options toggle. In other words, the first time they appear,
that switch is turned on. The second time, it is turned off. For example:
TRACE !
‘DELETE MY.CNTL.PDS’ Does not delete the file
TRACE !
‘DELETE MY.CNTL.PDS’ Deletes the file
You can specify the abbreviation shown above, or the full word (e. g. TRACE
NORMAL).
41
42
Tracing Options
42
43
Using EXECUTIL
“EXECUTIL TS” turns interactive debugging on within the exec. There is no special
reason for doing this in an exec, “TRACE ?” works.
“EXECUTIL TE” turns interactive debugging off within the exec. There is no special
reason for doing this in an exec, “TRACE OFF” works.
Interactive Debugging
During interactive debugging, your exec stops. You can do these things:
Questions
Your program is running, apparently not doing anything, and won’t stop. What do you
type in to see what it’s doing?
You’re in interactive trace, single-stepping through the program, and want to quit.
What do you type in to get the program to complete without further tracing?
43
44
44
45
Error Trapping
REXX allows five types of error trapping routines. There are two types of error trap.
One quits the program, the other continues running from the point of the error. We’ll take
a look at both.
Some errors should halt the program. The program should inform the user of the error
before shutting down.
Error traps are generally set up at the beginning of the program. Conditions occurring
after that are intercepted wherever they happen. Control jumps to the error handling
routine. Usually the routine contains an EXIT. Here is the syntax:
Signal on condition
:
:
condition:
/* handle the condition */
Exit
The other type of error traps are subroutines. Control returns to the instruction
immediately after the one causing the error. You may not return anything. The RESULT
variable is not set. Here is the syntax.
Call on condition
:
:
condition:
/* handle the condition */
Return
You can name the routine if you want to, as in this example.
Call on condition,
NAME routine_name
:
:
routine_name:
/* handle the condition */
Return
45
46
Syntax error: your REXX instruction cannot be interpreted. If you don’t have a
syntax trap, REXX displays the line in error and an error message, then stops.
Error: traps failures of known commands to the environment. That happens when
your TSO, ISPF, or macro command failed. If you have no “FAILURE” trap, ERROR
traps that as well. If you don’t have an error trap, REXX displays the failed command
and continues. Warning: some commands give return codes greater than zero when they
work correctly. Those trigger the ERROR trap.
Failure: the command does not exist (RC = –3). The command’s abend code is
converted to a decimal number in RC. A system abend gives a negative number; a user
abend gives a positive number. To convert to “normal” abend codes, use this command:
Say D2X(ABS(RC))
If you don’t have a FAILURE trap, REXX displays the failed command and continues
with the exec.
PA1/ATTN: capture the user hitting the ATTN or PA1 keys. If you don’t set a HALT
trap, hitting PA1 or ATTN, then typing HI, ends the exec. Don’t prevent the user from
stopping execution!
46
47
Trapping Examples
Signal on Syntax
Call on Error
Signal on Failure
Call on NoValue
Call on Halt
:
:
Syntax:
Say “Syntax error”
Exit
Error:
Say “Command failed”
Return
Failure:
Say “Oops!”
Say “Error code is” D2X(ABS(RC))
Exit
NoValue:
Say “Please define your variables”
Return
Halt:
Say “Want to stop now (Y/N)?”
Pull REPLY
If REPLY = “Y” Then Exit
Return
47
48
Apart from notifying users there has been an error, you can do several things in a
REXX condition trap.
The special REXX variable SIGL contains the line number of the statement sent to
the error trap.
The function ERRORTEXT(RC) gives the message REXX puts out for a syntax error.
The function CONDITION(“D”) displays the string in error with a NOVALUE trap
(i.e. the variable in error).
As you may have guessed, SIGNAL can send to a label, even without an error
condition. This is the equivalent of the GOTO. If you do use SIGNAL as a GOTO, it
should go to an exit point.
48
49
“DELETE NO.SUCH.DATASET”
“WHAT COMMAND IS THIS “
SALARY-INCREASE = 10
Say ERROR_MESSAGE
Exit
ERROR:
Say “Command to TSO did not work on line” SIGL
Say “Command was” SOURCELINE(SIGL)
Return
SYNTAX:
Say “Syntax error on line” SIGL
Say “Instruction was” SOURCELINE(SIGL)
Say “REXX error message:” ERRORTEXT(RC)
Say “Problem is in:” CONDITION(“D”)
Exit
FAILURE:
Say “Command to TSO did not work on line” SIGL
Say “Command was” SOURCELINE(SIGL)
Say “Abend Code was” RC
If RC = -3 Then Say “Command not found.”
Exit
49
50
Questions
How does the NOVALUE trap help enforce good programming practice?
Exercise #13
Write an exec asking for a dataset name. It then issues the TSO command LISTD on
it. Set up an error trap to intercept the command not working.
In the error trap, display the line of the program in error, the string producing the error,
and the error code from TSO. Ask for the dataset name again, re-execute the command,
and exit.
50
51
Logical evaluations of statements are not math. For example, SAY 1 = 2 is the same
as SAY 0.
Operators
+ Add, as in 1 + 1 = 2.
- Subtract, as in 1 - 1 = 0.
* Multiply, as in 2 * 3 = 6.
/ Divide, as in 4 / 2 = 2.
% Integer divide, as in 5 % 2 = 2.
// Remainder, as in 5 // 2 = 1.
A “-” (minus sign) just before a number indicates a negative (e. g. –1).
A “+” (plus sign) just before a number indicates a positive number (e. g. +1).
51
52
Arithmetic Precision
REXX can do math to almost any precision, and very quickly. You can run out of
memory using too great a precision. The default precision is 9 digits. Try the following
on your own machine:
While I’ve never tried a huge number, NUMERIC DIGITS 10000 has worked for me
(it’s kind of fun to see all those sixes).
A while back we talked about FUZZ as a way to approximate values. For example,
NUMERIC FUZZ 1 ignores the least significant digit.
Exercise #14
Write an exec asking for two numbers, and then multiply them. Set an error trap to
intercept any error such as invalid numbers.
Exercise #15
Write an exec asking for an LRECL and a BLKSIZE, then determine if the BLKSIZE
is an even multiple of the LRECL. Tell the user if it is or is not.
52
53
So far, we’ve seen three REXX control structures: the IF statement, the SIGNAL
instruction, and the DO group. The DO group we’ve seen so far is executed once. You
can execute the same DO group over and over based on conditions, much like in an IF
statement. There is also a special form of the DO group called SELECT. We’ll talk
about SELECT first, and then the other DO group types.
The SELECT statement lets you specify a number of conditions, only one of which is
executed, based on a single condition check. SELECT replaces a string of IF … THEN
… GOTO statements.
Select
When expression Then instruction
Otherwise instruction
End
You can have as many WHEN expressions as you need to complete your selection.
Each expression is checked in order. When an expression is found to be true, that
instruction is executed and the program continues after the END. If none of the
expressions are true, the OTHERWISE instruction is executed.
The instruction may be another SELECT, a DO group, or any valid REXX instruction.
Here is a concrete example:
Select
When DAY = 1 Then Say “Sunday”
When DAY = 2 Then Say “Monday”
When DAY = 3 Then Say “Tuesday”
When DAY = 4 Then Say “Wednesday”
When DAY = 5 Then Say “Thursday”
When DAY = 6 Then Say “Friday”
When DAY = 7 Then Say “Saturday”
Otherwise Say “Unknown day of the week.”
End
53
54
Day_Off = “No”
Select
When DAY = 1 Then Say “Sunday”
When DAY = 2 Then Say “Monday”
When DAY = 3 Then Say “Tuesday”
When DAY = 4 Then Say “Wednesday”
When DAY = 5 Then Say “Thursday”
When DAY = 6 Then Do
Say “Friday!”
Day_Off = “YES”
End
When DAY = 7 Then Do
Say “Saturday”
Day_Off = “YES”
End
Otherwise Say “Unknown day of the week.”
End
Exercise #16
Write a metric conversion exec. The exec should accept two arguments: UNIT and
QUANTITY.
UNIT can have one of these possible values: LITER, QUART, MILE, or
KILOMETER.
It returns the equivalent of Quantity in the other measurement system based on this
table.
54
55
Do
instructions
End
This runs the group of instructions once. There are several modifiers you can use with
the DO group to make the group run more than once, or even not at all.
If you want to run the loop a specific number of times, code a number. For example,
this DO group runs 3 times:
Do 3
Say “Hello”
End
A variable can be used instead of a number if you need to change the number of times
the loop is run for each execution.
Do variable_name
Say “And so on...”
End
If you want to run the loop at least once, until some condition is true, use the UNTIL
clause. The UNTIL is checked after the loop has been executed.
If you want to run the loop as long as some condition is true, use the WHILE clause.
The condition is checked before the loop begins, so the loop may not execute even once.
55
56
More DO Loops
You can step through a variable for a DO loop. This is useful for going through a
table:
By default, the loop steps through the variable by 1. To step by another increment, use
a “BY” clause and the increment desired. Here are three examples.
Do I = 1 to 10
Say “Number of times through loop:” I
End
EndLoop = 10; Y = 1
Do Z = 1 to EndLoop By 2
Say “Loop counter is:” Z
Say “Number of times through loop:” Y
Y = Y + 1
End
Say ‘Countdown:’
Do J = 10 to 1 By -1
Say J
End
56
57
You can make a loop run forever. That may sound strange, but there are situations
where you want to do just that. Of course, there has to be a way to duck out neatly;
REXX has one. Here’s an example.
Do Forever
If TIME() > “12:00:00” Then Leave
Say “Is it lunch time yet?”
End
In any loop you may encounter a condition such that, while you don’t want to leave
the loop, you also don’t want to execute the rest of the instructions in it. REXX has a
way to do that. The ITERATE instruction tells REXX to “never mind the rest of the loop,
go back to the top, increment, and continue from there.” Here’s an example for those not
liking the number 13.
Do I = 1 to 15
If I = 13 Then Iterate
Say “I is” I
End
I is 1
I is 2
I is 3
I is 4
I is 5
I is 6
I is 7
I is 8
I is 9
I is 10
I is 11
I is 12
I is 14
I is 15
57
58
Questions
Do I = 1 To 4
Say I
End
Say “Ending value of I is” I
What is the result of running this after 12:00 noon? Run it to find out (but please
don’t do so until 11:59!).
Exercise #17
Write an exec asking the user to enter a series of numbers, never the same one twice in
a row. Limit the list to 10 numbers.
58
59
REXX understands its own keywords. Anything else is passed to the environment.
The environment is a command processor, whether it’s TSO, MVS, ISPF, or the ISPF
Editor. The environment processes commands sent to it by REXX, setting the return
code (RC) based on the results of the command. RC will be one of:
Line of program
|
Does REXX understand it?
| |
| |
Yes No
| |
REXX does it |__Pass to TSO
ISPEXEC
ISREDIT
If you run your exec from READY mode, you can pass commands to TSO.
If you run your exec from within ISPF, you can pass commands to TSO, ISPEXEC,
ISPF, and the ISPF Dialog Manager.
If you run your exec from within the ISPF Editor, you can pass commands to TSO,
ISPEXEC, ISPF, ISREDIT, and the ISPF Dialog Manager.
Putting quotes around the command tells REXX not to try to understand it.
A = B /* understood */
“A = B” /* not understood */
YELP “Bark” /* not understood */
YELP = “Bark” /* understood */
59
60
Questions
“DELETE ABC.DATA”
60
61
REXX tries to figure out what kind of command the statement is. It then determines
who should execute the statement. All unknown commands are passed to the
environment. Using quotes tells REXX to send the statement directly to the environment.
That is a good question. In READY mode there is only one environment: TSO.
When the exec is running in ISPF there are several environments to choose from. If you
don’t specify the environment, the command is sent to TSO. The question is, how do you
specify the environment for the command?
The ADDRESS keyword tells REXX what environment the command should be sent
to. ADDRESS has two, similar formats.
That might be a little confusing, so there are two examples on the next page.
61
62
Change the environment until it’s changed back, affecting many commands:
ADDRESS ISPEXEC
“DISPLAY PANEL(MEDMENU)” /* Sent to ISPF */
“VPUT (DOG CAT) SHARED” /* Sent to ISPF */
ADDRESS TSO
“DELETE ABC.DATA” /* Sent to TSO */
You cannot address ISPF from READY mode because the ISPF environment isn’t
available. In REXX you can find out whether an environment is available using the
SUBCOM command. A return code of 0 means that environment is available.
“SUBCOM ISPEXEC”
If RC = 0
Then NOP /* In ISPF, so continue */
Else Do /* Try again, using ISPF */
“ISPSTART COMMAND(this command)”
Exit
End
Note the EXIT in the ELSE loop. This is needed because otherwise the exec will
continue to execute. Another way to tell if ISPF is active is this code.
62
63
Coding edit macros is a separate topic in itself. This topic covers the differences in
writing REXX versus CLIST edit macros.
If you have parameters to pass to the macro, they follow the MACRO keyword and
are enclosed in parentheses, separated by commas if necessary. For example, with two
arguments:
To pass commands to the editor, use the environment ISREDIT. Below is a very
simple edit macro to convert all lower case characters to upper case:
Question
Exercise #18
Write an ISPF edit macro to save and execute the exec you’re currently working on. It
must start with the usual comment, and then have ADDRESS ISREDIT MACRO (see
above). The commands to pass to the ISPF editor are:
(CURMBR) = MEMBER
SAVE
63
64
64
65
REXX has a large library of built-in functions. They simplify programming, acting
arithmetically on data and manipulating strings. The result of the function is substituted
for the function call. For example,
Say REVERSE(“ABCD”)
displays “DCBA”.
A function may be called like a subroutine. When done in this way, the result of the
function is placed in a special variable called RESULT. For example,
displays “DCBA”.
Say TIME()
A complete list of functions can be found in the attachment to this class, and in Book
Manager and other IBM documentation.
A Pitfall
If you leave a space between the function name and its data items you don’t get the
function, you get concatenation.
Length ABCDEF
65
66
We’ve seen a few functions already, such as TIME() and PROMPT(). All functions
must have the parentheses even when nothing is in them. Here are a few useful ones:
66
67
67
68
DATATYPE(string[,type]):
If type is specified, DATATYPE returns a “1” if the string is that type or “0” if it does
not match the type.
A – alphabetic
B – bits
L – lower case
M – mixed case
N – number
S – symbol (valid symbol, e. g. $, @)
U – upper case
W – whole number
X – hexadecimal number
DATE([option]):
If option is omitted the format of the date is DD MMM YYYY. Valid types are:
68
69
To list dataset information like LRECL or RECFM, use the REXX function LISTDSI.
LISTDSI sets system variables from data returned to it by the system. It also sets a return
code based on whether the file was there or if the system information is usable. For a
complete list of codes see Appendix D.
CODE = LISTDSI(“’ENDN1.A06TIC08.SPROCLIB’”)
CODE = LISTDSI(“MY.COBOL.PDS”)
A CODE of “0” means the dataset exists. A CODE of 4 means the directory
information of a PDS is invalid. A 16 is returned if no information is available (e. g. file
not found).
LISTDSI may also be used with a DD name by providing the parameter “FILE”.
Questions
True or false: there must be a space after the name of the function and before the
parenthesis when you use the function.
When you call a built-in function with CALL, where is the answer given?
Exercise #19
Write an exec to accept two numbers from the terminal. Verify they are valid
numbers. Subtract one from the other, drop the sign, and display the answer.
Exercise #20
Write an exec see if a dataset called WORKSHOP.TEMP exists. If so, delete it. If
not, allocate a new one like your EXEC library. The TSO command is:
69
70
70
71
A function and a subroutine are essentially the same. The difference is in how they
are invoked. Functions are used in place; subroutines are CALLed and put the result into
the RESULT variable.
The benefit is the ability to use the function internally or externally with minor
change. It also makes the program more modular. That in turn makes the program easier
to debug.
A function/subroutine can be either internal (within the same program) or external (in
a separate file). Internal and external functions are called the same way.
REXX looks for internal functions first. If you use quotes, REXX looks externally.
For example:
Say “MYSUBR”(123)
71
72
Note the use of commas in the example below and those on the next page.
72
73
73
74
Questions
True or false: if the code is used as a function, you execute it this way:
function_name(data).
True or false: if the code is used as a subroutine, you execute it this way: Call
function_name data and the answer comes back in RESULT.
Exercise #21
74
75
Generally, it’s cleaner to call a user-written function as you would any standard
function. If you do code it as a call, you must quote the function name, and pass the
parameters outside of the parenthesis. For example:
/* REXX */
DSN1 = “SR1.CNTL”; DSN2 = “’@TSSQ04.SR1.EXEC’”
75
76
This is a simplified version of how REXX and TSO search for functions and
subroutines.
A final note: typically SYSEXEC is searched before SYSPROC. This is not always
true, it is installation-dependent.
As you can call a function / subroutine, you can call a separate CLIST or REXX from
within an exec. REXX programs pick up data from their ARGs; CLISTs pick up data
from their PROCs. Any program can directly return only one thing back to the caller: a
return code. The caller picks up this return in the variable RC. Variables are not shared
with the caller, and you cannot pick up CLIST GLOBAL arguments. CLISTs or REXX
execs are called in one of two ways:
“%exec_name arguments”
76
77
Exercises
You must try Exercises #22 and #25. If you choose, you may do only one of either
Exercise #23 or #24.
Exercise #22
Redo the percent increase exec from Exercise #11 as an external subroutine. Name it
PERCENT. Have it accept two parameters, the old number and the new number. Have it
return the percent increase on the RETURN statement. Make sure both args are numeric.
If either one or both are not valid, display a message and return a “0”.
Exercise #23
Using your solution to #21, write your concatenate subroutine as an external function /
subroutine (leave the internal one where it is). Call the external function / subroutine in
such a way as to make sure you invoke the external one and not the internal one. Prove
you made the right call.
Exercise #24
Create a metric conversion external subroutine called METRIC (see Exercise #16).
Also write a main exec calling this function.
Exercise #25
Create an external subroutine called SQRT to compute the square root of a number
passed to it. It accepts one number only. Validate the data item for being a number. If it
is negative, or not numeric, display an appropriate message and return a “0”. Set a loop
limit of 50 (close is good enough for the cigar).
77
78
A compound variable is also called a stem variable, and consists of the following.
Here’s an example:
WEEKDAY.1 = “Sunday”
WEEKDAY.2 = “Monday”
:
WEEKDAY.7 = “Saturday”
These look a lot like WEEKDAY_1, WEEKDAY_2, and so on. The importance of the
period, and these being stem variables, is simply this: you can substitute a variable for
the number:
A = 1
WEEKDAY.A = “Sunday”
Say WEEKDAY.1 /* produces Sunday */
Say WEEKDAY.A /* produces Sunday */
You can easily vary the variable with a DO group, and step through a long list of data:
78
79
RPTDATE = Date("U")
/*-- Loop through the DSN list. If a report
does not exist, create a new one. */
Do I = FirstDSN To SPCRPT.0
VSAMDSN = Word(SPCRPT.I,1)
OUTDSN = "'DBIG."VSAMDSN".SPCHIST'"
::
"ALLOC DA("OUTDSN") F(INFILE) SHR REUSE"
"EXECIO * DISKR INFILE (STEM SPCOUT. FINIS"
If SPCOUT.0 > 57 Then SPCOUT.0 = 57
End
79
80
Changing the stem changes every element in the array. Then, if you change a single
element, all other elements are equal to the stem… even elements that haven’t been
created yet!
If you set the default in this way, the *.0 variable also has the default value. To use
*.0 to tell you the number of valid variables, you must reset it on your own.
Exercise #26
Write an exec with a loop setting NUMBER.1 through NUMBER.10 to the numbers
101 through 110. Then loop through the array, displaying the contents of NUMBER.1
through NUMBER.11, to see what happens.
80
81
TSO Interactions
TSO displays messages from most of its commands. To suppress messages use this
statement.
DUMMY = MSG(“OFF”)
You can trap most (but not all) of these messages. They are not displayed, but are still
accessible if your REXX wants to use them. To trap displayed TSO messages, use the
OUTTRAP function.
DUMMY = OUTTRAP(“LINE.”,”*”)
You can use any variable instead of LINE. Because this variable is a stem variable,
you must include the period.
The “*” says to capture all lines. This is the default. For the “*” you can substitute a
number to capture that many lines.
DUMMY = OUTTRAP(“LINE.”,100)
and so on. To suppress messages and not capture them either, this statement works.
DUMMY = OUTTRAP(“LINE.”,0)
DUMMY = OUTTRAP(“OFF”)
81
82
DUMMY = OUTTRAP(“LINE.”)
“LISTC”
Say “This many lines were trapped:” LINE.0
Do I = 1 to LINE.0
Say “Line of output was:” LINE.I
End
DUMMY = OUTTRAP(“OFF”)
This example runs the CRJ command against all members of a PDS. The function
STRIP removes spaces from around the member names.
Exercise #27
Write an exec to capture the display from TSO commands. Display the lines of output
one at a time.
82
83
The TSO stack is a buffer-like storage area managed by TSO. It holds data keyed at
the keyboard in the terminal stack, and data sent to or from programs in the program
stack. The entire stack is shared by subroutines and other called programs.
Each stack is temporary, owned by the running program, and deleted when the
program ends. Certain TSO commands use the stack. You can put information into the
stack for later use or for use by another program running concurrently.
PULL;
EXECIO write;
PARSE EXTERNAL;
TSO commands with PROMPTs.
The TSO stack is in two parts: the console stack (terminal input buffer) and the
program stack containing program data. The data moves from the end of the stack to the
beginning, in the direction shown below:
Data moves one line at a time. Each line in the stack is either one line entered at the
terminal or one REXX instruction being executed. A line may be null, have one word, or
several.
83
84
Terminal input enters the stack at the end (at left in the diagram). FIFO commands
(e.g. QUEUE, EXECIO READ) put data into the stack at the end of the program stack:
/\FIFO /\LIFO
commands commands
here here
LIFO commands (e.g. PUSH, EXECIO WRITE) put commands at the start of the
program stack.
The QUEUED() function tells you how many lines are in the stack.
Data is taken from the very start of the stack by PULL, EXECIO WRITE, and several
others.
If the program stack is empty, data comes from the terminal input buffer.
PARSE EXTERNAL takes data from the beginning of the terminal input buffer.
Because that is before the program buffer starts, you can use the command to avoid
getting things from the program buffer.
If the terminal input buffer is empty, the keyboard unlocks and TSO waits for you to
type something.
When your program ends, and all programs executing have ended, control goes back
to TSO (or to the editor if the command was a macro). Anything left over in the stack is
taken as a command by TSO.
84
85
Questions
There is nothing in either stack. Your program says PULL. What happens?
NEWSTACK creates a new program stack. You should leave the stack in the
condition it was just before your program needed it. That is essential when your program
calls or is called by another program also using the stack. Issue NEWSTACK at the
beginning of any exec using the stack.
When you use NEWSTACK, be sure to use DELSTACK when you’re done.
Otherwise the new stack remains after the exec ends (although the stack will be emptied
when your exec ends). Remember, if anything is left over in the stack TSO tries to run it.
This does not affect the terminal input buffer (console stack), which should be empty
if you are using the program stack.
“NEWSTACK”
Queue “ABC.DATA”
“DELETE”
“DELSTACK”
85
86
There is always at least one stack, plus any you’ve created with NEWSTACK. REXX
has a function to tell you how many stacks there are. To determine how many you
created, subtract 1 from the total number of stacks. To delete all your new stacks:
Pull STACK_ELEMENT
Say STACK_ELEMENT /* displays Second Record */
Pull STACK_ELEMENT
Say STACK_ELEMENT /* displays First Record */
86
87
Notes:
The variables UID, NewDSN, OldDSN, and KSDS were defined and set before
this set of code.
The SUBMIT command takes everything from the first QUEUE command
through the queued ZZ.
The “If KSDS” statement is explained below with the IF command details.
87
88
Here is an example of both passing data and NOT passing data to a program.
“NEWSTACK”
%otherpgm /* Accepts two lines of input from
user at terminal and displays them */
“DELSTACK”
%otherpgm /* Displays Received Rocky and
Received Bullwinkle */
- - - - - - - - - - - - - - - - - - - - -
/* REXX OTHERPGM */
Pull data_line
Say “Received” data_line
Pull data_line
Say “Received” data_line
88
89
TSO Prompting
TSO prompting uses the same stack as PUSH, PULL, and QUEUE. Prompting in
TSO defaults to ON. Prompting in an Exec defaults to OFF. You can turn prompting on
if your TSO profile allows it (PROFILE PROMPT).
“PROFILE PROMPT”
SAVE_PROMPT = PROMPT(‘ON’)
DUMMY = PROMPT(SAVE_PROMPT)
Say PROMPT()
Question
Exercise #28
Write a REXX to accept a dataset name from the terminal. Verify the DSN is less than
45 bytes long. Verify it exists. Place the DSN into the stack so the LISTD command can
get at it. Suggestion: use QUEUE.
Turn on prompting. Execute the LISTD command but omit the dataset name so TSO
prompts for it. Since the DSN is in the stack, LISTD should get it from there.
89
90
EXECIO is a function of TSO, not REXX. Use EXECIO to read from or write to
QSAM files. You can read a single record, read the entire file at once into a stem
variable, or use the program stack.
RC holds the return code from EXECIO. RC can have the following values:
0 - successful action
1 – truncated data written
2 – if end of file
20 – a severe error was encountered
You should always close a file when finished. The FREE command does not close the
file. Use the FINIS option of the EXECIO command to close files.
Since EXECIO is a TSO function, the entire command needs to be in quotes, options
and all. You must allocate the file first, whether NEW or MOD (if writing) or SHR (if
reading). The format of the command is:
operation:
o DISKR: read
o DISKW: write
o DISKRU: read for update
Seq: sequence number (record number (not used on
a write)). You can’t go backwards.
(options:
o none: use the stack
o STEM: use an array
o FINIS: close the file
The file can be read from or written to a record at a time or all at once.
90
91
The “*” tells EXECIO to retrieve all records. The “(FINIS” tells EXECIO to close the
file when the last record has been read.
The stack is used to hold the one record retrieved by the EXECIO call.
The RANDOM function generates a random number between the two named limits,
inclusive.
The “PARSE PULL” instruction gets the one record from storage.
91
92
Writing to a File
You can write to a file allocated as SHR, OLD, NEW, or MOD, but using SHR is not a
good idea. Use MOD if you want to keep the data already in the file.
When reading a file, we used an “*” to indicate all records. When writing to a file,
EXECIO has no idea when you’ve run out of records; only you do. Therefore you
always have to specify how many records to write. You can do this with a number, as we
did in previous examples, or with a variable. When you do so you cannot enclose the
variable within the quotes:
Don’t forget to FREE your files when you’re done with them. It’s standard REXX
TSO syntax.
“FREE F(dd1)”
92
93
Updating a File
Let’s update a record (say, record 10) in a file. Note this uses the TSO stack; we’ll
revisit this example when we talk about the stack in the advanced course.
Exercise #29
Choose a file you currently have available. Read it into an array, and then display
every other line starting with Line 1.
Exercise #30
Choose a file you currently have available. Read it into an array one record at a time.
Count each line as you read. Keep track of the longest record length. At the end of the
program, display the record count and the length of the longest record.
Exercise #31
Modify the OUTTRAP discussion example above to store the captured lines in the
dataset TEMP.CAPTURE.DATA.
93
94
References
Here is a list of references I’ve found helpful. Most are on the Web.
Mike Cowlishaw, the creator of REXX, wrote a book titled The REXX language:
ISBN 0-13-780735-X Prentice-Hall, 1985
ISBN 0-13-780651-5 2nd edition, 1990
Mark Zelden’s home page. Mr. Zelden has created a large number of useful REXX
commands. The ones posted on this site are available for download.
http://home.flash.net/%7Emzelden/mvsutil.html
Doug Nadel’s home page. Mr. Nadel has been an ISPF developer at IBM for more than
fifteen years. This site has several useful utilities, although not all of them are written in
REXX. http://www.sillysot.com/mvs/
Lionel B. Dyck’s home page. Mr. Dyck has been a systems’ programmer since 1972.
This page has a few really useful things. http://www.lbdsoftware.com/
Two pages from Neil Hancock. Mr. Hancock has been a programmer for many years,
formerly for Met Office, and recently for Macro4, in the UK. The first page is a set of
FAQs on REXX; the second is a REXX style guide.
http://www.uberfish.freeserve.co.uk/Computers/rexxfaq.html.
http://www.uberfish.freeserve.co.uk/Computers/RexxStyleGuide.html.
94
95
95
96
Accept a DSN from the user. Check if it’s fully qualified (has quotes) and remove the
quotes. Assume the DSN belongs to the user if no quotes are found. The end result is a
fully-qualified name with no quotes.
USERID = Sysvar(SYSUID)
If Left(dsn,1) = "'"
Then dsn = Strip(dsn,,"'") /* fully qualified */
Else dsn = USERID"."dsn /* NOT fully qualified */
Return dsn
Accept a DSN from the user. Create a second dataset from the first, except change the
third qualifier to today’s date. The variable assumed here is INDSN.
Parse Upper Var INDSN SDQ1 "." SDQ2 "." SDQ3 "." SDQ4
UQ3 = “J”DATE(“J”)
OUTDSN = SDQ1”.”SDQ2"."UQ3”.”SDQ4
Arg GDGBASE
If Left(GDGBASE,1) = "'" Then Strip(GDGBASE,,"'")
foo = OutTrap(CMDDATA.)
"LISTC ENT('"GDGBASE"') ALL GDG"
foo = OutTrap(Off)
LINE = CMDDATA.0
CURGEN = CMDDATA.LINE
OFFSET = Pos("--",CURGEN) + 2
CURGEN = Strip(Substr(CURGEN,OFFSET,45))
If SYSDSN("'"CURGEN"'") <> OK Then CURGEN = "BAD"
Return CURGEN
96
97
x = outtrap(RI.,'*')
"LD DA('"RACFDS"') GENERIC ALL"
If Word(RI.1,1) = "ICH35003I" Then Do /* No profile */
ZEDSMSG = "NO PROFILE FOUND"
ZEDLMSG = "Dataset" RACFDS "is not protected by RACF."
Address ISPEXEC "SETMSG MSG(ISRZ001)"
Exit
End
Do I = 1 To RI.0
Parse Var RI.1 . . . PROFILE
Parse Var RI.5 . . UACC .
Parse Var RI.17 MYACC .
End
If RI.0 = 1 Then Do
MYACC = "NONE"
UACC = "????"
PROFILE = "????"
End
MYACC = "My access ===>" MYACC
UACC = "Universal access ===>" UACC
PROFILE = "RACF profile name ===>" PROFILE
97
98
98
99
99
100
What two significant language features does REXX not have? Data Typing and
File I/O
How does file I/O happen in a REXX exec? The TSO function EXECIO
What does a REXX program always start with? A comment line with the word
REXX in it.
100
101
101
102
2 – Say “Hey”;
Say;
“Man”
This is incorrect. The semicolon after the second “Say” must be a comma.
If this is run, the result is “HEY” on one line, a blank line, then either the
TSO command “MAN” runs (if it exists) or an error message is displayed.
3 - Compute; C = Y - A
This is incorrect. The semicolon must be a colon.
True or false: you can “go to” a label. True. SIGNAL is the REXX equivalent
of GOTO.
True or false: the EXIT statement must always be the very last line in the program.
False. The EXIT statement is optional if it is the last line.
BARK “Hello”
102
103
/* REXX Try Me */
Say Greeting
What does this program do (I don’t expect you to know)? Try it!
Displays “Go Away!” on the terminal, and then displays “GREETING” on the
terminal. The DROP command removes the named entry from the variable
table, so it’s as if GREETING had never been assigned before.
103
104
/* REXX */
MESSAGE = MESSAGE
Say MESSAGE
EXIT
Displays “MESSAGE” on the terminal.
When this prints, will there be a space between Elle and Woody? No.
When this prints, how many spaces will be between Elle and Woody? One.
104
105
If you execute the exec with the command shown, what are the results?
/* REXX Runme */
Arg YOUR_NAME ADDRESS “/” JUNK
Say “Your name is” YOUR_NAME
Say “You live at” ADDRESS
You want the user to enter three, and only three, items of information separated by
spaces. What does your PULL look like?
Pull V1 V2 V3 .
105
106
Your program is running, apparently not doing anything, and won’t stop. What do you
type in to see what it’s doing? First, hit ATTN or PA1. Then, type TS to enter
interactive debug and hit ENTER.
You’re in interactive trace, single-stepping through the program, and want to quit.
What do you type in to get the program to complete without further tracing? Type one
of TRACE ?N, TRACE O, or SET EXECTRACE OFF.
Can you regain control of a runaway program by typing “EXECUTIL TS”? Only if
you hit ATTN or PA1 first.
Should you leave error traps in execs going into production? Yes.
Does the NOVALUE trap help enforce good programming practice? Yes, to catch
undefined variable usage versus literals.
106
107
Do I = 1 To 4
Say I
End
Say “Ending value of I is” I
What is the result of running this after 12:00 noon? Run it to find out.
Nothing happens. Since the time is greater than noon, the loop is not
entered.
107
108
Can you talk to ISPF from any EXEC? Yes, if a valid ISPF environment is
active.
108
109
True or false: there must be a space after the name of the function and before the
parenthesis when you use the function. False.
When you call a built-in function with CALL, where is the answer given? In the
special variable RESULT.
True or false: if the code is used as a function, you execute it this way:
function_name(data). True.
True or false: if the code is used as a subroutine, you execute it this way: Call
function_name data and the answer comes back in RESULT. True.
109
110
What will this line of a program do: SAY QUEUED() Display how many lines
are in the program stack.
There is nothing in either stack. Your program says PULL. What happens?
Keyboard unlocks, waiting for your input.
Your exec does 10 PUSHes, and 9 PULLs. What happens? The last line in the
stack waits for another PULL, write, or TSO command looking for input. If
the exec ends before that happens, the last line in the stack is passed to
TSO to be executed.
Your exec does 9 PUSHes, and 10 PULLs. What happens? Keyboard unlocks,
waiting for your input.
When and why should you use NEWSTACK? Use NEWSTACK when you want
to preserve stack contents, or as good practice when you interact with the
user via PULL. You must do this if there is a risk of a left-over command or
line of data from a previous command using the stack.
110
111
111
112
Exercise 1, page 19
TIME
SEND ‘Sample REXX ‘ U(*)
Execute the REXX statement below, but use a continuation character and two lines:
112
113
Exercise 2, page 21
3 + 1 is 4
‘3 + 1 is 4’
O’Brien
/* REXX # 2 */
Say "3 + 1 is 4"
Say "'3 + 1 is 4'”
Say "O'Brien”
Exercise 3, page 24
/* REXX */
A = 10
B = 20
Say "A + B is" A + B
113
114
Exercise 4, page 29
Exercise 5, page 32
Write an exec to execute the LISTCAT ENTRY(dsn) command. Pass the DSN using
ARG. Make sure it works on your own datasets and datasets not belonging to you.
/* REXX */
Arg DSN
"LISTC ENT("DSN")"
114
115
Exercise 6, page 34
Write an exec to accept three pieces of information and display them in reverse order
of entry. If more than three are entered, display an error message.
Exercise 7, Page 34
Write an exec to examine information passed to it. Perform the following checks:
/* REXX Agenda */
Arg NAME1 NAME2
If NAME1||NAME2 = "ALRUSH",
| NAME1||NAME2 = "RUSHAL"
Then Say "Look out!"
Else Do
If NAME1 = "AL" | NAME2 = "AL"
Then Say "Must be a liberal."
If NAME1 = "RUSH" | NAME2 = "RUSH"
Then Say "Must be a conservative."
If NAME1 <> "RUSH" & NAME2 <> "RUSH",
& NAME1 <> "AL" & NAME2 <> "AL"
Then Say "Oh, a moderate."
End
115
116
Exercise 8, Page 37
Write an exec to accept two args: the day of the week and the weather. If the day is
Friday and the weather is rainy display “Head for office!”. If the day is Friday and the
weather is not rainy display “Head for golf course!”.
Exercise 9, Page 39
Write an exec to ask for three, and only three, words, and display them in reversed
order.
Write a front end exec for the DELETE command. Have it ask, “Are you sure?”. If
the dataset name is “junk.data” don’t ask.
116
117
Write an exec to compute the percent increase of one number over another. Ask for
the two amounts from the terminal. The formula is:
Ask for the weather and the day of the week from the terminal. If it’s raining, ask how
many inches are expected.
If it’s Friday and sunny or cloudy, display “Head for the golf course!”
If it’s Saturday and less than .5 inches, display “Fishing pole, please!”
117
118
Write an exec asking for a dataset name. It then issues the TSO command LISTD.
Set up an error trap to intercept the command not working.
In the error trap display the line of the program in error, the string producing the error,
and the error code from TSO. Ask for the dataset name again, re-execute the command,
and exit.
ERROR:
Say "Command to TSO did not work on line" SIGL
Say "Command was" SOURCELINE(SIGL)
Say "Abend Code was" RC
Say
Say "The DSN may be wrong. Try again:"
Pull DSN
"LISTD" DSN
Return
118
119
Write an exec asking for two numbers, and then multiply them. Set an error trap to
intercept any error such as invalid numbers.
ERROR:
SYNTAX:
Say "Command to TSO did not work on line" SIGL
Say "Error; command was" SOURCELINE(SIGL)
Say "Abend Code was" RC
Exit
Write an exec asking for an LRECL and a BLKSIZE. Determines if the BLKSIZE is
an even multiple of the LRECL. Tell the user if it is or is not.
119
120
Write a metric conversion exec. The exec should accept two arguments: UNIT and
QUANTITY. UNIT can have one of these possible values: LITER, QUART, MILE, or
KILOMETER.
It returns the equivalent of Quantity in the other measurement system based on this
table:
Select
When UNIT = "LITER"
Then Say AMT UNIT "is" AMT*1.057 "quart."
When UNIT = "QUART"
Then Say AMT UNIT "is" AMT*.946 "liter."
When UNIT = "MILE"
Then Say AMT UNIT "is" AMT*1.6 "kilometer."
When UNIT = "KILOMETER"
Then Say AMT UNIT "is" AMT*.625 "mile."
Otherwise Say "Invalid unit entered."
End
120
121
Write an exec asking the user to enter a series of numbers, never the same one twice in
a row. Limit the list to 10 numbers.
Write an ISPF edit macro to save and execute the exec you’re currently working on. It
must start with the usual comment, then ADDRESS ISREDIT MACRO. The commands
to be passed to the ISPF editor are:
(CURMBR) = MEMBER
SAVE
121
122
Write an exec to accept 2 numbers from the terminal. Verify they are valid numbers.
Subtract one from the other, drop the sign and display the answer.
Write an exec see if a dataset called WORKSHOP.TEMP exists. If so, delete it. If
not, allocate a new one like your EXEC library. The TSO command is:
/* REXX WORKSHOP.TEMP */
LDRC = LISTDSI("WORKSHOP.TEMP")
If LDRC = 0
Then "DELETE WORKSHOP.TEMP"
Else "ALLOC DSN(WORKSHOP.TEMP) LIKE(EXEC)"
122
123
/*-----------------------------------------*
* CONCatenate any two variables into one. *
*-----------------------------------------*/
CONC:
Arg V1,V2
ANS = VAR1||VAR2
RETURN ANS
123
124
Redo the % increase exec from Exercise #11 as an external subroutine. Name it
PERCENT. Have it accept two parameters, the old number and the new number. Have it
return the % increase on the RETURN statement. Check both args to be numeric. If
either or both arguments are invalid display a message and return a “0”.
Return PCTX
124
125
Using your solution to #21, write your concatenate subroutine as an external function /
subroutine (leave the internal one where it is). Call the external function / subroutine in a
such a way as to make sure you invoke the external one and not the internal one. Prove
you made the right call.
Exit
/*--------------------------------------------*
* This is the subroutine as an internal *
* call. There is a display in the external *
* call, none in this one. If the external *
* one is called, you should see the display. *
*--------------------------------------------*/
EX23:
Arg V1,V2
ANS = V1||V2
RETURN ANS /* Return the answer */
125
126
Convert the metric conversion program from Exercise #16 to an external subroutine
called METRIC, and write a main exec calling the function.
Select
When UNIT = "LITER"
Then Say AMOUNT UNIT "is" RESULT "quart."
When UNIT = "QUART"
Then Say AMOUNT UNIT "is" RESULT "liter."
When UNIT = "MILE"
Then Say AMOUNT UNIT "is" RESULT "kilometer."
When UNIT = "KILOMETER"
Then Say AMOUNT UNIT "is" RESULT "mile."
Otherwise Say "Invalid unit entered."
End
126
127
Create an external subroutine called SQRT to compute the square root of a number. It
accepts one number only. Make sure the data item is a number. If it’s not numeric (or it’s
negative) display an appropriate message and return a “0”. Set a loop limit of 50.
127
128
Write an exec with a loop setting NUMBER.1 through NUMBER.10 to the numbers
101 through 110. Then loop through the array displaying the contents of NUMBER.1
through NUMBER.11 to see what happens.
Write an exec to capture the display from TSO commands in an array, and then
display the lines of output one at a time.
DUMMY = OutTrap(Display_Line.)
Address TSO CMD
DUMMY = OutTrap(Off)
128
129
Write a REXX to accept a dataset name from the terminal. Verify the DSN is less than
45 bytes long. Verify it exists. Place the DSN into the stack so the LISTD command can
get at it. Suggestion: use QUEUE.
Turn on prompting. Execute the LISTD command but omit the dataset name so TSO
will prompt for it. Since the DSN is in the stack, LISTD should get it from there.
129
130
Choose a file you currently have available. Read it into an array, and then display
every other line starting with Line 1.
DO I = 1 TO MEMLIST.0 By 2
Say MEMLIST.I
END
130
131
Choose any available file. Read it into an array one record at a time. Count each line
as you read. Keep track of the longest record length. At the end of the program display
the record count and the length of the longest record.
MAINLINE:
Do I = 1 While EOF = “NO”
LineNum = LineNum + 1
Pull RECORD
LineLen = Length(RECORD)
If LineLen > LLine Then LLine = LineLen
Call READIT
End
Say “Number of lines read: “ LineNum
Say “Length of Longest Record: “ LLine
“DELSTACK”
“FREE F(INFILE)”
Exit
READIT:
“EXECIO 1 DISKR INFILE”
If RC <> 0 Then Do
EOF = “YES”
“EXECIO 0 DISKR INFILE (FINIS”
End
Return “”
131
132
DUMMY = OUTTRAP(“LINE.”)
/* your command here */
Do I = 1 to LINE.0 /* write each line */
Say “Line of output was:” LINE.I
End
DUMMY = OUTTRAP(“OFF”)
Use SYSDSN to see if the dataset exists. If not, allocate it using this command:
“ALLOC DA(TEMP.CAPTURE.DATA) F(CAPTURE) NEW SPACE(1 1) TRACKS
LRECL(80) RECFM(F B)”
OUTTRAP loads an array. Use that array to write the lines of the commad display.
The write command should close the file when it’s done writing.
DUMMY = OutTrap(Display_Line.)
Address TSO CMD
DUMMY = OutTrap(Off)
If SYSDSN(TEMP.CAPTURE.DATA) = “OK”
Then “ALLOC F(CAPTURE) DA(TEMP.CAPTURE.DATA) OLD REUSE”
Else “ALLOC F(CAPTURE) DA(TEMP.CAPTURE.DATA) NEW REUSE
SPACE(1 1) TRACKS LRECL(80) RECFM(F B)”
"EXECIO" Display_Line.0 "DISKW CAPTURE (STEM
Display_Line. FINIS”
Address ISPEXEC “BROWSE DATASET(TEMP.CAPTURE.DATA)”
132
Appendix D: REXX Functions and Instructions
Keywords are supported under both TSO and CMS unless noted. Some keywords are
used both as instructions and as functions. Keywords without a description are
environment commands (e.g. CONWAIT). Instructions begin on page 2; function
descriptions begin on Page 24.
TSO:
TSO (the default)
ISPEXEC (ISPF, Dialog Manager)
ISREDIT (the ISPF editor)
CMS:
CMS (the default if the file type is EXEC)
XEDIT (the default if the file type is XEDIT, i.e. XEDIT macros)
COMMAND (the CMS command processor. Note this bypasses synonyms,
requires upper case, and requires the file type EXEC for EXECs and CP for
CP commands).
Example:
ADDRESS ISPEXEC
“DISPLAY PANEL(MENUPANL)”
“VGET (RESP) SHARED”
ADDRESS TSO
“DELETE” RESP
ADDRESS environment command sends the one command to the named environment.
Other commands are not sent to this environment.
Example:
ADDRESS ISPEXEC “DISPLAY PANEL(MENUPANL)”
“DELETE” RESP
The ARG instruction receives data from a calling program. It is a short form of PARSE
UPPER ARG. In a main program it receives data typed on the command line; in a
function or subroutine it receives data passed to it on the call.
The data may be received in one or more variables separated by a delimiter such as a
space or comma. Fields separated by spaces are considered words; commas are normally
used in function calls. Use a period (.) to drop variables.
ARG FIELD1 FIELD2 FIELD3 places the first word (all characters up to the
first blank) in FIELD1, the second word in FIELD2, and all remaining characters
(spaces and all) in FIELD3.
ARG FIELDS places all data passed into the variable FIELDS.
ARG FIELD1 FIELD2 . places the first word in FIELD1, the second word in
FIELD2, and ignores everything after the second word.
ARG FIELD1,FIELD2 places all data before the first comma into FIELD1 and
the remaining data into FIELD2.
The CALL instruction invokes a subroutine, whether external or internal. The called
routine should end with a RETURN instructor. CALL can also turn on or off an error
trap.
CALL subroutine parameters passes parameters to the subroutine, which picks them up
via the ARG instruction. The subroutine passes the result, if any, in the variable
RESULT.
Example:
CALL LENGTH “ABCD”
SAY RESULT /* displays a 4 */
CALL ON condition-name sets up an error trap (see SIGNAL). If the error trap is
entered, a RETURN at the end of the trap sends control back to the instruction after the
failed instruction.
Example:
CALL ON ERROR /* sends control to the ERROR trap */
CONWAIT is a CMS-only instruction. It waits until all output directed to the terminal
has been displayed. Often used with DESBUF to ensure no terminal output is lost while
clearing the terminal output buffer.
Example:
PUSH “CART”
“CONWAIT”
“DESBUF” /* CART is lost */
DESBUF is a CMS-only instruction. It clears the stack and both the input and output
terminal buffers. Often used with CONWAIT to ensure no terminal output is lost while
clearing the buffers.
Example:
PUSH “CART”
“CONWAIT”
“DESBUF” /* CART is lost */
DO I = 1 TO 10 /* Increment a variable */
SAY I
END
DO I = 10 TO 1 BY -1 /* Decrement a variable */
SAY I
END
Example:
GREETING = “HI!”
SAY GREETING /* displays HI! on the screen */
DROP GREETING
SAY GREETING /* displays GREETING on the screen */
END ends a DO or SELECT structure. If on a counting loop, END can name the
counting variable to ensure the right loop is ending.
Example:
DO I = 1 TO 10
SAY I
END I /* we know it’s ending the DO I loop */
The EXECIO TSO/CMS instruction handles dataset I/O for reading, writing, and
updating datasets in a REXX exec. In TSO you must ALLOCATE the dataset before you
can run EXECIO.
CMS examples: note filename, filetype, and filemode stand for the actual file being
read or written.
“EXECIO * CARD (STEM RECD.” reads from the reader into the variables
RECD.1 through RECD.n where “n” is the number of cards read. EXECIO
sets RECD.0 to the number of cards read.
“EXECIO “ RECD.0 ”PRINT” writes all records from RECD. to the printer.
“EXECIO “ QUEUED() ”PUNCH” writes all records from the stack to punch.
TSO examples: note ddname stands for the DDname of the dataset being read or
written.
“EXECIO * DISKR ddname (FINIS” reads from the dataset into the stack
and closes the dataset.
“EXECIO 1 DISKRU ddname” gets one record from the file and holds it for
rewriting.
“EXECIO 1 DISKRU ddname (VAR REC1” gets one record from the file
and holds it in the variable REC1 for rewriting.
The EXECUTIL instruction is valid in TSO only. It may be executed inside an exec or
as a native TSO command. It controls the execution of a REXX exec. Some examples:
The EXIT instruction ends the REXX program and returns control to the calling program
or environment. May pass back a return code (numeric only) by coding it after the
instruction (EXIT 8 passes a return code of 8). The return code can be checked as
follows:
The EXPOSE instruction is used with the PROCEDURE instruction to allow the named
variables to be shared with the main program. In effect, EXPOSE makes the named
variables global. This instruction is usually found right after the PROCEDURE
statement; for example:
SUBPGM: PROCEDURE EXPOSE VAR1 shares VAR1 with the main program;
all other variables in the procedure SUBPGM are protected and cannot be
seen or modified by the main program.
The HI instruction stops execution of the program (HI is Halt Immediate). In TSO it
may only be executed after an ATTN interrupt. In CMS, it may be executed only when
the screen displays MORE … in the lower right.
The HT instruction stops display to the terminal (HT is Halt Terminal). In TSO it may
only be executed after an ATTN interrupt. In CMS, it may be executed only when the
screen displays MORE … in the lower right. See the RT command.
IF expression
THEN instruction
ELSE instruction
The expression may contain one of these comparison operators. Numbers are
compared numerically, characters by the collating sequence. See also the
description under “equal” and “strictly equal.”
= Equal. Numbers are equal numerically, e.g. 001.0 equals 1. Characters are
considered equal ignoring leading or trailing spaces, e.g. “ DEB “ is equal to
“DEB”. Case is significant, so “DEB” does not equal “Deb”.
<> Not equal. The opposite of “=”. Other ways of writing not equal are ^=, \=,
and ¬ =.
¬> Not greater than. The opposite of “>”. Other ways of writing not greater than
are ^= and \=.
¬> Not less than. The opposite of “<”. Other ways of writing not less than are ^=
and \=.
IF expressions continued.
== Equal in every way, strictly equal. This is a bit comparison rather than a value
comparison.
The expression may also contain one or more of these logical connectors.
Examples:
IF A = 1
THEN SAY “A IS EQUAL TO 1”
ELSE SAY “A IS NOT EQUAL TO 1”
IF A = 1
THEN DO
SAY “A IS EQUAL TO 1”
SAY “ISN’T IT?”
END
ELSE SAY “A IS NOT EQUAL TO 1”
IF examples continued.
IF A = 1 & B = 1
THEN SAY “A and B ARE BOTH EQUAL TO 1”
ELSE SAY “ONE OF A OR B IS NOT EQUAL TO 1”
IF A == “DATE”
THEN SAY “TRULY A DATE”
ELSE SAY “MAYBE A DATE, BUT NOT EXACTLY”
IF A ¬= “MEAT”
THEN SAY “I CAN EAT THAT”
ELSE DO
SAY “SORRY, I’M A VEGETARIAN”
EXIT
END
IF A <= 3
THEN SELECT
WHEN A = 1 THEN SAY “IT’S ON!”
WHEN A = 3 THEN SAY “IT’S OFF!”
OTHERWISE SAY “IT’S NOT ON OR OFF.”
END
ELSE IF A = 4
THEN SAY “SWITCH IS IN MIDDLE.”
ELSE SAY “INVALID VALUE FOR A.”
TRUE = 1
IF TRUE
THEN SAY “IT’S TRUE!”
ELSE SAY “DON’T LIE TO ME!”
The INTERPRET instruction causes REXX to look at data as if it is seeing it for the first
time. The data may be a REXX instruction or a command meant for the command
processor. Two examples:
PART1 = “S”
PART2 = “AY HI”
PART3 = “!”
INTERPRET PART1||PART2||PART3
The ITERATE instruction sends control to the DO of a DO-END loop. It skips the
instructions between it and the END. In a nested loop, ITERATE works only in its loop.
If ITERATE names a loop’s variable, REXX iterates within that loop. Three examples:
DO I = 1 TO 20
IF I = 13 THEN ITERATE /* SKIP #13 */
SAY I
END
DO HR = 1 TO 12
DO MM = 1 TO 60
IF MM = 60 THEN ITERATE HR /* next hour */
SAY HR“:”MM
END
END
The LEAVE instruction sends control to the instruction after the END of a DO-END
loop. LEAVE ends the loop it’s in. In a nested loop, LEAVE works only in its oen loop.
If LEAVE names a loop’s variable, REXX iterates within that loop. Three examples:
DO I = 1 TO 20
IF I = 13 THEN LEAVE /* PRINT 1 – 12 ONLY */
SAY I
END
DO HR = 1 TO 12
DO MM = 1 TO 60
IF MM = 60 THEN LEAVE HR /* next hour */
SAY HR“:”MM
END
END
The MAKEBUF instruction creates a new buffer. This buffer can be used like a stack,
but does not isolate the current stack. The buffer’s number is returned in the variable RC.
Drop buffers created with DROPBUF. When you delete the buffer, all its data is lost.
Here are two examples.
“MAKEBUF”
BUFNO = RC /* save buffer number */
SAY QUEUED() /* displays “1” */
PUSH “CART” /* place CART in stack */
SAY QUEUED() /* displays “1” */
“DROPBUF” BUFNO /* release MAKEBUF buffer */
SAY QUEUED() /* displays “0” (CART went away */
SAY “ENTER NAME” /* assume Arthur */
PULL NAME
SAY “THANKS,” NAME“.” /* NAME = Arthur */
PUSH “CART”
SAY QUEUED() /* displays “1” */
“NEWSTACK” /* get a new stack */
SAY QUEUED() /* displays “0” */
SAY “ENTER NAME” /* assume Arthur */
PULL NAME
SAY QUEUED() /* displays “0” */
SAY “THANKS,” NAME“.” /* NAME = Arthur */
“DELSTACK” /* return to the old stack */
SAY QUEUED() /* displays “1” */
SAY “ENTER VEHICLE” /* assume TAXI */
PULL VEHICLE
SAY “VEHICLE WAS” VEHICLE“.” /* displays CART */
“NEWSTACK”
PUSH “CART” /* place CART in stack */
SAY QUEUED() /* displays “1” */
“DELSTACK” /* Removes stack with CART */
SAY QUEUED() /* displays “0” */
SAY “ENTER NAME” /* assume Arthur */
PULL NAME
SAY QUEUED() /* displays “0” */
SAY “THANKS,” NAME“.” /* NAME = Arthur */
SAY QUEUED() /* displays “1” */
SAY “ENTER VEHICLE” /* assume TAXI */
PULL VEHICLE
SAY “VEHICLE WAS” VEHICLE“.” /* displays TAXI */
The NOP instruction tells REXX to do nothing. Here’s an example.
IF A = B
THEN NOP
ELSE SAY “A IS NOT EQUAL TO B.”
The NUMERIC instruction sets the way REXX deals with numbers. It has three forms,
explained below with examples.
NUMERIC DIGITS number sets the precision of arithmetic operations. The system
default is 9. While there is no limit to precision, high precision has high overhead. If
the number of digits exceeds the precision, the least significant digit is rounded.
The OTHERWISE instruction notes the default alternative in a SELECT structure. This
path is taken if none of the SELECT conditions are true. OTHERWISE is optional;
however, an END is required at the end of the SELECT whether there is an
OTHERWISE or not.
SELECT
WHEN S = “M” THEN SAY “HI, MISTER!”
WHEN S = “F” THEN SAY “HELLO, MISS!”
OTHERWISE SAY “GREETINGS!”
END
The PARSE instruction does character string functions. The basic syntax for PARSE is:
The UPPER is optional. If used, it converts the characters to upper case. If it is not used,
the characters remain in the case they started in.
PARSE takes the data from the origin and processes it using the template. The net result
is that all the variables in the template are set or changed in some way.
VAR a variable.
/* REXX STOOGE */
PARSE UPPER ARG VAR1 VAR2 VAR3
SAY VAR1
SAY VAR2
SAY VAR3
MOE
LARRY
CURLEY
PARSE examples continued.
Using a literal string delimiter. Data is first split at the delimiting character(s). Each
side of the delimiter is split by spaces or other delimiters. The delimiter is not
considered part of the string.
/* REXX STOOGE */
PARSE UPPER ARG VAR1 VAR2 “!” VAR3
SAY VAR1 VAR2
SAY VAR3
HEY MOE
HELLO!
Using column delimiters. Data is split at the columns given. The number to the left
of a variable is the starting column; the number to the right of a variable is the
ending column, minus one.
ABC
DEFG
HIJ
ABC
FG
EFGHIJK
Using a value.
TWO
WORDS
Using a variable.
HELLO
ALL
YOU PEOPLE
The PULL instruction takes a line from the program stack or, if empty, from the terminal
input buffer. Short form of PARSE UPPER PULL, see PARSE for more information.
The PUSH instruction puts a line into the program stack last in, first out (LIFO) (see the
QUEUE instruction). For example,
“QBUF”
SAY RC /* returns “0” */
“MAKEBUF”
“QBUF”
SAY RC /* returns “1” */
“DROPBUF”
“QBUF”
SAY RC /* returns “0” */
The QELEM instruction returns the number of elements or lines are available in the
buffer created by MAKEBUF. The number of buffers is returned in the variable RC. For
example,
“MAKEBUF”
PUSH “CART”
PUSH “CAR”
“QELEM”
SAY RC /* returns “2” */
“DROPBUF”
“QELEM”
SAY RC /* returns “0” */
The QSTACK instruction is available in TSO only. It returns the number of stacks
created by the NEWSTACK instruction, plus one. The number of stacks is returned in
the variable RC. To drop all the new stacks, use RC – 1 to know how many times to run
the DELSTACK command. For example,
“QSTACK”
HOW_MANY = RC - 1
DO HOW_MANY
“DELSTACK”
END
The QUEUE instruction puts a line in the program stack. Data is put into the stack first
in, first out (FIFO) (see the PUSH instruction). For example,
The RETURN instruction sends control back from a subroutine or internal function to
the instruction just after the call. Except in an error trap, can pass back a single string or
variable to the caller. For example:
SUBR:
ARG NUM1,NUM2
TOTAL = NUM1 + NUM2
RETURN TOTAL
Returns the sum of NUM1 and NUM2 back to the main program.
The RT instruction resumes display to the terminal (RT is Resume Terminal). This is the
opposite of HT. In TSO it may only be executed after an ATTN interrupt. In CMS, it
may be executed only when the screen displays MORE … in the lower right.
The SAY instruction displays a line on the terminal. The line may be either a variable, a
literal, a function call, or any combination.
Examples:
Example:
SELECT
WHEN DAY = 1 THEN SAY “SUNDAY”
WHEN DAY = 2 THEN SAY “MONDAY”
WHEN DAY = 3 THEN SAY “TUESDAY”
WHEN DAY = 4 THEN SAY “WEDNESDAY”
WHEN DAY = 5 THEN SAY “THURSDAY”
WHEN DAY = 6 THEN SAY “FRIDAY”
WHEN DAY = 7 THEN SAY “SATURDAY”
OTHERWISE SAY “NO SUCH DAY OF THE WEEK!”
END
The SIGNAL instruction turns on or off a condition trap named by a label. The trap can
interrupt a non-normal condition wherever it occurs after the SIGNAL. The code for the
error trap is found after the end of the main program.
Examples:
SYNTAX:
SAY “SYNTAX ERROR!”
EXIT
NOVALUE:
SAY “UNINITIALIZED VARIABLE ON” SOURCELINE(SIGL)
RETURN
SIGNAL can also be used as a label for a GOTO operation. For example,
SIGNAL DONE
:: code
DONE: A = A + 1
The SUBCOM instruction asks TSO or CMS if a particular environment is available, and
returns the answer in RC. RC is “0” if the environment is available, “1” if not.
Examples:
“SUBCOM” “TSO”
SAY RC /* displays “0” under TSO */
“SUBCOM” “ISPEXEC”
SAY RC /* displays “1” under TSO */
“SUBCOM” “ISPEXEC”
SAY RC /* displays “0” in ISPF */
“SUBCOM” “XEDIT”
SAY RC /* displays “0” if in XEDIT */
“SUBCOM” “USA”
SAY RC /* displays “1” */
The TE instruction is valid for TSO only. It turns interactive debugging off, and may be
run only after an attention interrupt.
The TS instruction turns interactive debugging on. In TSO it may only be executed after
an ATTN interrupt. In CMS, it may be executed only when the screen displays MORE …
in the lower right.
The UPPER instruction converts the alphabetic contents of a variable to upper case.
Example:
REXX has three reserved variables it uses for many situations. You may display,
check, or assign from them, but you should not change their contents.
The RC variable contains the return code set by an environment command. If the
command works, RC usually contains 0. There are exceptions; for example, see
MAKEBUF, QELEM, and QBUF. It also contains the number assigned to REXX syntax
errors. It is not set by REXX instructions, e.g. IF. Examples:
SIGNAL ON SYNTAX
“MAKEBUF”
SAY RC /* returns “1” or greater, buffer number */
“DELETE A.B.C”
IF RC = 0
THEN SAY “A.B.C DELETED”
ELSE SAY “DELETE FAILED”
SAY “A” – “B”
EXIT
SYNTAX:
SAY RC “IS THE REXX ERROR NUMBER.”
SAY ERRORTEXT(RC) “IS THE ERROR MESSAGE.”
SAY SIGL “IS THE LINE NUMBER IN ERROR.”
EXIT
The RESULT variable contains data passed back from a function or subroutine invoked
with the CALL instruction. It contains any data passed back on the RETURN statement.
Here is an example:
The SIGL variable contains the line number of the REXX statement causing a transfer of
control to a subroutine or condition trap. This is useful for debugging; see the example
code under RC.
REXX functions
The REXX functions listed here are supported under both TSO and CMS unless
otherwise noted. Functions may be used in one of two ways:
Letting REXX substitute the value for the function. For example,
NOTES:
o There must not be a space between the function name and the parentheses.
o The result of the function is not available in the variable RESULT.
o Separate parameters with commas, not spaces. For example,
LEFT(“ABCD”,3).
Using the special variable RESULT to get the value for the function. For
example,
NOTES:
Examples:
ABS(number). Returns the absolute value (i.e. drops the sign) of a number. Formats the
result using the current NUMERIC setting. For example:
Example:
ARG() returns the number of argument strings passed (commas delimit argument
strings). You can pass several to a subroutine or function, but only one to a main
program. Example:
BITOR(string1,string2,pad). BITOR logically ORs string1 and string2, with pad used
to fill the shorter string to the right. Each bit in string1 is compared to the corresponding
bit in string2. Each bit in the result is set to 1 if the matching bit in either string is a 1. If
neither bit in the strings are 1, the corresponding bit in the result is set to 0. Examples:
COMPARE(“APPLES”,“APPLES”) /* returns 0 */
COMPARE(“APPLES”,“APPLESAUCE”) /* returns 1 */
CONDITION(type). Normally used in a condition trap, this function gives information
about the condition found. Valid types are:
Examples:
SIGNAL ON ERROR
“LISTCAT NOHLQ”
EXIT
ERROR:
SAY “COMMAND FAILED!”
SAY CONDITION(“C”) /* displays “ERROR” */
SAY CONDITION(“D”) /* displays “LISTCAT NOHLQ” */
SAY CONDITION(“I”) /* displays “SIGNAL” */
EXIT
C2D(string). Converts string to its binary form, then to a decimal number. Examples:
DATATYPE(string,type)
Returns 1 if string has the same type as type, otherwise it returns 0. Note you may
need to strip extra spaces to get this to work properly; for example,
Valid types:
A – alphanumeric (A – Z, a – z, 0 – 9)
B – binary digits 1 and 0
D – double-byte characters
L – lower-case characters
M – mixed-case characters
N – valid number
S – valid REXX symbol
U – upper-case letters
W – whole number
X – hexadecimal number (0 – 9, A – F)
Examples:
Valid types:
NUMERIC DIGITS 7
SAY DIGITS() /* returns 7 */
D2C(number). Converts the decimal number to a hex number, and then returns the
character for that hexadecimal code.
ERRORTEXT(number). Returns the REXX syntax message for the passed error
number.
EXTERNALS(). Returns the number of elements in the terminal input buffer (how
many lines are there). In VM/CMS, this number can be greater than zero; in TSO,
because there is no type-ahead buffer REXX returns zero..
LongNum = 1 / 3
ShortNum = 1 / 2
SAY FORMAT(LongNum,3,2) /* returns ‘ 1.33’ */
SAY FORMAT(ShortNum,2,4) /* returns ‘ 0.5000’ */
NUMERIC FUZZ 2
SAY FUZZ() /* returns ‘2’ */
LISTDSI (TSO only). Returns information about the dataset in REXX variables. See
the following pages for a list of those variables and for the return codes set by LISTDSI.
It can be used in two ways.
RetCode = LISTDSI(dsn)
or
0) Success!
1) REXX had a problem analyzing the statement
2) Dynamic allocation failure
3) Cannot process this type of dataset
4) Error occurred obtaining unit name
5) Dataset is not catalogued
6) Error occurred getting dataset name
7) Error occurred getting unit type
8) Dataset is not on disk
9) Dataset is migrated and cannot be recalled
10) -
11) Unauthorized to obtain directory information
12) VSAM dataset
13) Open error
14) Device type not found in MVS
15) –
16) Command did not work
17) Some sort of abend
18) Incomplete information obtained
19) Multi-volume dataset
20) Unknown device type
21) Catalog error
22) Volume not mounted
23) I/O error attempting to get dataset information
24) Dataset not on catalogued volume
25) Dataset is migrated and is unavailable
26) Dataset is on a mass storage device
27) Cannot find VOLSER for this dataset
28) DD name specified is not valid
29) Neither dataset name nor DD name was provided
When using SYMDEF, you must supply both the word SYMDEF and the symbolic
variable name. Variables must be defined in the SYS1.PARMLIB member IEASYMxx.
OUTTRAP, TSO only. Captures the output from most TSO commands into a stem
variable you specify. The first entry of the stem variable, VAR.0, contains the number of
lines of output. You can also specify the number of lines to trap, from none (suppress all
messages) to all lines.
NOTE: some programs, such as the CONCAT command, produce output that cannot
be captured by OUTTRAP.
TMP = OUTTRAP(LCDATA.)
“LISTC ENT(MY.JCL.PDS)”
TMP = OUTTRAP(“OFF”)
SAY “There are” LCDATA.0 “lines of LISTC output.”
Say LCDATA.1 /* produces ‘0NONVSAM MYID.MY.JCL.PDS’ */
Say LCDATA.2 /* produces ‘ IN-CAT LOCAL.CATALOG’ */
Do I = 1 to LCDATA.0
Say LCDATA.I
End /* DO group displays all lines from the LISTC */
PROMPT(), TSO only. Returns the PROMPT status of your TSO session.
Alternatively, sets the PROMPT status of your session. When PROMPT is on, TSO
commands prompt the user for input if it is missing. When PROMPT is off, those
messages are suppressed.
SIGN(number). Returns:
Say STORAGE(000000,8)
Displays the first 8 bytes of storage.
NewString = STRIP(string,option,character). Removes character from string based on
option. By default, character is a space. Available options are:
Say STRIP(‘MYUSERID.MY.CNTL’,,“’”)
Displays “MYUSERID.MY.CNTL”
As you can see from that last example, STRIP is useful for removing leading and
trailing quotes from fully-qualified dataset names.
OK
MEMBER SPECIFIED BUT DATASET NOT PDS
MEMBER NOT FOUND
DATASET NOT FOUND
ERROR PROCESSING REQUESTED DATASET
PROTECTED DATASET
VOLUME NOT ON SYSTEM
UNAVAILABLE DATASET
INVALID DATASET NAME
MISSING DATASET NAME
1. SYSVAR can only be used in TSO/E environments (i.e. not VM, Linux, etc.).
3. SYSPCMD and SYSSCMD are connected. For example, if you’re running the TEST
TSO command (debugging a program), SYSSCMD might return EQUATE (the last
TEST command run) while SYSPCMD would return TEST.
5. Some CLIST control variables do not apply to REXX. REXX has “replacements” for
these variables.
SYSDATE ===> DATE(“U”)
SYSJDATE ===> DATE(“J”)
SYSSDATE ===> DATE(“O”)
SYSSTIME ===> SUBSTR(TIME(),1,5)
SYSTIME ===> TIME()
Examples:
Am I in ISPF?
If SYSVAR(SYSISPF) = “NOT ACTIVE” Then Exit
TIME() : hh:mm:ss
TIME(“E”): first time, starts the elapsed time counter
TIME(“E”): second time, displays the number of seconds since the first
“E”.
TIME(“H”): hours since midnight
TIME(“M”): minutes since midnight
TIME(“R”): Resets elapsed time to zero.
TIME(“S”): Seconds since midnight
Example:
SAY TRANSLATE(“ABCDEF”,“ZYXWV”,“ABCDE”)
displays ZYXWVF
Examples:
PROGLANG = “COBOL”
COBOL = “English-like”
Say VALUE(“PROGLANG”) /* displays ‘COBOL’ */
Say VALUE(PROGLANG) /* displays ‘English-like’ */
IF VERIFY(input,'1234567890E+-*/% ().') = 0
THEN /* ‘input’ is a valid arithmetic expression */
ELSE SAY input “has invalid arithmetic characters.”
Examples: