Friday, November 18, 2011

ISPF Tables

Most of our uses of ISPF tables are very simple.  Every once in a while, however, we might bump into a relatively-more-complex situation where the uses are not so simple.  Without fail, such times are opportunities for us to learn some very difficult and painful lessons.  It's much better to learn them on a blog than while sitting before a terminal pumping code in a vain attempt to make a deadline.  The most difficult lesson is this: reading a table row populates any REXX variables that have matching names (and creates them otherwise).  This is most dangerous when you have to work with more than one table simultaneously.  Let me illustrate:

   address ISPEXEC 
   "TBSKIP ORDERS" /* sets vendor, product, date, qty, invoice */
   "TBGET  INVENT" /* keyed by 'product', sets qty, descrip */ 

The value for 'qty' from 'ORDERS' has been overlaid by 'qty' from 'INVENT'.  To preserve the original 'qty', it has to be copied to a different variable name.  Code-writing time is the wrong place to have to suddenly rename variables wholesale.  That is why I recommend that every table variable name should have a two-character prefix unique to the particular table:

   address ISPEXEC 
   "TBSKIP ORDERS" /* sets orvendr, orprod, ordate, orqty, orinvc */
   "TBVCLEAR INVENT"
   inprod = orprod
   "TBGET  INVENT" /* keyed by 'inprod', sets inqty, indesc */ 

There is now 'orqty' and 'inqty' and they can be compared, perhaps to see whether it's time to reorder.

Problem solved?  Hardly.  ISPF tables have more tricks up their sleeve(s).  Behold... extension variables.

Extension variables are unique to each row, and only the programmer exercising care in their naming can prevent clashes such as above.  As with ordinary table variables, extension variables also populate REXX variables when the row is read, and there is no warning that a simple TBSKIP may have clobbered other variables... unless the programmer is smart enough to ask if any extension variables were transferred with the rest of the row:

   "TBSKIP ORDERS SAVENAME(xvars)"
   parse var xvars  "("  xvars  ")"

which lets us know that 'ornotes', 'ormgrnam' and 'ormgrtel' were set without warning.  If we were to update that row without also commanding that those three extension variables be included in the update, they would simply disappear, also without warning.  It's a quick way to shoot holes in table data.  That's not us, thankfully.  We're smart enough to:

   "TBMOD   ORDERS  SAVE(" xvars ")"

thus preserving the data in those extension variables.

As with everything else, a few small proof-of-concept routines can be an invaluable learning aid, and (of course) you need to test the logic to death.

Thursday, November 17, 2011

Associative arrays

In REXX, arrays do not have to be indexed by numbers.  They can be indexed by anything... I think.  Certainly they can be indexed by names or other non-numeric tokens, and they certainly don't have to have values for every possibility.  Les Koehler calls these 'content addressible arrays' because it is data-content which serves as the index-value for the array.

It's common to see such arrays in matching routines where an array might be initialized to '0' and set to '1' for each of several dozen/hundred/thousand values as they are encountered in the course of processing data.  The value of the array-element tells us, in that case, whether or not we have encountered the index token before, or in the case of an actual counter, how many times we have encountered that token.  If you are, for instance, trying to eliminate duplicate data in a file and the duplicates might be scattered randomly throughout the data, this is just what the doctor ordered:

exists. = 0
do (over the entire input stream)
                  /* get the next token */
   if exists.token then iterate   /* discarding this input */
                  /* process this input data */
   exists.token = 1               /* discard all future */
end

This logic causes each token to be processed only the first time it is encountered.  All following occurrences are flushed.  If, instead, we wished to know how many of each token were present, the code would simply increment a counter each time the token were encountered.  However, in such a case, it will be nigh-on impossible to retrieve the counts at the end of processing unless the program has separately kept a list of the tokens it found, because the tokens could be anything... literally.

WARNING!  One aspect of content-addressible arrays has caused me endless grief because I continually forget the lesson so painfully learned the last time it happened.  To the extent those index-values are alphabetic, they are exclusively upper-case.  That is: if you set a value as

fullname.Tom  = "Tom Swift"

you must be careful when retrieving it that you specify the index-value as "TOM".  Stated another way, you cannot have separate values for 'fullname.Tom' and 'fullname.TOM'.  They occupy the same space.  Only the last set value will exist, and it will be indexed by 'TOM'.  It is a worthwhile 'exercise for the student' to write a small demonstration program to expose this behavior.

