Monday, October 31, 2011

The Magic of TRANSLATE

TRANSLATE is typically used to clear unwanted characters from a string or to change a set of characters to some other set.  The syntactical description is that in

x = Translate( a , b , c )
each character in 'a' is searched for in 'c', and if found the corresponding character from 'b' replaces the character in 'a' on output.  Any characters in 'a' which are not found in 'c' are copied as-is to the output.  The default values for 'b' and 'c' are the uppercase alphabet and the lowercase alphabet, respectively, so that TRANSLATE, by default, will shift any string into uppercase.  This behavior can be harnessed for other purposes.

Among other things, TRANSLATE can rearrange the characters of one string to form a completely new and different arrangement.  (The technique shown here also works in PL/I where the syntax of the TRANSLATE function is exactly identical to REXX syntax.)  What's happening is often not immediately clear, but the code can be written to make it clear:

changed = Translate("CcYy/Mm/Dd" , chgdate , "CcYyMmDd")
The code surrounding this will make it fairly obvious that, going into the conversion, 'chgdate' has the form of a REXX date("S").  It becomes pretty easy to guess that the output form will have slashes inserted in the appropriate spots.  In effect,
CcYy/Mm/Dd  <--  CcYyMmDd
If that's not the format you need on output, a simple change provides whatever you want:
changed = Translate("Mm/Dd/Yy" , chgdate , "CcYyMmDd")
/*  Mm/Dd/Yy  <--  CcYyMmDd  */
comp_time = Translate("Hh:Mm:Ss" , comp_time , "HhMmSs")
/*  Hh:Mm:Ss  <--  HhMmSs   */

Just remember that when using TRANSLATE this way, the 'c' string describes the starting position of the 'b' string, and the 'a' string describes the desired result.  Naturally, the 'c' string may not have any duplicate characters.  While you can use any characters you want for 'c', it makes a lot of sense to use characters which give the reader/maintainer some clue as to what's intended.

No comments:

Post a Comment