home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 18 REXX / 18-REXX.zip / rximc175.zip / rexx.info < prev    next >
Text File  |  2002-08-06  |  39KB  |  963 lines

  1.   The REXX Tutorial 
  2.  
  3.   Note: some of the information in this file is system-specific, though
  4.   most of it pertains to every implementation of Rexx.
  5. # Lines containing implementation-specific information are flagged with
  6. # letters in column 1. The letter "I" denotes information for REXX/imc.
  7. # I have also started adding information about OS/2 Rexx, which will be
  8. # flagged with "O" in column 1. I hope it is not too confusing to see some
  9. # sections written twice, once for each system.  The file is designed so
  10. # that if you run it through "egrep '^(x| |$)'|cut -c3-" (where x is the
  11. # desired letter) then it should still make sense and cut out the flag
  12. # letters.  Doing this will select one of the following lines indicating
  13. # which system was selected; the characters to the left of this paragraph
  14. # will make sure it gets deleted when that happens.
  15. I This file describes REXX/imc.
  16. O This file describes OS/2 Classic Rexx (which is also pretty much
  17. O compatible with the OS/2 Object Rexx interpreter).
  18.   
  19. I More advanced information can be found in rexx.summary (bare details
  20. I of each command and builtin function, with a list of differences from
  21. I standard Rexx) and rexx.ref (technical details of every aspect of this
  22. I Rexx implementation).
  23. O More information is available in the OS/2 help system.  For example,
  24. O typing "help rexx signal" will give the syntax of the Rexx "signal"
  25. O instruction.
  26.   
  27.   1. Creating a Rexx program
  28.   
  29.   Many programmers start by writing a program which displays the message
  30.   "Hello world!".  Here is how to do that in Rexx...
  31.   
  32. I Write a file called "hello.rexx" containing the following text.  Use any
  33. I text editor or simply `cat' the text into the file.
  34. O Write a file called "hello.cmd" containing the following text.  Use any
  35. O text editor (for example, E).
  36.   Note that the text, as with all example text in this guide, starts at the
  37.   first indented line and ends at the last.  The four spaces at the start of
  38.   each line of text should not be entered.
  39.   
  40.       /* This program says "Hello world!" */
  41.       say "Hello world!"
  42.   
  43.   This program consists of a comment saying what the program does, and an
  44.   instruction which does it.  "say" is the Rexx instruction which displays
  45.   data on the terminal.
  46.   
  47.   The method of executing a Rexx program varies greatly between
  48.   implementations.
  49. I Here is how you execute that file using REXX/imc:
  50. I
  51. I     rexx hello
  52. I
  53. I Notes about this command: rexx is the name of the interpreter.  In order
  54. I for this command to work, the interpreter must lie on your current PATH.
  55. I If you require more information about this then you should contact the
  56. I person who installed REXX on your system.
  57. I
  58. I The word "hello" which comes after the command "rexx" is the name of your
  59. I program.  Ordinarily, the interpreter adds ".rexx" to the name you give in
  60. I order to construct the name of the file to execute.
  61. I
  62. O Here is how you execute that file on OS/2:
  63. O
  64. O     hello
  65. O
  66.   When you execute your first Rexx program using the method detailed above,
  67.   you should see the message "Hello world!" appear on the screen.
  68.  
  69.   2. Doing arithmetic
  70.  
  71.   Rexx has a wide range of arithmetic operators, which can deal with very
  72.   high precision numbers.  Here is an example of a program which does
  73.   arithmetic.
  74. I Make a file called "arith.rexx" containing the following.
  75. O Make a file called "arith.cmd" containing the following.
  76.  
  77.       /* This program inputs a number and does some calculations on it */
  78.       pull a
  79.       b=a*a
  80.       c=1/a
  81.       d=3+a
  82.       e=2**(a-1)
  83.       say 'Results are:' a b c d e
  84.  
  85. I Run it with "rexx arith" and type in a positive integer.
  86. O Run it by typing "arith" and type in a positive integer.
  87.   Here is a sample run:
  88.  
  89. I     rexx arith
  90. O     arith
  91.       5
  92.       Results are: 5 25 0.2 8 16
  93.  
  94.   The results you see are the original number (5), its square (25), its
  95.   reciprocal (0.2), the number plus three (8) and two to the power of one
  96.   less than the number (16).
  97.  
  98.   This example illustrates several things:
  99.  
  100.   * variables: in this example a, b, c, d and e are variables.  You can
  101.     assign a value to a variable by typing its name, "=", and a value,
  102.     and you can use its value in an expression simply by typing its name.
  103.   * input: by typing "pull a" you tell the interpreter to ask the user for
  104.     input and to store it in the variable a.
  105.   * arithmetic: the usual symbols (+ - * /) as well as ** (to-power) were
  106.     used to perform calculations.  Parentheses (or "brackets") were used
  107.     to group together an expression, as they are in mathematics.
  108.   * string expressions: the last line of the program displays the results by
  109.     saying the string expression
  110.     
  111.         'Results are:' a b c d e
  112.  
  113.     This has six components: the string constant 'Results are:' and the
  114.     five variables.  These components are attached together with spaces
  115.     into one string expression, which the "say" command then displays on
  116.     the terminal.  A string constant is any sequence of characters which
  117.     starts and ends with a quotation mark - that is, either " or ' (it makes
  118.     no difference which you use, as long as they are both the same).
  119.  
  120.   If you supply the number 6 as input to the program, you should notice
  121.   that the number 1/6 is given to nine significant figures.  You can easily
  122.   change this.  Edit the program and insert before the second line:
  123.  
  124.       numeric digits 25
  125.  
  126.   If you run this new program you should see that 25 significant figures are
  127.   produced.  In this way you can calculate numbers to whatever accuracy you
  128.   require, within the limits of the machine.
  129.  
  130.   At this point it seems worth a mention that you can put more than one
  131.   instruction on a line in a Rexx program. You simply place a semicolon
  132.   between the instructions, like this:
  133.  
  134.       /* This program inputs a number and does some calculations on it */
  135.       pull a; b=a*a; c=1/a; d=3+a; e=2**(a-1); say 'Results are:' a b c d e
  136.  
  137.   Needless to say, that example went a bit over the top...
  138.       
  139.   3. Errors
  140.  
  141.   Suppose you ignored the instructions of the previous section and typed a
  142.   non-integer such as 3.4 as input to the program.  Then you would get an
  143.   error, because the ** (to-power) operator is only designed to work when
  144.   the second parameter (that is, the power number) is an integer. You might
  145.   see this, for example:
  146.  
  147. I     rexx arith
  148. I     3.4
  149. I         6 +++ e=2**(a-1)
  150. I     Error 26 running arith.rexx, line 6: Invalid whole number
  151. O     arith
  152. O     3.4
  153. O          6 +++   e = 2 ** ( a - 1 );
  154. O     REX0026: Error 26 running D:\ARITH.CMD, line 6: Invalid whole number
  155.  
  156.   Or if you typed zero, you might see the following (because you cannot
  157.   divide by zero):
  158.  
  159. I     rexx arith
  160. I     0
  161. I         4 +++ c=1/a
  162. I     Error 42 running arith.rexx, line 4: Arithmetic overflow or underflow
  163. O     arith
  164. O     0
  165. O          4 +++   c = 1 / a;
  166. O     REX0042: Error 42 running D:\ARITH.CMD, line 4: Arithmetic 
  167. O     overflow/underflow
  168.  
  169.   Perhaps most interestingly, if you type a sequence of characters which is
  170.   not a number, you might see this.  It does not complain about the
  171.   characters you entered, but at the fact that the program tries to use it
  172.   as a number.
  173.  
  174. I     rexx arith
  175. I     hello
  176. I         3 +++ b=a*a
  177. I     Error 41 running arith.rexx, line 3: Bad arithmetic conversion
  178. O     arith
  179. O     hello
  180. O          3 +++   b = a * a;
  181. O     REX0041: Error 41 running D:\ARITH.CMD, line 3: Bad arithmetic conversion
  182.  
  183.   In each case, you have generated a "syntax error" (it is classified as a
  184.   syntax error, even though the problem was not directly related to the
  185.   program's syntax).  What you see is a "traceback" starting with the line
  186.   which caused the error (no other lines are listed in this traceback,
  187.   because we have not yet considered any Rexx control structures), and a
  188.   description of the error.  This information should help you to determine
  189.   where the error occurred and what caused it.  More difficult errors can be
  190.   traced with the "trace" instruction (see later).
  191.  
  192.   4. Untyped data
  193.  
  194.   In the previous section, you found that you could input either a number or
  195.   a sequence of letters and store it in the variable a, although arithmetic
  196.   can only be performed on numbers.  That is because data in Rexx are
  197.   untyped.  In other words, the contents of a variable or the result of an
  198.   expression can be any sequence of characters.  What those characters are
  199.   used for matters only to you, the programmer.  However, if you try to
  200.   perform arithmetic on a random sequence of characters you will generate a
  201.   syntax error, as shown in the previous section.
  202.  
  203.   You have seen that you can add strings together by placing a space in
  204.   between them.  There are two other ways: the abuttal and the concatenation
  205.   operator.  An abuttal is simply typing the two pieces of data next to each
  206.   other without a space.  This is not always appropriate: for example you
  207.   cannot type an "a" next to a "b", because that would give "ab", which is
  208.   the name of another unrelated variable.  Instead, it is safer to use the
  209.   concatenation operator, ||.  Both these operations concatenate the strings
  210.   without a space in between.  For example:
  211.  
  212.       /* demonstrates concatenation and the use of untyped data */
  213.       a='A string'
  214.       b='123'
  215.       c='456'
  216.       d=a":" (b||c)*3
  217.       say d
  218.  
  219.   The above program says "A string: 370368".  This is because (b||c) is the
  220.   concatenation of strings b and c, which is "123456".  That sequence of
  221.   characters happens to represent a number, and so it can be multiplied by 3
  222.   to give 370368.  Finally, that is added with a space to the concatenation
  223.   of a with ":" and stored in d.
  224.  
  225.   5. More on variables
  226.  
  227.   The previous examples only used single-letter variable names.  In fact
  228.   it is more useful to have whole words as variable names, and Rexx allows
  229.   this up to an implementation maximum (which should be suitably large, e.g.
  230.   250 characters).  Moreover, not only letters but numbers and the three
  231.   characters "!", "?" and "_" are allowed in variable names - or "symbols",
  232.   as they are generally called.  These are valid symbols:
  233.  
  234.       fred
  235.       Dan_Yr_0gof
  236.       HI!
  237.  
  238.   The case of letters is unimportant, so that for example "Hello", "HELLO"
  239.   and "hellO" all mean the same.
  240.  
  241.   If you use a symbol in an expression when it has not been previously given
  242.   a value, that does not cause an error (unless "signal on novalue" is set -
  243.   see later).  Instead, it just results in its own name translated into
  244.   upper case.
  245.  
  246.       /* A demonstration of simple symbols */
  247.       foo=3
  248.       bar="Characters"
  249.       say foo bar':' hi!
  250.  
  251.   This program says "3 Characters: HI!".
  252.  
  253.   As well as "simple symbols", which are variables like the above, there
  254.   are arrays (strictly speaking, they are not called arrays in Rexx but
  255.   "stem variables", though equivalent things in other languages are called
  256.   "associative arrays").  Any ordinary variable name can also be used as the
  257.   name of an array:
  258.  
  259.       /* This program uses an array. */
  260.       pull a
  261.       array.1=a
  262.       array.2=a*a
  263.       array.3=a**3
  264.       say array.1 array.2 array.3 array.1+array.2+array.3
  265.  
  266.   An element of an array is accessed by typing the array name, a dot, and
  267.   the element number.  The array name and the dot are together known as
  268.   the "stem" of the array.  The rest of the element's name is known as the
  269.   "tail" of the name.  The stem and tail together are called "a compound
  270.   symbol".  Note that an array does not have to be declared before it is
  271.   used.  Also note that the simple variable "a" and the stem "a." refer
  272.   to completely separate variables.
  273.  
  274.   In fact not only numbers, but strings and variable names may be used as
  275.   element names.  Also, an element name can consist of two or more parts
  276.   separated by dots, so giving two or more dimensional arrays.
  277.  
  278.       /* This program uses an array with various elements */
  279.       book.1.author="M. F. Cowlishaw"
  280.       book.1.title="The REXX Language, a practical approach to programming"
  281.       book.1.pub="Englewood Cliffs 1985"
  282.       book.2.author="A. S. Rudd"
  283.       book.2.title="Practical Usage of REXX"
  284.       book.2.pub="Ellis Horwood 1990"
  285.       /* insert lots more */
  286.       say "Input a book number"
  287.       pull i
  288.       say "Author:   " book.i.author
  289.       say "Title:    " book.i.title
  290.       say "Publisher:" book.i.pub
  291.  
  292.   In the above program, a stem variable called "book" is created, containing
  293.   a number of records each with elements AUTHOR, TITLE and PUB.  Notice that
  294.   these three uppercase names are produced by symbols "author", "title" and
  295.   "pub", because those symbols have not been given values.  When a book
  296.   number i has been input, the elements of the (i)th record are printed out.
  297.  
  298.   It is not an error to reference an undefined element of a stem variable.
  299.   If you type "3" into the above program, you will see this:
  300.  
  301.       Input a book number
  302.       3
  303.       Author:    BOOK.3.AUTHOR
  304.       Title:     BOOK.3.TITLE
  305.       Publisher: BOOK.3.PUB
  306.  
  307.   As before, if a compound symbol has not been given a value, then its name
  308.   is used instead.
  309.  
  310.   There is a way to initialise every element of a stem variable: by
  311.   assigning a value to the stem itself.  Edit the above program and insert
  312.   after the comment line:
  313.  
  314.       book.="Undefined"
  315.  
  316.   This gives every possible element of the stem variable the value
  317.   "Undefined", so that if you again type "3" you will see the following:
  318.  
  319.       Input a book number
  320.       3
  321.       Author:    Undefined
  322.       Title:     Undefined
  323.       Publisher: Undefined
  324.       
  325.   6. Functions
  326.  
  327.   The Rexx Summary contains a list of the functions which are available in
  328.   Rexx.  Each of these functions performs a specific operation upon the
  329.   parameters. For example,
  330.  
  331.       /* Invoke the date function with various parameters */
  332.       say date("W")',' date()
  333.  
  334.   This might say, for example, "Friday, 22 May 1992".
  335.  
  336.   A function is called by typing its name immediately followed by "(".
  337.   After that come the parameters, if any, and finally a closing ")". Note
  338.   that you should not type a space between the name and "(", because that
  339.   space would be a concatenation operator, as in section 4. In the above
  340.   example, the "date" function is called twice.  The value of date("W") is
  341.   the name of the weekday, and the value of date() is the date in "default"
  342.   format.
  343.  
  344.   7. Conditionals
  345.  
  346.   It is time to use some Rexx control structures.  The first of these will
  347.   be the conditional.  Here is an example:
  348.  
  349.       /* Use a conditional to tell whether a number is less than 50 */
  350.       pull a
  351.       if a<50 then say a "is less than 50"
  352.       else say a "is not less than 50"
  353.  
  354.   The program is executed in the manner in which it reads - so, if a is less
  355.   than 50 then the first instruction is executed, and otherwise the second
  356.   instruction is executed.
  357.  
  358.   The "a<50" is a conditional expression.  It is like an ordinary
  359.   expression (in fact conditional expressions and ordinary numeric
  360.   expressions are interchangeable), but it contains a comparison operator.
  361.  
  362.   There are many comparison operators, as follows:
  363.  
  364.   = (equal to)  < (less than)  > (greater than)  <= (less or equal)
  365.   >= (greater or equal)  <> (greater or less)  \= (not equal)
  366.   \> (not greater)  \< (not less)
  367.  
  368.   All the above operators can compare numbers, deciding whether one is equal
  369.   to, less than, or greater than the other.  They can also compare
  370.   non-numeric strings, first stripping off leading and trailing blanks.
  371.  
  372.   There are analogous comparison operators to these for comparing strings
  373.   strictly.  The main difference between them is that 0 is equal to 0.0
  374.   numerically speaking, but the two are different if compared as strings.
  375.   The other difference is that the strict operators do not strip blanks
  376.   before comparing.  The strict operators are
  377.  
  378.   == (equal to)  << (less than)  >> (greater than)  <<= (less or equal)
  379.   >>= (greater or equal)  \== (not equal)  \>> (not greater)  \<< (not less)
  380.  
  381.   Conditional expressions may be combined with the boolean operators:
  382.   & (and), | (or) and && (xor).  They may also be reversed with the \ (not)
  383.   operator.
  384.  
  385.       /* Decide what range a number is in */
  386.       pull a
  387.       if a>0 & a<10 then say "1-9"
  388.       if a\<10 & a<20 then say "10-19"
  389.       if \ (a<20 | a>=30) then say "20-29"
  390.       if a<=0 | a>=30 then say "Out of range"
  391.  
  392.   As well as demonstrating the boolean and comparison operators, this
  393.   program shows that the "else" clause is not required to be present.
  394.  
  395.   The above program may also be written using Rexx's other conditional
  396.   instruction, "select":
  397.  
  398.       /* Decide what range a number is in */
  399.       pull a
  400.       select
  401.          when a>0 & a<10 then say "1-9"
  402.          when a\<10 & a<20 then say "10-19"
  403.          when \ (a<20 | a>=30) then say "20-29"
  404.          otherwise say "Out of range"
  405.       end
  406.  
  407.   The "select" instruction provides a means of selecting precisely one from
  408.   a list of conditional instructions, with the option of providing a list of
  409.   instructions to do when none of the above was true.  The difference is
  410.   that if no part of a "select" instruction can be executed then a syntax
  411.   error results, whereas it is OK to miss out the "else" part of an "if"
  412.   instruction.
  413.  
  414.   Only one instruction may be placed after the "then" or "else" of
  415.   a conditional instruction, but Rexx provides a way of bracketing
  416.   instructions together so that they can be treated as a single instruction.
  417.   To do this, place the instruction "do" before the list of instructions and
  418.   "end" after it.
  419.  
  420.       /* execute some instructions conditionally */
  421.       pull a
  422.       if a=50 then
  423.          do
  424.             say "Congratulations!"
  425.             say "You have typed the correct number."
  426.          end
  427.       else say "Wrong!"
  428.  
  429.   If you wish for one of the conditional instructions to do "nothing", then
  430.   you must use the instruction "nop" (for "no operation").  Simply placing
  431.   no instructions after the "then", "else" or "when" will not work.
  432.  
  433.   8. Loops
  434.  
  435.   Rexx has a comprehensive set of instructions for making loops, using the
  436.   words "do" and "end" which you met briefly in the previous section.
  437.  
  438.     a. Counted loops
  439.  
  440.     The instructions within a counted loop are executed the specified number
  441.     of times:
  442.  
  443.         /* Say "Hello" ten times */
  444.         do 10
  445.            say "Hello"
  446.         end
  447.  
  448.     A variation of the counted loop is one which executes forever:
  449.  
  450.         /* This program goes on forever until the user halts it */
  451.         do forever
  452.            nop
  453.         end
  454.  
  455.     b. Control loops
  456.  
  457.     Control loops are like counted loops, but they use a variable (called
  458.     the control variable) as a counter.  The control variable may count
  459.     simply in steps of 1:
  460.  
  461.         /* Count to 20 */
  462.         do c=1 to 20
  463.            say c
  464.         end
  465.  
  466.     or in steps of some other value:
  467.  
  468.         /* Print all multiples of 2.3 not more than 20 */
  469.         do m=0 to 20 by 2.3
  470.            say m
  471.         end
  472.  
  473.     It may take a specific number of steps:
  474.  
  475.         /* Print the first six multiples of 5.7 */
  476.         do m=0 for 6 by 5.7
  477.            say m
  478.         end
  479.  
  480.     or it may go on forever:
  481.  
  482.         /* Print all the natural numbers */
  483.         do n=0
  484.            say n
  485.         end n
  486.  
  487.     The "n" at the end of this last example is optional.  At the end of any
  488.     controlled loop, the name of the control variable may be placed after
  489.     the "end", where it will be checked to see if it matches the control
  490.     variable.
  491.  
  492.     c. Conditional loops
  493.  
  494.     A set of instructions may be executed repeatedly until some condition is
  495.     true. For example,
  496.  
  497.         /* I won't take no for an answer */
  498.         do until answer \= "NO"
  499.            pull answer
  500.         end
  501.  
  502.     Alternatively, they may be executed as long as some condition is true:
  503.  
  504.         /* It's OK to repeat this as long as there is no error */
  505.         do while error=0
  506.            pull a
  507.            if a="ERROR" then error=1
  508.            else say a
  509.         end
  510.  
  511.     Note that in this example, the variable "error" must be zero to
  512.     start with.  If there is already an error to start with then the
  513.     set of instructions will not be executed at all.  However in the
  514.     previous example the instructions will always be executed at least
  515.     once.  That is, the expression after an "until" is evaluated at the
  516.     end of the loop, whereas the expression after a "while" is evaluated
  517.     at the start of the loop.
  518.  
  519.     d. Controlled conditional loops
  520.  
  521.     It is possible to combine forms a or b with form c mentioned above, like
  522.     this:
  523.  
  524.         /* I won't take no for an answer unless it is typed three times */
  525.         do 3 until answer \= "NO"
  526.            pull answer
  527.         end
  528.  
  529.     or this:
  530.  
  531.         /* input ten answers, but stop when empty string is entered */
  532.         do n=1 to 10 until ans==""
  533.            pull ans
  534.            a.n=ans
  535.         end
  536.  
  537.   The "iterate" and "leave" instructions allow you to continue with, or to
  538.   leave, a loop respectively.  For example:
  539.  
  540.       /* input ten answers, but stop when empty string is entered */
  541.       do n=1 to 10
  542.          pull a.n
  543.          if a.n=="" then leave
  544.       end
  545.  
  546.       /* print all integers from 1-10 except 3 */
  547.       do n=1 to 10
  548.          if n=3 then iterate
  549.          say n
  550.       end
  551.  
  552.   If a symbol is placed after the instructions "iterate" or "leave", then
  553.   you can iterate or leave the loop whose control variable is that symbol.
  554.  
  555.       /* Print pairs (i,j) where 1 <= i,j <= 5, except (2,j) if j>=3 */
  556.       do i=1 to 5
  557.          do j=1 to 5
  558.             if i=2 & j=3 then iterate i /* or "leave j" would work,
  559.                                            or just "leave"           */
  560.             say "("i","j")"
  561.          end
  562.       end
  563.  
  564.   9. Parsing
  565.  
  566.   The following program examines its arguments:
  567.  
  568.       /* Parse the arguments */
  569.       parse arg a.1 a.2 a.3 a.4
  570.       do i=1 to 4
  571.          say "Argument" i "was:" a.i
  572.       end
  573.  
  574.   Execute it as usual, except this time type "alpha beta gamma delta" after
  575.   the program name on the command line, for example:
  576.  
  577. I     rexx arguments "alpha beta gamma delta"
  578. O     argumnts alpha beta gamma delta
  579.  
  580.   The program should print out:
  581.  
  582.       Argument 1 was: alpha
  583.       Argument 2 was: beta
  584.       Argument 3 was: gamma
  585.       Argument 4 was: delta
  586.  
  587.   The argument "alpha beta gamma delta" has been parsed into four
  588.   components.  The components were split up at the spaces in the input.
  589.   If you experiment with the program you should see that if you do not
  590.   type four words as arguments then the last components printed out are
  591.   empty, and that if you type more than four words then the last component
  592.   contains all the extra data.  Also, even if multiple spaces appear between
  593.   the words, only the last component contains spaces.  This is known as
  594.   "tokenisation".
  595.  
  596.   It is not only possible to parse the arguments, but also the input.  In
  597.   the above program, replace "arg" by "pull".  When you run this new program
  598.   you will have to type in some input to be tokenised.
  599.  
  600.   Replace "parse arg" with "parse upper arg" in the program.  Now, when
  601.   you supply input to be tokenised it will be uppercased.  The instruction
  602.   "parse upper" is a variant of "parse" which always translates the data to
  603.   upper case.
  604.  
  605.   "arg" and "pull" are, respectively, abbreviations for the instructions
  606.   "parse upper arg" and "parse upper pull".  That explains why the "pull"
  607.   instruction appeared in previous examples, and why it was that input was
  608.   always uppercased if you typed letters in response to it.
  609.  
  610.   Other pieces of data may be parsed as well.  "parse source" parses
  611.   information about how the program was invoked, and what it is called,
  612.   and "parse version" parses information about the interpreter itself.
  613.   However, the two most useful uses of the parse instruction are
  614.   "parse var [variable]" and "parse value [expression] with".  These
  615.   allow you to parse arbitrary data supplied by the program.
  616.  
  617.   For example,
  618.  
  619.       /* Get information about the date and time */
  620.       d=date()
  621.       parse var d  day month year
  622.  
  623.       parse value time() with hour ':' min ':' sec
  624.  
  625.   The last line above illustrates a different way to parse data.  Instead of
  626.   tokenising the result of evaluating time(), we split it up at the
  627.   character ':'.  Thus, for example, "17:44:11" is split into 17, 44 and 11.
  628.  
  629.   Any search string may be specified in the "template" of a "parse"
  630.   instruction.  The search string is simply placed in quotation marks,
  631.   for example:
  632.  
  633.       parse arg first "beta" second "delta"
  634.  
  635.   This line assigns to variable first anything which appears before
  636.   "beta", and to second anything which appears between "beta" and "delta".
  637.   If "beta" does not appear in the argument string, then the entire string
  638.   is assigned to first, and the empty string is assigned to "second".  If
  639.   "beta" does appear, but "delta" does not, then everything after "beta"
  640.   will be assigned to second.
  641.  
  642.   It is possible to tokenise the pieces of input appearing between search
  643.   strings. For example,
  644.  
  645.       parse arg "alpha" first second "delta"
  646.  
  647.   This tokenises everything between "alpha" and "delta" and places the
  648.   tokens in first and second.
  649.  
  650.   Placing a dot instead of a variable name during tokenising causes that
  651.   token to be thrown away:
  652.  
  653.       parse pull a . c . e
  654.  
  655.   This keeps the first, third and last tokens, but throws away the second
  656.   and fourth.  It is often a good idea to place a dot after the last
  657.   variable name, thus:
  658.  
  659.       parse pull first second third .
  660.  
  661.   Not only does this throw away the unused tokens, but it also ensures
  662.   that none of the tokens contains spaces (remember, only the last token
  663.   may contain spaces; this is the one we are throwing away).
  664.  
  665.   Finally, it is possible to parse by numeric position instead of by
  666.   searching for a string.  Numeric positions start at 1, for the first
  667.   character, and range upwards for further characters.
  668.  
  669.       parse var a 6 piece1 +3 piece2 +5 piece3
  670.  
  671.   The value of piece1 will be the three characters of a starting at
  672.   character 6; piece2 will be the next 5 characters, and piece3 will
  673.   be the rest of a.
  674.  
  675.   10. Interpret
  676.  
  677.   Suppose you have a variable "inst" which contains the string "a=a+1".  You
  678.   can execute that string as an instruction, by typing:
  679.  
  680.       interpret inst
  681.  
  682.   The interpret instruction may be used to accept Rexx instructions from
  683.   the user, or to assign values to variables whose names are not known in
  684.   advance.
  685.  
  686.       /* Input the name of a variable, and set that variable to 42 */
  687.       parse pull var
  688.       interpret var "=" 42
  689.  
  690.   11. The stack
  691.  
  692.   Rexx has a data stack, which is accessed via the "push", "queue" and
  693.   "pull" instructions.  The "pull" instruction (or in full, "parse pull")
  694.   inputs data from the user as we have seen before.  However, if there is
  695.   some data on the stack then it will pull that instead.
  696.  
  697.       /* Access the Rexx stack */
  698.       queue "Hello!"
  699.       parse pull a      /* a contains "Hello!" */
  700.       parse pull b      /* b is input from the user */
  701.       push "67890"
  702.       push "12345"
  703.       parse pull c      /* c contains "12345" */
  704.       /* there is one item left on the stack */
  705.  
  706.   The difference between "push" and "queue" is that when the items are
  707.   pulled off the stack, the items which were queued appear in the same
  708.   order that they were queued (FIFO, or first in, first out), and the items
  709.   which were pushed appear in reverse order (LIFO, or last in, first out).
  710.   If the queue contains a mixture of items which were pushed and items which
  711.   were queued, then those which were pushed will always appear first.
  712.  
  713.   The stack may be used to communicate data between REXX programs, or
  714.   between various subroutines within a REXX program (see the next section).
  715.   In certain circumstances, it may also be used to communicate data between
  716.   a REXX program and another program not written in REXX.
  717.  
  718.   On some systems, if a program finishes and returns to the operating
  719.   system while there are still items on the stack, then the operating
  720.   system will read and execute those items as if they had been typed on the
  721.   terminal.  However, on other systems the leftover items are just thrown
  722.   away.  Sometimes the items are even saved until the next REXX program is
  723.   executed.  It is good practice to ensure that the stack is empty before a
  724.   program returns control to the operating system (except, of course,
  725.   when the program has intentionally stacked a command for the system to
  726.   execute or a string for the next program to read).
  727.  
  728.   12. Subroutines and functions
  729.  
  730.   The following program defines an internal function, and calls it with
  731.   some data.  "Internal" just means the function is written in the same
  732.   file as the rest of the program.
  733.  
  734.       /* Define a function */
  735.       say "The results are:" square(3) square(5) square(9)
  736.       exit
  737.  
  738.       square: /* function to square its argument */
  739.       parse arg in
  740.       return in*in
  741.  
  742.   The output from this program should be: "The results are: 9 25 81"
  743.  
  744.   When Rexx finds the function call "square(3)", it searches the program
  745.   for a label called "square".  It finds the label on line 5 - the name
  746.   followed by a colon.  The interpreter executes the code which starts
  747.   at that line, until it finds the instruction "return".  While that code
  748.   is being executed, the arguments to the function can be determined with
  749.   "parse arg" in the same way as the arguments to a program.  When the
  750.   "return" instruction is reached, the value specified is evaluated and
  751.   used as the value of "square(3)".
  752.  
  753.   The "exit" instruction in this program causes it to finish executing
  754.   instead of running into the function.
  755.  
  756.   A function which takes multiple arguments may be defined, simply by
  757.   separating the arguments with a comma. That is, like this:
  758.  
  759.       /* Define a function with three arguments */
  760.       say "The results are:" conditional(5,"Yes","No") conditional(10,"X","Y")
  761.       exit
  762.  
  763.       conditional: /* if the first argument is less than 10 then return the
  764.                       second, else return the third.  */
  765.       parse arg c,x,y
  766.       if c<10 then return x
  767.       else return y
  768.  
  769.   A subroutine is similar to a function, except that it need not give a
  770.   value after the "return" instruction.  It is called with the "call"
  771.   instruction.
  772.  
  773.       /* Define a subroutine to print a string in a box, then call it */
  774.       call box "This is a sentence in a box"
  775.       call box "Is this a question in a box?"
  776.       exit
  777.   
  778.       box: /* Print the argument in a box */
  779.       parse arg text
  780.       say "+--------------------------------+"
  781.       say "|"centre(text,32)"|"             /* centre the text in the box */
  782.       say "+--------------------------------+"
  783.       return
  784.  
  785.   It is possible to call a function, even a built-in function, as if it
  786.   were a subroutine.  The result returned by the function is placed into
  787.   the variable called "result".
  788.  
  789.       /* print the date, using the "call" instruction */
  790.       call date "N"
  791.       say result
  792.  
  793.   If a function or subroutine does not need to use the variables which the
  794.   caller is using, or if it uses variables which the caller does not need,
  795.   then you can start the function with the "procedure" instruction.  This
  796.   clears all the existing variables away out of sight, and prepares for a
  797.   new set of variables.  This new set will be destroyed when the function
  798.   finishes executing.  The following program calculates the factorial of a
  799.   number recursively:
  800.  
  801.       /* Calculate factorial x, that is, 1*2*3* ... *x  */
  802.       parse pull x .
  803.       say x"!="factorial(x)
  804.       exit
  805.  
  806.       factorial: /* calculate the factorial of the argument */
  807.       procedure
  808.       parse arg p
  809.       if p<3 then return p
  810.       else return factorial(p-1) * p
  811.  
  812.   The variable p which holds the argument to funtion factorial is unaffected
  813.   during the calculation of factorial(p-1), because it is hidden by the
  814.   "procedure" instruction.
  815.  
  816.   If the subroutine or function needs access to just a few variables, then
  817.   you can use "procedure expose" followed by the list of variable names to
  818.   hide away all except those few variables.
  819.  
  820.   You can write functions and subroutines which are not contained in the
  821.   same Rexx program.  In order to do this, write the function and save it
  822.   into a file whose name will be recognised by the interpreter.  This type
  823.   of function is called an "external" function, as opposed to an "internal"
  824.   function which can be found inside the currently running program.
  825.  
  826. I If you want to call your function or subroutine using "call foobar" or
  827. I "foobar()", then you should save it in a file named "foobar.rexx" which
  828. I can be found in the current directory or in your path.
  829. O If you want to call your function or subroutine using "call foobar" or
  830. O "foobar()", then you should save it in a file named "foobar.cmd" which
  831. O can be found in the current directory or in your path.
  832.  
  833.   The "procedure" instruction is automatically executed before running
  834.   your external function, and so it should not be placed at the start of
  835.   the function.  It is not possible for an external function to access
  836.   any of its caller's variables, except by the passing of parameters.
  837.  
  838.   For returning from external functions, as well as the "return" instruction
  839.   there is "exit".  The "exit" instruction may be used to return any data to
  840.   the caller of the function in the same way as "return", but "exit" can be
  841.   used to return to the caller of the external function even when it is used
  842.   inside an internal function (which is in turn in the external function).
  843.   "exit" may be used to return from an ordinary Rexx program, as we have
  844.   seen.  In this case, a number may be supplied after "exit", which will
  845.   be used as the exit code of the interpreter.
  846.  
  847.   13. Executing commands
  848.  
  849.   Rexx can be used as a control language for a variety of command-based
  850.   systems.  The way that Rexx executes commands in these systems is
  851.   as follows.  When Rexx encounters a program line which is nether
  852.   an instruction nor an assignment, it treats that line as a string
  853.   expression which is to be evaluated and passed to the environment.
  854.   For example:
  855.  
  856.       /* Execute a given command upon a set of files */
  857.       parse arg command
  858.       command "file1"
  859.       command "file2"
  860.       command "file3"
  861.       exit
  862.  
  863.   Each of the three similar lines in this program is a string expression
  864.   which adds the name of a file (contained in the string constants) to the
  865.   name of a command (given as a parameter).  The resulting string is passed
  866.   to the environment to be executed as a command.  When the command has
  867.   finished, the variable "rc" is set to the exit code of the command.
  868.  
  869.   The environment to which a command is given varies widely between systems,
  870.   but in most systems you can select from a set of possible environments by
  871.   using the "address" instruction.
  872.   
  873.   14. Signal
  874.  
  875.   Where other programming languages have the "goto" command, Rexx has
  876.   "signal".  The instruction "signal label" makes the program jump to
  877.   the specified label (which is a name followed by a colon, the same as
  878.   is used to start an internal subroutine or function).  However, once
  879.   this has been done, it is not possible to resume any "select" or "do"
  880.   control structures that have recently been entered.  Thus the main use
  881.   of "signal" is to jump to an error handling routine when something goes
  882.   wrong, so that the program can clean up and exit.
  883.  
  884.   There is a much more useful way of using "signal", however.  That is
  885.   to trap certain kinds of error condition.  The conditions which may
  886.   be trapped include: "syntax" (that is, any syntax error), "error" (any
  887.   environment command that results in a non-zero exit code), "halt" (when
  888.   the user interrrupts execution) and "novalue" (which is when a symbol is
  889.   used without having been given a value).
  890.  
  891.   Error trapping for one of these conditions is turned on by
  892.  
  893.       signal on <condition>
  894.  
  895.   and is turned off by
  896.  
  897.       signal off <condition>
  898.  
  899.   When one of these conditions occurs, the program immediately signals to a
  900.   label whose name is the same as that of the condition.  Trapping is turned
  901.   off, so another "signal on" will be required if you want to continue to
  902.   trap that condition.
  903.  
  904.   If you wish for the program to signal to a label whose name is not the
  905.   same as that of the condition, then you may specify that label using the
  906.   "name" parameter of a "signal on" instruction, like this:
  907.  
  908.       signal on syntax name my_label
  909.  
  910.   Whenever a "signal" occurs, the variable "sigl" is set to the line number
  911.   of the instruction which caused the jump.  If the signal was due to an
  912.   error trap, then the variable "rc" will be set to an error code.
  913.  
  914.       /* This program goes on forever until someone stops it. */
  915. I     say "Press Control-C to halt"
  916. O     say "Press Control-C or Control-Break to halt"
  917.       signal on halt
  918.       do i=1
  919.          say i
  920.          do 10000
  921.          end
  922.       end
  923.  
  924.       halt:
  925.       say "Ouch!"
  926.       say "Died at line" sigl
  927.  
  928.  
  929.   15. Tracing
  930.  
  931. I Full details of how to use Rexx's tracing facility are contained in
  932. I rexx.ref.
  933. O More details of how to use Rexx's tracing facility can be found in the
  934. O OS/2 help system (help rexx trace).
  935.  
  936.   If a program goes wrong and you need more information in order to work out
  937.   why, then Rexx provides you with the ability to trace all or part of your
  938.   program to see what is happening.
  939.  
  940.   The most common form of tracing is turned on by
  941.  
  942.       trace r
  943.  
  944.   This causes each instruction to be listed before it is executed. Also, it
  945.   displays the results of each calculation after it has been found.
  946.  
  947.   Another useful trace command is:
  948.  
  949.       trace ?a
  950.  
  951.   This makes the interpreter list the next instruction and then stop.
  952.   You can continue to the next instruction by pressing return, or you
  953.   can type in some Rexx to be interpreted, after which the interpreter
  954.   will pause again.  You can use this to examine the program's variables
  955.   and so forth.
  956.  
  957.   If you want the interpreter to stop only when passing a label, use:
  958.  
  959.      trace ?l
  960.  
  961.   This is useful for setting breakpoints in the program, or for making the
  962.   program stop at a function call.
  963.