Wednesday, November 16, 2011

The Stack

The best part about REXX (after PARSE, of course) is the stack.  Knowing how to exploit the stack can save you mountains of trouble.  Once you get to appreciate the power of the stack, it opens doors to a world of capabilities.  Remember when we used to write line-mode dialogs: prompt then PULL the response?

say "Enter the dataset name:"
pull dsn

But you can't do that if there's already something on the stack.  You can't do that if there might be something on the stack.  Just in case, you should always phrase the above as

"NEWSTACK"
say "Enter the dataset name:"
pull dsn
"DELSTACK"

The same is true if you're dealing with a subroutine that returns its answer on the stack (my favorite mode of inter-module communication).  Let's say you have a subroutine that does some function for you and returns its result via the stack:

"NEWSTACK"
"CKSTATE" volid
pull state
if state = "MULT" then
   do queued()
      pull state   area
   parse value  volst.0+1   state  area    with,
                zz          volst.zz   1  volst.0  .
   end 
else volst.1 = state   "00"
"DELSTACK"

That is, if your subroutine returns more than one value, the first line of the returned stack is "MULT" and all the returned values follow.  If there's only one returned value, it's on line number 1.

The beauty of "NEWSTACK"/"DELSTACK" is that you can protect any material you've squirreled away against damage by other data that also needs to use the stack.  This is especially important when that 'other data' comes from the keyboard in response to a prompt.

Lastly, the use of "NEWSTACK"/"DELSTACK" guarantees that the current stack is empty.  If you want to be 100% sure you're getting a response from the keyboard and no place else, "NEWSTACK" is it.  When I want to put out multiple pages of data (HELP-text, for instance, or a screenful of output) and wait for the user's permission to go to the next page, I insert this line where I want to wait for the user to finish reading:

"NEWSTACK"; pull ; "CLEAR" ; "DELSTACK"

(Your installation may use some other routine to clear the screen.  Just substitute your local flavor.)

Saturday, November 12, 2011

How to empty a sequential dataset

If site security rules prevent you deleting and recreating a sequential dataset but you can write to it (in ACF2 terms, you are "READ(A) WRITE(A) ALLOC(P)"), you can still clear it of records.

"ALLOC FI($TMP) DA($TMP) SHR REU"
"EXECIO 0 DISKW $TMP (OPEN FINIS"
"FREE  FI($TMP)"

I'm about to run out of quick tips.  They'll either get longer and more elaborate (and thus lots less 'quick') or they're going to become fewer and not quite so 'daily'...

Thursday, November 10, 2011

Is it a Leap Year?

