Table of Contents

Functions

A function is a program or group of statements that is executed whenever that function name is called in a particular context. A function may be part of an internal program, part of a library, or a separate external program. Functions are an important building block of modular programming because they allow you to construct large programs from a series of small, easily developed modules.

This chapter explains the different types of functions and how they are evaluated. It also provides an alphabetical reference of ARexx's built-in function library.

Invoking a Function

Within a ARexx program, a function is defined as a symbol or string followed immediately by an open parenthesis. The symbol or string (taken as a literal) specifies the function name, and the open parenthesis begins the argument list. Between the opening and closing parentheses are zero or more argument expressions, separated by commas, that supply the data being passed to the function.

Valid function calls are:

CENTER ('title', 20)
ADDRESS()
'ALLOCMEM' (256*4,1)

Each argument expression is evaluated in turn and the resulting strings are passed as the argument list to the function. Each argument expression, while often just a single literal value, can include arithmetic or string operations or even other function calls. Argument expressions are evaluated from left to right.

Functions can also be invoked using the CALL instruction. The CALL instruction, described in Chapter 4, can be used to invoke a function that may not return a value.

Types of Functions

There are three types of functions:

Internal Functions

An internal function is identified by a label within the program. When the internal function is called. ARexx creates a new storage environment so that the previous caller's environment is preserved. The new environment inherits the values from its predecessor, but subsequent changes to the environment variables do not affect the previous environment.

The specific values preserved are:

The new environment does not automatically get a new symbol table, so initially all of the variables in the previous environment are available to the called function. The PROCEDURE instruction can be used to create a table and thereby protect the caller's symbol values. PROCEDURE can also be used to allow the same variable name to be used in two different areas with two different values.

Execution of the internal function proceeds until a RETURN instruction is executed. At this point the new environment is dismantled, and control resumes at the point of the function call. The expression supplied with the RETURN instruction is evaluated and passed back to the caller as the function result.

Built-In Functions

ARexx provides a substantial library of predefined functions as part of the language system. These functions are always available and have been optimized to work with the internal data structures. In general, the built-in functions execute much faster than an equivalent interpreted function, so their usage is strongly recommended.

Several of the built-in functions create and manipulate external AmigaDOS files. Files are referenced by a logical name, a case-sensitive name that is assigned to a file when it is first opened. The initial input and output streams are given the names STDIN (standard input) and STDOUT (standard output). There is no theoretical limit to the number of files that may be open simultaneously, although a limit will be imposed by available memory. All open files are closed automatically when the program exits.

External Function Libraries

A function library is a collection of one or more functions organized as an Amiga shared library. The library must reside in LIBS:, but may be either memory or disk-resident. Disk-resident libraries are loaded and opened as needed.

The library has to be especially tailored for use by ARexx. Each function library must contain a library name, a search priority, an entry point offset, and a version number. When ARexx is searching for a function, the interpreter opens each library and checks its "query" entry point. This entry point must be specified as an integer offset (e.g. "-30") from the library base. The return code from the query call indicates whether the desired function was found. If the function is found, it is called with the parameters passed by the interpreter, and the function result is returned to the caller. If it is not found, a "Function not found" error code is returned, and the search continues with the next library in the list. Function libraries are always closed after being checked so that the operating system can reclaim the memory space if required.

The Library List

The ARexx resident process maintains a list of the currently available function libraries and function hosts called the Library List. Application programs can add or remove function libraries as required.

The Library List is maintained as a priority-sorted queue. Each entry has an associated search priority in the range 100 (highest) to -100 (lowest). Entries can be added at an appropriate priority to control the function name resolution. Libraries with higher priorities are searched first. Within a given priority level, those libraries added first are searched first. The priority levels are significant if any of the libraries have duplicate function name definitions, since the function located further down the search chain could never be called.

External Function Hosts

The name associated with a function host is the name of its public message port. Function calls are passed to the host as a message packet; it is then up to the individual host to determine whether the specified function name is one that it recognizes. The name resolution is completely internal to the host, so function hosts provide a natural gateway mechanism for implementing remote procedure calls to other machines in a network. The ARexx resident process is a function host and is installed in the Library List with a priority of -60.

The Search Order

Function linkages in ARexx are established at the time of the function call. A specific search order is followed until a function matching the name symbol or string is found. If the specified function cannot be located, an error is generated and the expression evaluation is terminated. The full search order is:

  1. Internal Functions - The program source is examined for a label that matches the function name. If a match is found, a new storage environment is created and control is transferred to the label.
  2. Built-In Functions - The built-in function library is searched for the specified name. All of these functions are defined by uppercase names.
  3. Function Libraries and Function Hosts - The available function libraries and function hosts are maintained in the Library List, which is searched starting at the highest priority until the requested function is found or the end of the list is reached. Function hosts are called using a message-passing protocol similar to that used for commands and may be used as gateways for remote procedure calls to other machines in a network.
  4. External ARexx Programs - The final search step is to check for an external ARexx program file by sending an invocation message to the ARexx resident process. The search always begins in the current directory and follows the same search path as the original ARexx program invocation. The name matching process is not case-sensitive.

The function name-matching procedure may be case-sensitive for some of the search steps, but not for others. The matching procedure used in a function library or function host is design dependent. Functions defined with mixed-case names must be called using a string token, since symbol names are always translated to uppercase.

The full search order is followed whenever the function name is defined by a symbol token. However, the search for internal functions is bypassed if the name is specified by a string token. This allows internal functions to usurp the names of external functions, as in the following example:

CENTER: /*internal "CENTER"*/
ARG string, length /*get arguments*/
length = MIN(length,60) /*compute length*/
return 'CENTER' (string, length)

Here the built-in function CENTER() has been replaced by an internal function after modifying the length argument.

The Clip List

The Clip List is a publicly accessible mechanism that can be used as a general clipboard for intertask communication. Many functions use the clipboard for retrieving different types of information, such as predefined constants or strings.

The Clip List maintains a set of (name, value) pairs that may be used for a variety of purposes. (SETCLIP() is used to add pairs to the list.) Each entry in the list consists of a name and a value string and may be located by name. In general, the names used should be chosen to be unique to an application to prevent unintended duplications with other programs. Any number of entries may be posted to the list.