Well, really, the only reason we care is to know whether February has 28 days or 29 days, right?  Everything else is the same, because knowing that fact also tells us whether the year is 365 days long or 366.  So, the problem devolves to simply knowing the number of days in February, and that depends strictly upon the question 'what year is it?'.

   days.   = 31                        /* jan mar may jul aug oct dec*/
   days.04 = 30                        /* apr                        */
   days.06 = 30                        /* jun                        */
   days.09 = 30                        /* sep                        */
   days.11 = 30                        /* nov                        */
   days.02 = 28 + (ccyy//4=0) - (ccyy//100=0) + (ccyy//400=0)

(Presuming you have a 4-digit year available for the calculation)  the number of days in February is 28 plus...

One if the year is evenly divisible by 4  (ccyy//4 = 0),  unless...

The year is also evenly divisble by 100  (ccyy//100 = 0)  unless...

The year is also evenly divisble by 400  (ccyy//400 = 0)

Couldn't be simpler.  2000 was a leap year, and February had 28 + 1 - 1 + 1 (=29) days.  1900 was not a leap year;  it had 28 + 1 - 1 (=28) days.

Wednesday, November 9, 2011

Invoking an ISPF-dependent routine from READY

So you've written this peachy routine that uses all sorts of ISPF facilities.  It runs great from any command line just about anywhere within ISPF, but when you try invoking it from READY, it crashes because there is not an ISPF environment available.  You could simply start ISPF whenever you want to run it, run it from the primary option panel, and flush ISPF when it's done...

...or you could rig it so that it will run from READY as easily as it does from within ISPF.  That way, you never have to remember which of your routines need ISPF and which don't.  The ones that do will pave their own road ahead of their need for it.

WARNING: the code that follows presumes you have all the capability provided by REXXSKEL.  For more information about REXXSKEL and what it does, pop on over to my REXX page and take a look at the write-up titled "How To REXXSKEL".  Of particular interest in that regard is the subroutine SWITCH and the flow of control from the mainline to TOOLKIT_INIT through LOCAL_PREINIT.

TOOLKIT_INIT in a REXXSKEL-enabled routine sets, among other things, "sw.inispf" which tells us whether or not an ISPF environment exists.  (Yes, I know it should be "sw.0inispf", but REXXSKEL was built a long, long time ago in a galaxy far away...)  When an ISPF environment does not exist, we can generate one via ISPSTART, but we have to be prepared to rip it down when we're done with it.  During the early mainline of your well-structured program, you will need to restart the routine in a newly-invoked ISPF environment and to halt the current execution as soon as that restarted execution completes:

if /sw.inispf  then do                 /* after TOOLKIT_INIT return  */
   arg line
   line = line "((  RESTART"           /* tell the next invocation   */
   "ISPSTART CMD("exec_name line")"    /* Invoke ISPF...             */
   exit 4                              /* ...then bail out           */
   end

When the restarted routine ends, it should end with a non-zero return code to skip processing for any generated LOG or LIST datasets written by the newly-invoked ISPF environment:

if sw.0Restarted then,                 /* just after DUMP_QUEUE      */
   exit 4

To determine whether or not this execution was restarted, LOCAL_PREINIT (part of initialization, but customized routine by routine) has checked the parameter string for the presence of the token "RESTART":

   sw.0Restarted = SWITCH("RESTART")

That's it.  That's all there is to it.  When you fire this routine from READY, it discovers that it is not in ISPF, restarts itself (via ISPSTART).  The restarted invocation ends non-zero, and returns to its calling point in the original, whereupon the original exits back to the operating system.

Tuesday, November 8, 2011

RXVSAM — VSAM-enabling REXX routines

RXVSAM is a package originated by Mark Winges.  Mark is out of the programming game these days, preferring to devote his time to music, but he left behind a very useful piece of software that you can have for free.  It can be found on file 268 of the CBT Tape.  You will have to assemble the RXVSAM load module from its supplied source, but it doesn't have to be located in an authorized library, so anyone can have a VSAM-enabled REXX routine, and let me assure you that is something very useful to have on occasion.  What follows will be a very 'surface' treatment of RXVSAM just to illustrate how powerful it is.  It will not be a recitation of the RXVSAM manual. 

Once you have RXVSAM available to you as a callable load module, you have to make it available to your REXX routine:

   "LIBDEF ISPLLIB DATASET ID(...the loadlib with RXVSAM...) STACK"

and you have to allocate and open the VSAM dataset(s) you are going to work with:

   "ALLOC FI($VS) DA("ocompds") SHR REU"
   rxv_rc = RXVSAM("OPENINPUT","$VS","KSDS")

A word of warning:  RXVSAM is very fussy about its parameters.  They must be exactly the right length.  Quoted literals are best whenever possible.  With the dataset allocated and open, VSAM I/O operations may commence:

   rxv_rc = RXVSAM('READ','$VS',component,'AD0104')
   if rxv_rc > 0 then do               /* ...oops                    */
      sw.0error_found = 1
      end
   else do
      parse var ad0104  appl 9 component 19 currver 29 bits 30
      ...
      end

Here, a READ command is issued against a KSDS dataset previously opened as INPUT ($VS) using key 'component'.  The result of the READ is returned in variable AD0104.  Note carefully what is quoted and what is not quoted.

When the VSAM dataset is no longer needed, it must be closed by RXVSAM and FREEd:

   rxv_rc = RXVSAM("CLOSE","$VS")
   "FREE  FI($VS)"

and, of course, you must (eventually) release the LIBDEF for the RXVSAM library:

   "LIBDEF ISPLLIB"

Virtually anything you can do to or with a VSAM dataset in COBOL or PL/I you can now do in REXX.  If, for instance, an ISPF table has grown beyond the limits of practicality for tables, the data can be configured as a VSAM KSDS.  To service an inquiry, read-with-key in the VSAM KSDS, and load a selection of the dataset's records to a temporary ISPF table.  All the facilities for handling ISPF tables will then be available for use on that subset of the VSAM file — the best of both worlds.

I have a large number of examples of operations using RXVSAM.  If you have questions, feel free to drop me a line.