One potential application for the Clip List is as a mechanism for loading predefined constants into an ARexx program. For example:

pi=3.14159; e=2.718; sqrt2=1.414 . . .

(i.e., a series of assignments separated by semicolons). In use, such a string could be retrieved by name using the built-in function GETCLIP() and then INTERPRETed within the program. The assignment statements within the string would then create the required constant definitions. For example:

/*Assume a string called "numbers" is available*/
numbers = GETCLIP ('numbers')
INTERPRET numbers /*. . . assignments*/

The strings would not be restricted to contain only assignment statements, but could include any valid ARexx statements. The Clip List could thus provide a series of programs for initializations or other processing tasks.

The resident process supports addition and deletion operations for maintaining the Clip List. The names in the (name,value) pairs are assumed to be in mixed case and are maintained to be unique in the list. An attempt to add a string with an existing name will simply update the value string. The name and value strings are copied when an entry is posted to the list, so the program that adds an entry is not required to maintain the strings.

Entries posted to the Clip List remain available until explicitly removed. The Clip List is automatically released when the resident process exits.

Built-in Functions Reference

This section provides an alphabetical list of the built-in functions. The syntax of each function is shown to the right of the function keyword.

Syntax

Optional arguments are shown in brackets and generally have a default value that is used if the argument is omitted. When an option keyword is specified as an argument, only the first character is significant. Option keywords are not case-sensitive.

Many functions accept a pad character argument. Pad characters are inserted to fill or create spaces. For functions that accept a pad argument, only the first character of the argument string is significant. If a null string is supplied, the default padding character, usually a blank, will be used.

In the following examples, an arrow (→) is used as an abbreviation for "evaluates as." The arrow will not be displayed when a program is run. For example:

SAY ABS (-5.35) -> 5.35

This means that ABS(-5.35) is evaluated as 5.35.

Alphabetical Reference

ABBREV()

ABBREV(string1,string2[,length])

Returns a Boolean value that indicates whether string2 is an abbreviation of string1 with length greater than or equal to the specified length argument. The default length is 0, so the null string is an acceptable abbreviation. For example:

SAY ABBREV ('fullname', 'ful') -> 1
SAY ABBREV ('almost', 'alm',4) -> 0
SAY ABBREV ('any','') -> 1 

ABS()

ABS(number)

Returns the absolute value of the number argument. This value must be numeric. For example:

SAY ABS(-5.35) -> 5.35
SAY ABS(10) -> 10

ADDLIB()

ADDLIB(name,priority[,offset,version])

Adds a function library or a function host to the library list maintained by the resident process. The name argument specifies either the name of a function library or the public message port associated with a function host. The name is case-sensitive. Any specified libraries should reside in the system LIBS: directory.

The priority argument specifies the search priority and must be an integer between 100 and -100, inclusive. The offset and version arguments apply only to libraries. The offset is the integer offset to the library's "query" entry point, and the version is an integer specifying the minimum acceptable release level of the library.

The function returns a Boolean result that indicates whether the operation was successful. If a library is specified, it is not actually opened at this time. Similarly, ARexx does not check to see whether a specified function host port is open. For example:

SAY ADDLIB ("rexxsupport.library",0,-30,0) -> 1
CALL ADDLIB "EtherNet",-20 /*A gateway*/ 

ADDRESS()

ADDRESS()

Returns the current host address string. The host address is the message port to which commands will be sent. The SHOW() function can be used to check whether the required external host is actually available. See also SHOW(). For example:

SAY ADDRESS() -> REXX 

ARG()

ARG([number][,'EXISTS'|'OMITTED'])

ARG() returns the number of arguments supplied to the current environment. If only the number parameter is supplied, the corresponding argument string is returned. If a number and the Exists or Omitted keyword is given, the Boolean return indicates the status of the corresponding argument. The existence or omission test does not indicate whether the string has a null value, but only whether a string was supplied. For example:

/*Assume arguments were: ('one',,10)*/
SAY ARG() -> 3
SAY ARG(1) -> one
SAY ARG(2,'O') -> 1 

B2C()

B2C(string)

Converts a string of binary digits (0,1) into the corresponding (packed) character representation. The conversion is the same as though the argument string had been specified as a literal binary string (e.g. '1010'B). Blanks are permitted in the string, but only at byte boundaries. This function is particularly useful for creating strings that are to be used as bit masks. See also X2C(). For example:

SAY B2C('00110011') -> 3
SAY B2C('01100001') -> a

BITAND()

BITAND(string1,string2[,pad])

The argument strings are logically ANDed together, with the length of the result being the longer of the two operand strings. If a pad character is supplied, the shorter string is padded on the right. Otherwise, the operation terminates at the end of the shorter string, and the remainder of the longer string is appended to the result. For example:

BITAND('0313'x, 'FFF0'x) -> '0310'x 

BITCHG()

BITCHG(string,bit)

Changes the state of the specified bit in the argument string. Bit numbers are defined such that bit 0 is the low-order bit of the rightmost byte of the string. For example:

BITCHG('0313'x,4) -> '0303'x 

BITCLR()

BITCLR(string,bit)

Clears (sets to zero) the specified bit in the argument string. Bit numbers are defined such that bit 0 is the low-order bit of the rightmost byte of the string. For example:

BITCLR('0313'x,4) -> '0303'x 

BITCOMP()

BITCOMP(string1,string2[,pad])

Compares the argument strings bit-by-bit, starting at bit number 0. The returned value is the bit number of the first bit in which the strings differ, or -1 if the strings are identical. For example:

BITCOMP('7F'x, 'FF'x) -> 7 /*Seventh bit*/
BITCOMP('FF'x, 'FF'x) -> -1 

BITOR()

BITOR(string1,string2[,pad])

The argument strings are logically ORed together, with the length of the result being the longer of the two operand strings. If a pad character is supplied, the shorter string is padded on the right. Otherwise, the operation terminates at the end of the shorter string, and the remainder of the longer string is appended to the result. For example:

BITOR('0313'x, '00F'x) -> '033F'x 

BITSET()

BITSET(string,bit)

Sets the specified bit in the argument string to 1. Bit numbers are defined such that bit 0 is the low-order bit of the rightmost byte of the string. For example:

BITSET('313'x,2) -> '0317'x 

BITTST()

BITTST(string,bit)

The Boolean return indicates the state of the specified bit in the argument string. Bit numbers are defined such that bit 0 is the low-order bit of the rightmost byte of the string. For example:

BITTST('0313=x,4) -> 1 

BITXOR()

BITXOR(string1,string2[,pad])

The argument strings are logically and exclusively-ORed together, with the length of the result being the longer of the two operand strings. If a pad character is supplied, the shorter string is padded on the right. Otherwise, the operation terminates at the end of the shorter string, and the remainder of the longer string is appended to the result. For example:

BITXOR('0313'x, '001F'x) -> '030C'X 

C2B()

C2B(string)

Converts the character string into the equivalent string of binary digits. See also C2X(). For example:

SAY C2B('abc') -> 011000010110001001100011

C2D()

C2D(string[,n])

Converts the string argument from its character representation to the corresponding decimal number, expressed as ASCII digits (0-9). If n is supplied, the character string is considered to be a number expressed in n bytes. The string is truncated or padded with nulls on the left as required, and the sign bit is extended for the conversion. For example:

SAY C2D('0020'x) -> 32
SAY C2D('FFFF ffff'x) -> -1
SAY C2D('FF0100'x,2) -> 256

C2X()

C2X(string)

Converts the string argument from its character representation to the corresponding hexadecimal number, expressed as the ASCII characters 0-9A-Fa-f. See also C2B(). For example:

SAY C2X('abc') -> 616263 

CENTER()/CENTRE()

CENTER(string,length[,pad])
CENTRE(string,length[,pad])

Centers the string argument in a string with the specified length. If the length is longer than that of the string, pad characters or blanks are added as necessary. For example:

SAY CENTER('abc',6) -> ' abc '
SAY CENTER('abc',6,'+') -> '+abc++'
SAY CENTER ('123456',3) -> '234' 

CLOSE()

CLOSE(file)

Closes the file specified by the given logical name. The returned value is a Boolean success flag and will be 1 unless the specified file was not open. For example:

SAY CLOSE('input') -> 1

COMPARE()

COMPARE(string1,string2[,pad])

Compares two strings and returns the index of the first position in which they differ or 0 if the strings are identical. The shorter string is padded as required using the supplied character or blanks. For example:

SAY COMPARE('abcde', 'abcce') -> 4
SAY COMPARE('abcde', 'abcde') -> 0
SAY COMPARE('abc++', 'abc+-', '+') -> 5 

COMPRESS()

COMPRESS(string[,list])

If the list argument is omitted, the function removes leading, trailing or embedded blank characters from the string argument. If the optional list is supplied, it specifies the characters to be removed from the string. For example:

SAY COMPRESS(' why not ') -> whynot
SAY COMPRESS('++12-34-+', '+-') -> 1234

COPIES()

COPIES(string,number)

Creates a new string by concatenating the specified number of copies of the original. The number argument may be zero, in which case the null string is returned. For example:

SAY COPIES('abc',3) -> abcabcabc 

D2C()

D2C(number)

Creates a string whose value is the binary (packed) representation of the given decimal number. For example:

D2C(65) -> A 

D2X()

D2X(number[,digits])

Converts a decimal number to hexadecimal. For example:

D2X(31) -> 1F 

DATATYPE()

DATATYPE(string[,option])

If only the string argument is specified, DATATYPE() tests whether the string parameter is a valid number and returns either NUM or CHAR. If an option keyword is given, the Boolean return indicates whether the string satisfied the requested test. The following option keywords are recognized:

For example:

SAY DATATYPE('123') -> NUM
SAY DATATYPE('1a f2', 'X') -> 1
SAY DATATYPE('aBcde', 'L') -> 0 

DATE()

DATE([option][,date][format])

Returns the current date in the specified format. The default (NORMAL) option returns the date in the form DD MMM YYYY, as in 20 APR 1988. The options recognized are:

These options can be shortened to just the first character.

The DATE() function also accepts optional second and third arguments to supply the date either in the form of internal system days or in the "sorted" form YYYYMMDD. The second argument is specifying either system days (the default) or a sorted date. The third argument specifies the form of the date and can be either 'I' or 'S'. The current date in system days can be retrieved using DATE('INTERNAL'). For example:

SAY DATE() -> 14 Jul 1992
SAY DATE('M') -> July
SAY DATE(S) -> 19920714
SAY DATE('S' ,DATE('I')+21) -> 19920804
SAY DATE('W' ,19890609, 'S') -> Friday 

DELSTR()

DELSTR(string,n[,length])

Deletes the substring of the string argument beginning with the n-th character for the specified length in characters. The default length is the remaining length of the string. For example:

SAY DELSTR('123456',2,3) -> 156

DELWORD()

DELWORD(string,n[,length])

Deletes the substring of the string argument beginning with the nth word for the specified length in words. The default length is the remaining length of the string. The deleted string includes any trailing blanks following the last word. For example:

SAY DELWORD('Tell me a story',2,2) -> 'Tell story'
SAY DELWORD('one two three',3) -> 'one two ' 

DIGITS()

DIGITS()

Returns the current Numeric Digits setting. For example:

NUMERIC DIGITS 6
SAY DIGITS() -> 6

EOF()

EOF(file)

Checks the specified logical file name and returns the Boolean value 1 (True), if the end-of-file has been reached, and 0 (False) otherwise. For example:

SAY EOF(infile) -> 1 

ERRORTEXT()

ERRORTEXT(n)

Returns the error message associated with the specified ARexx error code. The null string is returned if the number is not a valid error code. For example:

SAY ERRORTEXT(41) -> Invalid expression 

EXISTS()

EXISTS(filename)

Tests whether an external file of the given filename exists. The name string may include device and directory specifications. For example:

SAY EXISTS('SYS:C/ED') -> 1 

EXPORT()

EXPORT(address[,string][,length][,pad])

Copies data from the optional string into a previously-allocated memory area. This memory area must be specified as a four-byte address. The length parameter specifies the maximum number of characters to be copied. The default is the length of the string. If the specified length is longer than the string, the remaining area is filled with the pad character or nulls ('00'x). The returned value is the number of characters copied.

Any area of memory can be overwritten, possibly causing a system crash. Task switching is forbidden while the copy is being done, so system performance may be degraded if long strings are copied.

See also IMPORT() and STORAGE(). For example:

count = EXPORT('0004 0000'x, 'The answer') 

FIND()

FIND(string,phrase)

The FIND() function locates a phrase of words in a larger string of words and returns the word number of the matched position. For example:

SAY FIND('Now is the time', 'is the') -> 2

FORM()

FORM()

Returns the current NUMERIC FORM setting. For example:

NUMERIC FORM SCIENTIFIC
SAY FORM() -> SCIENTIFIC 

FREESPACE()

FREESPACE(address,length)

Returns a block of memory of a given length to the interpreter's internal pool. The address argument must be a 4 byte string obtained by a prior call to GETSPACE(), the internal allocator. It is not always necessary to release internally allocated memory, since it will be released to the system when the program terminates. However, if a very large block has been allocated, returning it to the pool may avoid memory space problems. The return value is a Boolean success flag. See also GETSPACE().

Calling FREESPACE() with no arguments will return the amount of memory available in the interpreter's internal pool. For example:

FREESPACE('00042000'x,32) -> 1 

FUZZ()

FUZZ()

Returns the current NUMERIC FUZZ setting. For example:

NUMERIC FUZZ 3
SAY FUZZ() -> 3

GETCLIP()

GETCLIP(name)

Searches the Clip List for an entry matching the supplied name parameter and returns the associated value string. The name matching is case-sensitive. The null string is returned if the name cannot be found. See also SETCLIP(). For example:

/*Assume 'numbers' contains 'PI=3.14159'*/
SAY GETCLIP('numbers') -> PI=3.14159 

GETSPACE()

GETSPACE(length)

Allocates a block of memory of the specified length from the interpreter's internal pool. The returned value is the four-byte address of the allocated block, which is not cleared or otherwise initialized. Internal memory is automatically returned to the system when the ARexx program terminates, so this function should not be used to allocate memory for use by external programs. The REXXSupport.Library includes the function ALLOCMEM(), which allocates memory from the system free list. See also FREESPACE(). For example:

SAY C2X (GETSPACE(32)) -> '0003BF40'x 

HASH()

HASH(string)

Returns the hash attribute of a string as a decimal number and updates the internal hash value of the string. For example:

SAY HASH('1') -> 49

IMPORT()

IMPORT(address[,length])

Creates a string by copying data from the specified four-byte address. If the length parameter is not supplied, the copy terminates when a null byte is found. See also EXPORT(). For example:

extval = IMPORT('0004 0000'x,8) 

INDEX()

INDEX(string,pattern[,start])

Searches for the first occurrence of the pattern argument in the string argument, beginning at the specified start position. The default start position is 1. The returned value is the index of the matched pattern or 0 if the pattern was not found. For example:

SAY INDEX("123456", "23") -> 2
SAY INDEX("123456", "77") -> 0
SAY INDEX("123123", "23",3) -> 5

INSERT()

INSERT(new,old[,start][,length][,pad])

Inserts the new string into the old string after the specified start position. The default starting position is 0. The new string is truncated or padded to the specified length as required, using the supplied pad character or blanks. If the start position is beyond the end of the string, the old string is padded on the right. For example:

SAY INSERT('ab', '12345') -> ab12345
SAY INSERT('123', '++',3,5, '-') -> ++-123-- 

LASTPOS()

LASTPOS(pattern,string[,start])

Searches backwards for the first occurrence of the pattern argument in the string argument, beginning at the specified start position. The default starting position is the end of the string. The returned value is the index of the matched pattern or 0 if the pattern was not found. For example:

SAY LASTPOS('2', '1234') -> 2
SAY LASTPOS('2', '1234234') -> 5
SAY LASTPOS('2', '123234',3) -> 2
SAY LASTPOS('2', '13579') -> 0

LEFT()

LEFT(string,length[,pad])

Returns the leftmost substring in the given string argument with the specified length. If the substring is shorter than the requested length, it is padded on the right with the supplied pad character or blanks. For example:

SAY LEFT('123456',3) -> 123
SAY LEFT('123456',8, '+') -> 123456++

LENGTH()

LENGTH(string)

Returns the length of the string. For example:

SAY LENGTH('three') -> 5 

LINES()

LINES(file)

Returns the number of lines queued or typed ahead at the logical file, which must refer to an interactive stream. The line count is obtained as the secondary result of a WaitForChar() call. For example:

PUSH 'a line'
PUSH 'another one'
SAY LINES(STDIN) -> 2

MAX()

MAX(number,number[,number,...])

Returns the maximum of the supplied arguments, all of which must be numeric. At least two parameters must be supplied. For example:

SAY MAX(2.1,3,-1) -> 3 

MIN()

MIN(number,number[,number,...])

Returns the minimum of the supplied arguments, all of which must be numeric. At least two parameters must be supplied. For example:

SAY MIN(2.1,3,-1) -> -1 

OPEN()

OPEN(file,filename[,'APPEND'|'READ'|'WRITE'])

Opens an external file for the specified operation. The file argument defines the logical name by which the file will be referenced. STDIN and STDOUT are logical files that are available by default. The filename is the external name of the file and may include device and directory specifications. The function returns a Boolean value that indicates whether the operation was successful. There is no limit to the number of files that can be open simultaneously, and all open files are closed automatically when the program exits. See also CLOSE(), READ(), and WRITE(). For example:

SAY OPEN('MyCon', 'CON:160/50/320/100/MyCON/cds') -> 1
SAY OPEN('outfile', 'ram:temp', 'W') -> 1

OVERLAY()

OVERLAY(new,old[,start][,length][,pad])

Overlays the new string onto the old string beginning at the specified start position, which must be positive. The default starting position is 1. The new string is truncated or padded to the specified length as required, using the supplied pad character or blanks. If the start position is beyond the end of the old string, the old string is padded on the right. For example:

SAY OVERLAY('bb', 'abcd') -> bbcd
SAY OVERLAY('4', '123',5,5, '-') -> 123-4---- 

POS()

POS(pattern,string[,start])

Searches for the first occurrence of the pattern argument in the string argument, beginning at the position specified by the start argument. The default starting position is 1. The value is the index of the matched string or 0 if the pattern wasn't found. For example:

SAY POS('23', '123234') -> 2
SAY POS('77', '123234') -> 0
SAY POS('23', '123234',3) -> 4 

PRAGMA()

PRAGMA(option[,value])

This function allows a program to change various attributes relating to the system environment within which the program executes. The option argument is a keyword that specifies an environmental attribute. The value argument supplies the new attribute value to be installed. The value returned by the function depends on the attribute selected. Some attributes return the previous value installed, while others may simply set a Boolean success flag.

The currently defined option keywords are:

The currently implemented options are:

SAY PRAGMA('D', 'DF0:C') -> Extras
SAY PRAGMA('D', 'DF1:C') -> Workbench:C
SAY PRAGMA('PRIORITY', -5) -> 0
SAY PRAGMA('ID') -> 00221ABC
CALL PRAGMA '*',STDOUT
SAY PRAGMA("STACK",8092) -> 4000 

RANDOM()

RANDOM([MIN][,MAX][,seed])

Returns a pseudo-random integer in the interval specified by the min and max arguments. The default minimum value is 0 and the default maximum value is 999. The interval max-min must be less than or equal to 1000. If a greater range of random integers is required, the values from the RANDU() function can be suitably scaled and translated. The seed argument can be supplied to initialize the internal state of the random number generator. See also RANDU(). For example:

thisroll = RANDOM(1,6) /*Might be 1*/
nextroll = RANDOM(1,6) /*Might be snake eyes*/ 

RANDU()

RANDU([seed])

Returns a uniformly-distributed, pseudo-random number between 0 and 1. The number of digits of precision in the result is always equal to the current Numeric Digits setting. With the choice of suitable scaling and translation values, RANDU() can be used to generate pseudo-random numbers on an arbitrary interval.

The optional integer seed argument is used to initialize the internal state of the random number generator. See also RANDOM(). For example:

firsttry = RANDU() /*0.371902021?*/
NUMERIC DIGITS 3
tryagain = RANDU () /*0.873?*/ 

READCH()

READCH(file,length)

Reads the specified number of characters from the given logical file into a string. The length of the returned string is the actual number of characters read and may be less than the requested length if, for example, the end-of-file was reached. See also READLN(). For example:

instring = READCH('input',10)

READLN()

READLN(file)

Reads characters from the given logical file into a string until a newline character is found. The returned string does not include the newline. See also READCH(). For example:

instring = READLN('MyFile') 

REMLIB()

REMLIB(name)

Removes an entry with the given name from the Library List maintained by the resident process. The Boolean return is 1 if the entry was found and successfully removed. This function does not make a distinction between function libraries and function hosts, but simply removes a named entry. See also ADDLIB(). For example:

SAY REMLIB('MyLibrary.library') -> 1

REVERSE()

REVERSE(string)

Reverses the sequence of characters in the string. For example:

SAY REVERSE('?ton yhw') -> why not?
RIGHT(string,length[,pad])

Returns the rightmost substring in the given string argument with the specified length. If the substring is shorter than the requested length, it is padded on the left with the supplied pad character or blanks. For example:

SAY RIGHT('123456',4) -> 3456
SAY RIGHT('123456',8, '+') -> ++123456

SEEK()

SEEK(file,offset[,'BEHIN'|'CURRENT'|'END'])

Moves to a new position in the given logical file, specified as an offset from an anchor position. The default anchor is Current. The returned value is the new position relative to the start of the file. For example:

SAY SEEK('input',10,'B') -> 10
SAY SEEK('input',0,E') -> 356 /*file length*/

SETCLIP()

SETCLIP(name[,value])

Adds a name-value pair to the Clip List maintained by the resident process. If an entry of the same name already exists, its value is updated to the supplied value string. Entries may be removed by specifying a null value. The function returns a Boolean value that indicates whether the operation was successful. For example:

SAY SETCLIP('path', 'DF0:s') -> 1
SAY SETCLIP('path') -> 1 

SHOW()

SHOW(option[,name][,pad])

Returns the names in the resource list specified by the option argument, or tests to see whether an entry with the specified name is available. The currently implemented options keywords are:

If the name argument is omitted, the function returns a string with the resource names separated by a blank space or the pad character, if one was supplied. If the name argument is given, the returned Boolean value indicates whether the name was found in the resource list. The name entries are case-sensitive.

SIGN()

SIGN(number)

Returns 1 if the number argument is positive or zero and -1 if the number is negative. The argument must be numeric. For example:

SAY SIGN(12) -> 1
SAY SIGN(-33) -> -1

SOURCELINE()

SOURCELINE([line])

Returns the text for the specified line of the currently executing ARexx program. If the line argument is omitted, the function returns the total number of lines in the file. This function is often used to embed "help" information in a program. For example:

/*A simple test program*/
SAY SOURCELINE() -> 3
SAY SOURCELINE(1)-> /*A simple test program*/

SPACE()

SPACE(string,n[,pad])

Reformats the string argument so that there are n spaces (blank characters) between each pair of words. If the pad character is specified, it is used instead of blanks as the separator character. Specifying n as 0 will remove all blanks from the string. For example:

SAY SPACE('Now is the time',3) -> 'Now is the time'
SAY SPACE('Now is the time',0) -> 'Nowisthetime'
SAY SPACE('1 2 3',1, '+') -> '1+2+3' 

STORAGE()

STORAGE([address][,string][,length][,pad])

STORAGE() with no arguments returns the available system memory. If the address argument is given, it must be a four-byte string. The function copies data from the (optional) string to the indicated memory address. The length parameter specifies the maximum number of bytes to be copied and defaults to the length of the string. If the specified length is longer than the string, the remaining area is filled with the pad character or nulls ('00'x).

The returned value is the previous contents of the memory area. This can be used in a subsequent call to restore the original contents. See also EXPORT().

Any area of memory can be overwritten, possibly causing a system crash. Task switching is forbidden while the copy is being done, so system performance may be degraded if long strings are copied.

For example:

SAY STORAGE() -> ' 248400
oldval = STORAGE('0004 0000'x, 'The answer')
CALL STORAGE '0004 0000'x,,32, '+' 

STRIP()

STRIP(string[,{'B' | 'L' | 'T'}][,pad])

If neither of the optional parameters is supplied, the function removes both leading and trailing blanks from the string argument. The second argument specifies whether Leading, Trailing or Both (leading and trailing) characters are to be removed. The optional pad (or unpad) argument selects the character to be removed. For example:

SAY STRIP(' say what? ') -> 'say What?'
SAY STRIP(' say what? ','L') -> 'say what?
SAY STRIP('++123+++', 'B', '+') -> '123' 

SUBSTR()

SUBSTR(string,start[,length][,pad])

Returns the substring of the string argument beginning at the specified start position for the specified length. The starting position must be positive, and the default length is the remaining length of the string. If the substring is shorter than the requested length, it is padded on the right with the blanks or the specified pad character. For example:

SAY SUBSTR('123456',4,2) -> 45
SAY SUBSTR('myname',3,6, '=') -> 'name=='

SUBWORD()

SUBWORD(string,n[,length])

Returns the substring of the string argument beginning with the nth word for the specified length in words. The default length is the remaining length of the string. The returned string will never have leading or trailing blanks. For example:

SAY SUBWORD('Now is the time ',2,2) -> 'is the' 

SYMBOL()

SYMBOL(name)

Tests whether the name argument is a valid ARexx symbol. If the name is not a valid symbol, the function returns the string BAD. If the symbol is uninitialized, the returned string is LIT. If the symbol has been assigned a value, VAR is returned. For example:

SAY SYMBOL('J') -> VAR
SAY SYMBOL('x') -> LIT
SAY SYMBOL('++') -> BAD 

TIME()

TIME(option)

Returns the current system time or controls the internal elapsed time counter. The valid option keywords are:

If no option is specified, the function returns the current system time in the form HH:MM:SS. For example:

/*Suppose that the time is 1:02 AM . . .*/
SAY TIME('C'( -> 1:02 AM
SAY TIME('HOURS') -> 1
SAY TIME('M') -> 62
SAY TIME('N') -> 01:02:54
SAY TIME('S') -> 3720
call TIME('R') /*reset timer*/
SAY TIME('E') -> .020
SAY TIME() -> 01:02:00 

TRACE()

TRACE(option)

Sets the tracing mode (see Chapter 6) to that specified by the option keyword, which must be one of the valid alphabetic or prefix options. The TRACE() function will alter the tracing mode even during interactive tracing, when TRACE instructions in the source program are ignored. The returned value is the mode in effect before the function call. This allows the previous trace mode to be restored later. For example:

/*Assume tracing mode is ?ALL*/
SAY TRACE('Results') -> ?A

TRANSLATE()

TRANSLATE(string[,output][,input][,pad])

This function constructs a translation table and uses it to replace selected characters in the argument string. If only the string argument is given, it is translated to upper case. If an input table is supplied, it modifies the translation table so that characters in the argument string that occur in the input table are replaced with the corresponding character in the output table. Characters beyond the end of the output table are replaced with the specified pad character or a blank. The result string is always of the same length as the original string. The input and output tables may be of any length. For example:

SAY TRANSLATE("abcde", "123", "cbade", "+") -> 321++
SAY TRANSLATE("low") -> LOW
SAY TRANSLATE("0110", "10", "01") -> 1001 

TRIM()

TRIM(string)

Removes trailing blanks from the string argument. For example:

SAY length (TRIM(' abc ')) -> 4 

TRUNC()

TRUNC(number[,places])

Returns the integer part of the number argument followed by the specified number of decimal places. The default number of decimal places is 0. The number is padded with zeroes as necessary. For example:

SAY TRUNC(123.456) -> 123
SAY TRUNC(123.456,4) -> 123.4560 

UPPER()

UPPER(string)

Translate the string to upper case. The action of this function is equivalent to that of TRANSLATE(string), but it is slightly faster for short strings. For example:

SAY UPPER('One Fine Day') -> ONE FINE DAY

VALUE()

VALUE(name)

Returns the value of the symbol represented by the name argument. For example:

/*Assume that J has the value 12*/
SAY VALUE('j') -> 12

VERIFY()

VERIFY(string,list[,'MATCH'])

Returns the index of the first character in the string argument which is not contained in the list argument or 0 if all of the characters are in the list. If the MATCH keyword is supplied, the function returns the index of the first character which is in the list or 0 if none of the characters is in the list. For example:

SAY VERIFY('123456', '0123456789') -> 0
SAY VERIFY('123a56', '0123456789') -> 4
SAY VERIFY('123a45', 'abcdefghij', 'm') -> 4 

WORD()

WORD(string,n)

Returns the nth word in the string argument or the null string if there are fewer than n words. For example:

SAY WORD('Now is the time ',2) -> is

WORDINDEX()

WORDINDEX(string,n)

Returns the starting position of the nth word in the argument string or 0 if there are fewer than n words. For example:

SAY WORDINDEX('Now is the time ',3) -> 8

WORDLENGTH()

WORDLENGTH(string,n)

Returns the length of the n-th word in the string argument. For example:

SAY WORDLENGTH('one two three',3) -> 5 

WORDS()

WORDS(string)

Returns the number of words in the string argument. For example:

SAY WORDS("You don't SAY!") -> 3

WRITECH()

WRITECH(file,string)

Writes the string argument to the given logical file. The returned value is the actual number of characters written. For example:

SAY WRITECH('output', 'Testing') -> 7 

WRITELN()

WRITELN(file,string)

Writes the string argument to the given logical file with a newline appended. The returned value is the actual number of characters written. For example:

SAY WRITELN('output', 'Testing') -> 8

X2C()

X2C(string)

Converts a string of hex digits into the (packed) character representation. Blank characters are permitted in the argument string at byte boundaries. For example:

SAY X2C('12ab') -> '12ab'x
SAY X2C('12 ab') -> '12ab'x
SAY X2C(61) -> a 

X2D()

X2D(hex,digits)

Converts a hexadecimal number to decimal. For example:

SAY X2D('1f') -> 31

XRANGE()

XRANGE([start][,end])

Generates a string consisting of all characters numerically between the specified start and end values. The default start character is '00'x, and the default end character is 'FF'x. Only the first character of the start and end arguments is significant. For example:

SAY XRANGE() -> '00010203 . . . FDFEFF'x
SAY XRANGE('a', 'f') -> 'abcdef'
SAY XRANGE(,'0A'x) -> '000102030405060708090A'x 

Example Program

The following example program illustrates many of the built-in functions that manipulate character strings.

Program 13. Changestrings.rexx

/*This ARexx program shows the effect of built-in functions that change strings. The functions come in two groups: one that manipulates individual characters and one that manipulates whole strings.*/
 
teststring1 = " every good boy does fine "
 
/*The first group is composed of the functions STRIP(), COMPRESS(), SPACE(), TRIM(), TRANSLATE(), DELSTR(), DELWORD(), INSERT(), OVERLAY(), and REVERSE().*/
 
/*STRIP() removes only leading and trailing characters.*/
 
/*Print the original string, for comparison. We put a period at the end of the string, so you can see what happens to the spaces at the end of the string.*/
SAY " every  good   boy   does   fine   "
 
/*The same string stripped of leading and trailing spaces*/
SAY STRIP(" every good boy does fine ")"."
 
/*Failed attempt to remove leading and trailing "e"s*/
SAY STRIP(" every good boy does fine",,"e")"."
 
/*The "e"'s were protected by the leading and trailing spaces. Removing them exposes the "e"'s to the effects of STRIP()*/
SAY STRIP("every good boy does fine",,"e")"."
 
/*Remove "e"'s and spaces from the original string*/
SAY STRIP(" every good boy does fine ",," e")"."
 
/*We are now using the variable "teststring1", defined above. Remove only the trailing spaces in the test string.*/
SAY STRIP(teststring1, T)"."
 
/*Remove the trailing spaces and the "e"*/
SAY STRIP(teststring1,T," e")"."
 
/*Compress() removes characters anywhere in the string. This removes all blanks from the test string*/
SAY COMPRESS(teststring1)
 
CALL TIME('r')
SAY TIME('Civil') /*Civilian time HH:MM{AM | PM}*/
SAY TIME('h') /*Hours since midnight*/
SAY TIME('m') /*Minutes since midnight*/
SAY TIME('s') /*Seconds since midnight*/
SAY TIME('e') /*Elapsed time since program start*/
 
/*Function:TRACE Usage: TRACE( [option] )*/
SAY TRACE()
SAY TRACE(TRACE()) /*Leave it unchanged*/
 
/*Function:TRANSLATE Usage: TRANSLATE(string[,output][,input] [,pad])*/
SAY TRANSLATE('aBCdef') /*Translate to Uppercase*/
SAY TRANSLATE ('abcdef', '1234')
SAY TRANSLATE('654321', 'abcdef', '123456')
SAY TRANSLATE('abcdef', '123', 'abcdef', '+')
 
/*Function: TRIM Usage: TRIM(string)*/
SAY TRIM(' abc ')
 
/*Function: TRUNC Usage: TRUNC(number[,places])*/
SAY TRUNC(123.456)
SAY '$'TRUNC(134566.123,2)
 
/*Function: UPPER Usage: UPPER(string)*/
SAY UPPER('aBCdef12')
 
/*Function: VALUE Usage: VALUE(name)*/
abc = 'my name'
SAY VALUE('abc')
 
/*Function: VERIFY Usage: VERIFY(string,list[,'M'])*/
SAY VERIFY('123a45', '0123456789')
SAY VERIFY('abc3de', '012456789', 'M')
 
/*Function: WORD Usage: WORD(string,n)*/
SAY WORD('Now is the time',3)
 
/*Function: WORDINDEX Usage: WORDINDEX(string,n)*/
SAY WORDINDEX('Now is the time ',3)
 
/*Function: WORDLENGTH Usage: WORDLENGTH(string,n)*/
SAY WORDLENGTH('Now is the time ',4)
 
/*Function: WORDS Usage: WORDS(string)*/
SAY WORDS('Now is the time')
 
/*Function: WRITECH Usage: WRITECH(logical,string)*/
IF OPEN('test','ram:test$$', 'W') THEN DO
   SAY WRITECH('test', 'message') /*Write the string*/
   CALL CLOSE 'test'
END
 
/*Function: WRITELN Usage: WRITELN(logical,string)*/
IF OPEN('test', 'ram:test$$', 'W') THEN DO
   SAY WRITELN('test', 'message')
   /*Write the string (with newline)*/
   CALL CLOSE 'test'
END
 
/*Function: X2C Usage: X2C(heystring)*/
SAY X2C('616263') /*Convent to character (pack)*/
 
/*Function: XRANGE Usage: XRANGE([start] [,end])*/
SAY C2X(xrange('f0'x))
SAY XRANGE('a', 'g')
EXIT

The output of Program 13 is:

 every good boy does fine
every good boy does fine.
 every good boy does fine .
very good boy does fin.
very good boy does fin.
 every good boy does fine.
 every good boy does fin.
everygoodboydoesfine
1:23PM /*These results vary depending*/
13 /*on the time the program is run.*/
803
48199
0.80
N
N
ABCDEF
abcdef
fedcba
123+++
   abc
123
$134566.12
ABCDEF12
my name
4
0
the
8
4
4
7
8
abc
F0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF
abcdefg

REXXSupport.Library Functions

The functions listed in this section are part of the REXXSupport.library. They may only be used if this library has been opened. Below is an example that shows you how to open this library.

Program 14. OpenLibrary.rexx

/*Add rexxsupport.library if it isn't already open.*/
IF ~ SHOW ('L', "rexxsupport.library") THEN DO
/*If the library isn't open, try to open it*/
IF ADDLIB('rexxsupport.library', 0, -30,0)
THEN SAY "Added rexxsupport.library."
ELSE DO
   SAY 'ARexx support library not available, exiting'
   EXIT 10 /*Exit if ADDLIB() failed*/
   END
END 

ALLOCMEM()

ALLOCMEM(length[,attribute])

Allocates a block of memory of the specified length from the system free-memory pool and returns its address as a four-byte string. The optional attribute parameter must be a standard EXEC memory allocation flag, supplied as a four-byte string. The default attribute is for "PUBLIC" memory (not cleared).

This function should be used whenever memory is allocated for use by external programs. It is the user's responsibility to release the memory space when it is no longer needed. See also FREEMEM(). For example:

SAY C2X(ALLOCMEM(1000)) -> 00050000
SAY C2X(ALLOCMEM (1000, '00 01 00 0 1'X)) -> 00228400
/*1000 bytes of CLEAR Public memory*/ 

CLOSEPORT()

CLOSEPORT(name)

Closes the message port specified by the name argument, which must have been allocated by a call to OPENPORT() within the current ARexx program. Any messages received but not yet REPLYed are automatically returned with the return code set to 10. See also OPENPORT(). For example:

CALL CLOSEPORT myport 

FREEMEM()

FREEMEM(address,length)

Releases a block of memory of the given length to the system free list. The address parameter is a four-byte string, typically obtained by a prior call to ALLOCMEM(). FREEMEM() cannot be used to release memory allocated using GETSPACE(), the ARexx internal memory allocator. The returned value is a Boolean success flag. See also ALLOCMEM(). For example:

MemoryRequest = 1024
MyMem = ALLOCMEM(MemoryRequest)
SAY C2X(MyMem) -> 07C987B0
SAY FREEMEM(MyMem, MemoryRequest) -> 1
/*Or: SAY FREEMEM('07C987B0'x,1024)*/

Before your program terminates, you must use a matching FREEMEM() to release the exact amount of memory you allocated with each ALLOCMEM(). Otherwise, you may crash the system or leave memory unavailable until you reboot.

GETARG()

GETARG(packet[,n])

Extracts a command, function name or argument string from a message packet. The packet argument must be a four-byte address obtained from a prior call to GETPKT(). The optional n argument specifies the slot containing the string to be extracted and must be less than or equal to the actual argument count for the packet. Commands and function names are always in slot 0. Function packets my have argument strings in slots 1-15. For example:

command = GETARG(packet)
function = GETARG(packet,0) /*name string*/
arg1 = GETARG(packet,1) /*1st argument*/ 

GETPKT()

GETPKT(name)

Checks the message port specified by the name argument to see whether any messages are available. The named message port must have been opened by a prior call to OPENPRT() within the current ARexx program. The returned value is the four-byte address of the first message packet, or '0000 0000'x if no packets were available.

The function returns immediately whether or not a packet is enqueued at the message port. Programs should never be designed to "busy-loop" on a message port. If there is no useful work to be done until the next message packet arrives, the program should call WAITPKT() and allow other tasks to proceed. See also WAITPKT(). For example:

packet = GETPKT ('MyPort') 

OPENPORT()

OPENPORT(name)

Creates a public message port with the given name. The returned Boolean value indicates whether the port was successfully opened. An initialization failure will occur if another port of the same name already exists or if a signal bit couldn't be allocated. The message port is allocated as a Port Resource node and is linked into the program's global data structure. Ports are automatically closed when the program exits and any pending messages are returned to the sender. See also CLOSEPORT(). For example:

success = OPENPORT("MyPort") 

REPLY()

REPLY(packet,rc)

Returns a message packet to the sender, with the primary result field set to the value given by the rc argument. The secondary result is cleared. The packet argument must be supplied as a four-byte address, and the rc argument must be a whole number. For example:

CALL REPLY(packet,10) /*Error return*/ 

SHOWDIR()

SHOWDIR(directory[,'ALL'|'FILE'|'DIR'][,pad])

Returns the contents of the specified directory as a string of names separated by blanks. The second parameter is an option keyword that selects whether all entries, only files, or only subdirectories, will be included. For example:

SAY SHOWDIR('SYS:REXXC', 'f', ';') -> WaitForPort;TS;TE;TCO;RXSET;RXLIB;RXC;RX;HI

SHOWLIST()

SHOWLIST({'A' | 'D' | 'H' | 'T' | 'L' | 'M' | 'P' | 'R' | 'S' | 'T' | 'V' | 'W'}[,name][,pad])

An argument is entered using its initial letter. The arguments are:

If only one argument is supplied, SHOWLIST() returns a string separated by blanks: If a pad character is supplied, names will be separated by the pad rather than by blanks. If the name parameter is supplied. SHOWLIST() returns a Boolean value which indicates if the specified list contains that name. Names are case-sensitive. To provide an accurate snapshot of the current list, task switching is forbidden when the list is scanned.

SAY SHOWLIST('P') -> REXX MyCon
SAY SHOWLIST('P',,';') -> REXX;MyCon
SAY SHOWLIST('P', 'REXX') -> 1 

STATEF()

STATEF(filename)

Returns a string containing information about an external file. The string is formatted as:

"{DIR | FILE} length blocks protection days minutes ticks comment."

The length token gives the file length in bytes, and the block token specifies the file length in blocks. For example:

SAY STATEF("LIBS:REXXSupport.library")
/*might give "File 2524 5 ----RW-D 4866 817 2088*/ 

WAITPKT()

WAITPKT(name)

Waits for a message to be received at the specified (named) port, which must have been opened by a call to OPENPORT() within the current ARexx program. The returned Boolean value indicates whether a message packet is available at the port. Normally the returned value will be 1 (True), since the function waits until an event occurs at the message port.

The packet must then be removed by a call to GETPKT() and should be returned eventually using the REPLY() function. Any message packets received but not returned when an ARexx program exits are automatically REPLYed with the return code set to 10. For example:

CALL WAITPKT 'MyPort' /*Wait awhile*/ 

Index