fis-gtm/sr_port/mumps.hlp

18238 lines
573 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

1 About_GTM
GT.M Version 4.4
UNIX Edition
October 2003
The information in this manual is subject to change without notice and
should not be construed as a commitment by Sanchez Computer Associates.
The software described in this manual is furnished under a license and
may be used or copied only in accordance with the terms of such a
license.
Copyright 1987 - 2003
Sanchez Computer Associates
All rights reserved
GT.M, and GT.CM are trademarks of Sanchez Computer Associates. All
other company and product names may be trademarks of the respective
companies with which they are associated.
1 Prog_Dev_Cycle
Program Development Cycle
In contrast to M environments that interpret M code, GT.M compiles M
code from source files into the target machine language. The GT.M
compiler produces object files, which are dynamically linked into an
image. Source files and object files may be managed independently, or
placed together in a specific directory. GT.M permits access to source
and object files in multiple directories.
GT.M databases are UNIX files identified by a small file called a
Global Directory. Global Directories allow management of the database
files to be independent of the placement of files containing M
routines. By changing the Global Directory, you can use the same
programs to access different databases.
Program development may utilize both GT.M and UNIX development tools.
The development methodology and environment chosen for a particular
installation, and tailored by the individual user, determines the
actual mix of tools. These tools may vary from entirely GT.M with
little UNIX, to mostly UNIX with a modest use of GT.M.
Direct Mode serves as an interactive interface to the GT.M run-time
environment and the compiler. In Direct Mode, the user enters M
commands at the GT.M prompt, and GT.M compiles and executes the
command. This feature provides immediate turnaround for rapid program
development and maintenance.
The methods described in the GT.M column assume you are already at
the GTM> prompt, which is also called Direct Mode. To get to this
prompt, type $gtm_dist/mumps -direct.
2 Def_Env_Var
Defining Environment Variables
GT.M requires the definition of certain environment variables as part
of setting up the environment.
o To locate the files that Sanchez Computer Associates provides as
part of GT.M
o To hold some user-controlled information which GT.M uses for
run-time operation
The procedure below describes how to define an environment variable.
Use this procedure to define an environment variable either at the
shell prompt or in your shell startup file. If you define the variable
at the shell prompt, it will be effective only until you logout. If you
define it in your .profile file (.cshrc, if using a C shell variant),
it will be in effect whenever you log in. Your system manager may have
already defined some of these variables.
Each environment variable required by GT.M is described and
illustrated in individual sections following the procedure. Only
gtm_dist, and in some cases gtmgbldir, gtm_principal and
gtmroutines, are required by users who do not perform programming
activities.
To define an environment variable type the following commands:
$ env_variable=env_variable_value
$ export env_variable
The following environment variables hold information that determines
some details of GT.M run-time operation, over which the user has
control.
3 gtm_dist
gtm_dist
gtm_dist is used to establish the location of the installed GT.M
program and support files.
The syntax for gtm_dist is as follows:
$ gtm_dist=<GT.M-distribution-directory>
The standard installation places these files in /gtm/bin.
Example:
$ gtm_dist=/usr/staff/smith/GTM.dist
$ export gtm_dist
This identifies /usr/staff/smith/GTM.dist as the location of the
installed GT.M files.
Add gtm_dist to your PATH environment variable to have UNIX search the
GT.M installation directory (when processing a command to activate or
run an image). This allows you to activate GT.M and the utilities
without explicitly specifying a path.
To add gtm_dist to your PATH type the following commands:
$ PATH=$PATH:$gtm_dist
$ export PATH
Most of the examples in this manual assume that you have added
gtm_dist to your PATH.
3 gtmgbldir
gtmgbldir
gtmgbldir defines the path to a Global Directory. A Global Directory
maps global variables to physical database files, and is required to
locate M global variables. gtmgbldir provides the initial value for
$ZGBLDIR, the intrinsic special variable that connects the GT.M
run-time system to the Global Directory. It also connects the Global
Directory to the utilities requiring one.
If you maintain multiple global directories, define gtmgbldir to the
Global Directory you currently want to use.
The syntax of a gtmgbldir definition is:
$ gtmgbldir=/directory/filename.gld
Example:
$ gtmgbldir=/usr/staff/mumps.gld
$ export gtmgbldir
This specifies /usr/staff as the directory containing the Global
Directory file named mumps.gld.
3 gtm_principal
gtm_principal
The gtm_principal environment variable specifies the value for
$principal, which designates the absolute pathname of the principal $IO
device. This is an MDC Type A enhancement to standard M.
The following is an example of gtm_principal definition:
$ gtm_principal=/usr/filename
$ export gtm_principal
This specifies the /usr/filename as the principal $IO device, effective
until changed further or until you logout of the particular session.
3 gtmroutines
gtmroutines
The gtmroutines environment variable specifies a search list of
possible locations for M routines. This value is used to initialize
$ZROUTINES, (the intrinsic special variable that enables GT.M to find
the routine (program) you want to run). gtmroutines is required for
ZLINKing. gtmroutines is particularly helpful in calling percent
utilities and the Global Directory Editor (GDE), which are in gtm_dist.
$ gtmroutines="directories in search list"
The directories in the search list must be separated by a space and
enclosed in quotation marks (" "). Environment variables are accepted
in the search list.
The following is an example of gtmroutines definition:
$ gtmroutines=". $gtm_dist"
$ export gtmroutines
This specifies that GT.M search for a routine first in the current
directory (.), then in the distribution directory (which is identified
by the environment variable gtm_dist). The distribution directory is
included in the list because it contains the percent routines. You will
probably want the search list to contain these two items at a minimum.
In addition, you may want to add directories of your own.
3 Editor
Editor
The EDITOR environment variable specifies the UNIX text editor used
when editing a routine either from the shell or with ZEDIT. Since this
is a standard part of establishing your UNIX environment, you will
probably only need to define this when you want to use a different
editor than the one defined in your shell startup file.
Example:
$ EDITOR=/usr/bin/vi
$ export EDITOR
This defines the current text editor to vi.
2 Prep_the_DB
Preparing the Database
GT.M databases consist of one or more UNIX files. Most database files
have a UNIX file structure externally and a GT.M Database Structure
(GDS) internally. Management of the GDS files by the GT.M run-time
system assures high performance and integrity. GT.M database files are
coordinated by a Global Directory. The Global Directory identifies
which global names belong in which files, and specifies the creation
characteristics for each file. To specify access to a database, each M
process must define the gtmgbldir environment variable to point to the
associated Global Directory.
To define and maintain a Global Directory, use the Global Directory
Editor (
GDE) utility. The GDE utility automatically upgrades existing global
directories to the current format.The MUPIP command CREATE uses the
characteristics as defined in the Global Directory to create the
associated database. In a production environment, the system manager
typically maintains Global Directories.
For more information on GDE and MUPIP refer to the "Global Directory
Editor" and "MUPIP" chapters in the GT.M Administration and Operations
Guide .
Example:
This example is a sequence of events that illustrate steps you might
typically perform in creating a new global directory, in our example
PAYROLL.GLD. To assist you in following the sequence, each actual step
appears in typewriter font, as you might see on your terminal screen,
followed by an explanation in normal text font.
$ ls payroll.gld
payroll.gld not found
The ls command verifies that there are no existing files with the name
payroll.gld.
$ gtmgbldir=payroll.gld
$ export gtmgbldir
This establishes the current value of the environment variable
gtmgbldir as payroll.gld. GT.M uses gtmgbldir to identify the current
Global Directory. When defined at the shell prompt, gtmgbldir maintains
the defined value only for the current login session. The next time you
log into UNIX, you must again define the value of gtmgbldir as
payroll.gld to use it as the current Global Directory.
This example defines gtmgbldir without a full pathname. The environment
variable points to the payroll.gld file in the current working
directory. Therefore if the default directory changes, GT.M attempts to
locate the Global Directory in the new default directory and cannot use
the original file. If you intend for the Global Directory to
consistently point to this file, even if the default directory changes,
use a full file-specification for gtmgbldir.
$ gtm
GTM>d ^GDE
%GDE-I-GDUSEDEFS, Using defaults for Global Directory
/staff/payroll.gld
GDE>
This invokes the Global Directory Editor from the GT.M prompt and
produces an informational message. Refer to the "Program Development
Cycle" in GT.M Programmer's Guide for more details.
Example:
$ mupip load payroll.gld
GT.M
09-OCT-2001 11:26:44
keycnt: 100 max subsc len:12 max data len: 3
Last record number: 202
This uses the MUPIP LOAD command to load a sequential file into the
database.
Because MUPIP uses the environment variable gtmgbldir to locate a
Global Directory, which identifies the database file(s), the LOAD
command does not require any information about the target database.
With few exceptions, the GT.M utilities work in the same way.
For general information on shareable libraries in HP-UX, refer to
the "Programming on HP-UX" manual.
Refer to the documentation accompanying AIX for more information on
shareable libraries on AIX.
entryref: return-value routine-name
(parameter, parameter, ..)
where entryref is an M entryref,
return-value is xc_long_t, xc_status_t, or void
and parameter are in the format: direction:type.
len: void length (I:xc_float_t*, o:xc_float_t*)
Example:
% echo $GTMXC_mathpak
2 Cre_Edt_Source_Prog
Creating and Editing a Source Program
The first step in developing a GT.M program is to create a source file.
In most cases, the user can create and modify GT.M source programs
using UNIX text editors.
When the program is very simple (and its lines do not need revision
after they are entered), you can use the cat command to direct input
from your terminal to your source file.
3 Edit_from_GTM
Editing from GT.M
Invoke Direct Mode to create and edit a source program in GT.M. At the
GTM> prompt, invoke the editor by typing:
ZEDIT <filename>
ZEDIT invokes the editor specified by the EDITOR environment variable,
which creates a seperate file for each M source module.
The GT.M environment works most efficiently if the file has the same
name as the M routine it contains, and has an .m extension. Since ZEDIT
automatically defaults the.m extension, it is not necessary to specify
an extension unless you require a different one. If you use another
extension, you must specify that extension with every reference to the
file. Multiple character file extensions are permitted for M source
file names.
3 Edit_from_Shell
Editing from the Shell
To create and edit a source program from the shell, invoke any text
editor at the shell prompt and specify a UNIX file as the source. The
GT.M environment works best when you give a file the name of the M
routine that it contains, and an .m extension.
Example:
$ vi payroll.m
The vi command initiates an editing session for payroll.m from the
shell prompt. If payroll.m does not already exist, vi creates it.
Because this example uses UNIX rather than GT.M tools, we must specify
the .m file extension.
2 Comp_Source_Prog
Compiling a Source Program
GT.M compiles M source code files and produces object files for
complete integration into the UNIX enviroment. The object modules have
the same name as the compiled M source file with an .o file extension,
unless otherwise specified. The object files contain machine
instructions and information necessary to connect the routine with
other routines, and map it into memory. An M routine source file must
be compiled after it is created or modified. You can compile explicitly
with the ZLINK command or implicitly with auto-ZLINK. At the shell
command line, compile by issuing the mumps command.
The compiler checks M code for syntax errors and displays error
messages on the terminal, when processing is complete. Each error
message provides the source line in error with an indicator pointing to
the place on the line where the error is occurring. For a list and
description of the compiler error messages, refer to the GT.M Message
and Recovery Procedures Reference Manual.
You can generate a listing file containing the compile results by
including the
-list qualifier as a modifier to the argument to the ZLINK command in
Direct Mode. This can also be done by redirecting the compiler messages
to a file by adding >filename 2>&1 to the mumps command when compiling
a program from the shell. Refer to the "Compiling from the Shell"
section for an explanation of the M command describing -list, and other
valid qualifiers for the M and ZLINK commands.
The compiler stops processing a routine line when it detects an error
on that line. Under most conditions the compiler continues processing
the remaining routine lines. This allows the compiler to produce a more
complete error analysis of the routine and to generate code that may
have valid executable paths. The compiler does not report multiple
syntax errors on the same line. When it detects more than 127 syntax
errors in a source file, the compiler ceases to process the file.
3 Comp_from_GTM
Compiling from GT.M
In Direct Mode, GT.M provides access to the compiler explicitly through
the ZLINK and ZCOMPILE commands, and implicitly through automatic
invocation of ZLINK functionality (auto-ZLINK) to add required routines
to the image. ZCOMPILE is a GT.M routine compilation command, it
compiles the routine and creates a new object module. The primary task
of ZLINK is to place the object code in memory and "connect" it with
other routines. However, under certain circumstances, ZLINK may first
use the GT.M compiler to create a new object module.
The difference between ZCOMPILE and ZLINK is that ZCOMPILE creates a
new object module on compiling, whereas the ZLINK command links the
object module with other routines and places the object code in memory.
ZLINK compiles under these circumstances:
o ZLINK cannot locate a copy of the object module but can locate a
copy of the source module.
o ZLINK can locate both object and source module, and finds the
object module to be older than the source module.
o The file-specification portion of the ZLINK argument includes an
explicit extension of .m.
Auto-ZLINK compiles under the first two circumstances, but can never
encounter the last one.
When a command refers to an M routine that is not part of the current
image, GT.M automatically attempts to ZLINK and, if necessary, compile
that routine. In Direct Mode, the most common method to invoke the
compiler through an auto-ZLINK is to enter DO ^routinename at the GTM>
prompt. When the current image does not contain the routine, GT.M does
the following:
o Locates the source and object
o Determines whether the source has been edited since it was last
compiled
o Compiles the routine, if appropriate
o Adds the object to the image
By using the DO command, you implicitly instruct GT.M to compile, link,
and execute the program. With this method, you can test your routine
interactively.
For complete descriptions of ZLINK and auto-ZLINK, refer to the
"Commands" chapter in GT.M Programmer's Guide.
Example:
GTM>do ^payroll
GTM>do ^taxes
This uses the M DO command to invoke the GT.M compiler implicitly from
the GTM> prompt if the routine requires new object code. When the
compiler runs, it produces two object module files, payroll.o and
taxes.o.
If you receive error messages from the compilation, you may fix them
immediately by returning to the editor and correcting the source. By
default, the GT.M compiler operates in "compile-as-written" mode, and
produces object code even when a routine contains syntax errors. This
code includes all lines that are correct and all commands on a line
with an error, up to the error. Therefore, you may decide to tailor the
debugging cycle by running the program without removing the syntax
errors.
3 Comp_from_Shell
Compiling from the Shell
From the shell, invoke the compiler by entering mumps file-name at the
shell prompt.
Example:
$ mumps payroll.m
$ mumps taxes.m
This uses the mumps command to invoke the GT.M compiler from the shell
prompt, and creates .o versions of these files.
Use the mumps command at the shell prompt to:
o Check the syntax of a newly entered program.
o Optionally, get a formatted listing of the program.
o Ensure that all object code is up to date before linking.
The mumps command invokes the compiler to translate an M source file
into object code.
The format for the MUMPS command is:
MUMPS [-qualifier[...]] pathname
o Source programs must have an extension of .m.
o Each pathname identifies an M source program to compile.
o Qualifiers determine characteristics of the compiler output.
o Qualifiers must appear after the command, but before the file name
to be properly applied.
o GT.M allows the UNIX * and ? wildcards in a file name.
The * wildcard accepts any legal combination of numbers and characters
including a null, in the position the wildcard holds.
The ? wildcard accepts exactly one legal character in its position.
For example, mumps *.m compiles all files in the current default
directory with an .m extension. mumps *pay?.m compiles .m files with
names that contain any characters followed by pay, followed by one
character. Unlike when using ZLINK or ZCOMPILE, the filename must be
fully specified when compiling from the shell.
1 Opr_Dbg_Dir_Mode
Operating and Debugging in Direct Mode
Direct Mode is an important tool in GT.M because it allows you to
interactively debug, modify, and execute M routines. Direct Mode is a
shell that immediately compiles and executes GT.M commands providing an
interpretive-like interface. M simplifies debugging by using the same
commands for debugging that are used for programming.
The focus of this chapter is to describe the debugging process in
Direct Mode, and to illustrate the GT.M language extensions that
enhance the process. Command functionality is described only in enough
detail to illustrate why a particular command is useful for a debugging
activity being described. If you have specific functionality questions
about a command or variable, refer to the "Commands", "Functions" or
"Intrinsic Special Variables" chapters in GT.M Programmer's Guide.
2 Opr_Dir_Mode
Operating in Direct Mode
This section provides an overview of the following basic operational
issues in Direct Mode:
o Entering Direct Mode
o Available functionality
o Exiting Direct Mode
3 Entr_Dir_Mode
Entering Direct Mode
To enter Direct Mode, type $gtm_dist/mumps -direct at the shell prompt.
Example:
$ $gtm_dist/mumps -direct
GTM>
This shows using $gtm_dist/mumps -direct at the prompt to enter Direct
Mode.
To create a gtm alias in your shell startup file (in the example below
the startup file is assumed to be a .profile file):
o Open an edition session for your .profile file by typing:
$vi .profile
o Add a function to the file to define your gtm alias
o gtm()
{
$gtm_dist/mumps -direct
}
o save the file.
Now, when you want to enter Direct Mode for an editing or debugging
session, simply type gtm at the shell prompt.
Example:
$ gtm
GTM>
This shows that the gtm alias typed at the shell prompt also takes you
to the Direct Mode.
3 Func_in_Dir_Mode
Functionality Available in Direct Mode
This section provides an overview of basic functionality and concepts
that enhance your use of Direct Mode.
4 Comm_Recall
Command Recall
Direct Mode includes a line command recall function to display
previously entered command lines. Use the Up Arrow key at the GTM>
prompt to scroll back through command lines. Usethe Down Arrow key to
scroll forward through the command lines. GT.M displays one command
line at a time. You may delete and reenter characters starting at the
end of a recalled line.
The RECALL command is another way to access previously entered Direct
Mode command lines. RECALL is only valid in Direct Mode and causes an
error if it appears in other M code.
The format of the
RECALL command is:
REC[ALL] [intlit|strlit]
o The optional integer literal specifies a previously entered command
by the counting back from the present.
o The optional string literal specifies the most recently entered
command line that starts with characters matching the
(case-sensitive) literal.
o When the RECALL command has no argument, it displays up to a
maximum of 99 available past Direct Mode entries.
If the Direct Mode session has just started, you may not have entered
99 lines for GT.M to save and therefore you will not have 99 lines to
look at. The most recently entered GT.M command line has the number one
(1), older lines have higher numbers. GT.M does not include the RECALL
command in the listing. If the RECALL command is issued from a location
other than the Direct Mode prompt, GT.M issues a run-time error.
Example:
GTM>WRITE $ZGBLDIR
M.GLD
GTM>SET $ZGBLDIR TEST.GLD
GTM>SET A=10
GTM>SET B=A
GTM>REC
1 SET B=A
2 SET A=10
3 SET $ZGBLDIR TEST.GLD
4 WRITE $ZGBLDIR
This REC[ALL] command displays the previously entered commands.
You can also display a selected command by entering RECALL and the line
number of the command you want to retrieve.
Example:
GTM>REC 2
GTM>SET A=10
This RECALLs the line number two (2).
If the RE[CALL] command includes a text parameter, GT.M displays the
most recent command matching the text after the RE[CALL] command.
Example:
GTM>REC WRITE
GTM>WRITE $ZGBLDIR
MUMPS.GLD
This RECALLs "WRITE", the command most recently beginning with this
text. Note that the RECALL command text is case sensitive. The RECALL
command with a text argument treats WRITE and write differently, that
is, it treats them case sensitively. If you first type the WRITE
command in lower-case and then type WRITE in upper-case to recall it,
the RECALL command does not find a match.
4 Line_Editing
Line Editing
GT.M permits the use of the GT.M command line editor at the Direct Mode
prompt and during M READs from a terminal. The GT.M line editor allows
cursor positioning using the <CTRL> key, edit keypad and function keys.
The GT.M Direct Mode line editing keys are as follows:
Backspace Deletes the character to the left of the cursor
Delete Same as backspace
Up-arrow Moves to a less recent item in the RECALL list
Down-arrow Moves to a more recent item in the RECALL list
Left-arrow Moves the cursor one character to the left
Right-arrow Moves the cursor one character to the right
<CTRL-A> Moves the cursor to the beginning of the line
<CTRL-B> Moves the cursor one character towards the beginning of
the line
<CTRL-D> Deletes the character at the cursor position
<CTRL-E> Moves the cursor to the end of the line
<CTRL-F> Moves the cursor one character towards the end of the line
<CTRL-K> Deletes all characters from the cursor to the end of the
line
<CTRL-U> Deletes the entire line
4 M_Invo_Stack
The M Invocation Stack
The ANSI M Standard describes certain M operations in terms of how a
stack-based virtual machine would operate. A stack is a repository for
tracking temporary information on a "last-in/first-out" (LIFO) basis. M
program behavior can be understood using a stack-based model. However,
the standard is not explicit in defining how an implementation must
maintain a stack or even whether it must use one at all.
The stack model provides a trail of routines currently in progress that
shows the location of all the M operations that performed the
invocations leading to the current point.
3 Exit_Dir_Mode
Exiting Direct Mode
Four M commands terminate a Direct Mode session:
o HALT
o ZCONTINUE
o GOTO
o ZGOTO
The
HALT command exits Direct Mode and terminates the M process.
The
ZCONTINUE command instructs GT.M to exit Direct Mode and resume routine
execution at the current point in the M invocation stack. This may be
the point where GT.M interrupted execution and entered Direct Mode.
However, when the Direct Mode interaction includes a QUIT command, it
modifies the invocation stack and causes ZCONTINUE to resume execution
at another point.
The
GOTO and
ZGOTO commands instruct GT.M to leave Direct Mode, and transfer control
to a specified entry reference.
2 Debug_Rtn_Dir_Mode
Debugging a Routine in Direct Mode
To begin a debugging session on a specific routine, type the following
command at the GTM prompt:
GTM>DO ^routinename
You can also begin a debugging session by pressing <CTRL-C> after
running an M application at the shell. To invoke Direct Mode by
pressing <CTRL-C>, process must have the Principal Device in the
CENABLE state and not have the device set to CTRAP=$C(3).
When GT.M receives a <CTRL-C> command from the principal device, it
invokes Direct Mode at the next opportunity, (usually at a point
corresponding to the beginning of the next source line). GT.M can also
interrupt at a FOR loop iteration or during a command of indeterminate
duration such as JOB, LOCK, OPEN or READ. The GT.M USE command
enables/disables the <CTRL-C> interrupt with the [NO]CENABLE
deviceparameter. By default, GT.M starts <CTRL-C> enabled. The default
setting for <CTRL-C> handling is controlled by GTM$DEFAULTS.M64 and is
enabled in the distribution version of that file.
GT.M displays the GTM> prompt on the principal device. Direct Mode
accepts commands from, and reports errors to, the principal device.
GT.M uses the current device for all other I/O. If the current device
does not match the principal device when GT.M enters Direct Mode, GT.M
issues a warning message on the principal device. A USE command changes
the current device. For more information on the USE command, refer to
the "Input/Output Processing" chapter.
The default "compile-as-written" mode of the GT.M compiler lets you run
a program with errors as part of the debugging cycle. The object code
produced includes all lines that are correct and all commands on a line
with an error, up to the error. When GT.M encounters an error, it
XECUTEs non empty values of $ETRAP or $ZTRAP. By default $ZTRAP
contains a BREAK command, so GT.M enters Direct Mode.
The rest of the chapter illustrates the debugging capabilities of GT.M
by taking a sample routine, dmex, through the debugging process. dmex
is intended to read and edit a name, print the last and first name, and
terminate if the name is an upper-case or lower-case "Q".
Each of the remaining sections of the chapter uses dmex to illustrate
an aspect of the debugging process in GT.M.
3 Creat_Display_M_Rtn
Creating and Displaying M Routines
To create or edit a routine, use the
ZEDIT command. ZEDIT invokes the editor specified by the EDITOR
environment variable, and opens the specified file. dmex.m, for
editing.
Example:
GTM>ZEDIT "dmex"
Once in the editor, use the standard editing commands to enter and edit
text. When you finish editing, save the changes, which returns you to
Direct Mode.
For further details and examples, refer to the GT.M Programmer's
Guide.
3 Exec_M_Rtn_Inter
Executing M Routines Interactively
To execute an M routine interactively, it is not necessary to
explicitly compile and link your program. When you refer to an M
routine that is not part of the current image, GT.M automatically
attempts to compile and
ZLINK the program.
Example:
GTM>DO ^dmex
Name: Revere, Paul
%GTM-E-UNDEF, Undefined local variable: bame
At M source location name+3^dmex
GTM>
In this example GT.M places you in Direct Mode, but also cites an error
found in the program with a run-time error message. In this example, it
was a reference to bame, which is undefined.
To see additional information about the error message, examine the
$ECODE or
$ZSTATUS special variables.
$ECODE is read-write intrinsic special variable that maintains a list
of comma delimited codes that describe a history of past errors - the
most recent ones appear at the end of the list. In $ECODE, standard
errors are prefixed with an "M", user defined errors with a "U", and
GT.M errors with a "Z". A GT.M code always follows a standard code.
$ZSTATUS is a read-write intrinsic special variable that maintains a
string containing the error condition code and location of the last
exception condition occurring during routine execution. GT.M updates
$ZSTATUS only for errors found in routines and not for errors entered
at the Direct Mode prompt.
For further details and examples, refer to the GT.M Programmer's
Guide.
3 Proc_with_Runtime_Syn_Err
Processing with Run-time and Syntax Errors
When GT.M encounters a run-time or syntax error, it stops executing and
displays an error message. GT.M reports the error in the message. In
this case, GT.M reports an undefined local variable and the line in
error, name+3^dmex. Note that GT.M re-displays the GTM> prompt so that
debugging may continue.
To re-display the line and identify the error, use the
ZPRINT command.
Example:
GTM>ZPRINT, name+3
%GTM-E-SPOREOL, Either a space or an end-of-line was expected but not
found
ZP, name+3
^_____
GTM>
This example shows the result of incorrectly entering a ZPRINT command
in Direct Mode. GT.M reports the location of the syntax error in the
command line with an arrow. $ECODE and $ZSTATUS do not maintain this
error message because GT.M did not produce the message during routine
execution. Enter the correct syntax, (i.e., remove the comma) to
re-display the routine line in error.
Example:
GTM>WRITE $ZPOS
name+3^dmex
This example writes the current line position.
$ZPOSITION is a read-only GT.M special variable that provides another
tool for locating and displaying the current line. It contains the
current entry reference as a character string in the format
label+offset^routine, where the label is the closest preceding label.
The current entry reference appears at the top of the
M invocation stack, which can also be displayed with a
ZSHOW "S" command.
To display the current value of every local variable defined, use the
ZWRITE command with no arguments.
Example:
GTM>ZWRITE
ln=12
name="Revere, Paul"
This ZWRITE displays a listing of all the local variables currently
defined.
ZWRITE displays the variable name. ZWRITE does not display a value
for bame, confirming that it is not defined.
3 Correcting_Errors
Correcting Errors
Use the
ZBREAK command to establish a temporary breakpoint and specify an
action. ZBREAK sets or clears routine-transparent breakpoints during
debugging. This command simplifies debugging by interrupting execution
at a specific point to examine variables, execute commands, or to start
using
ZSTEP to execute the routine line by line.
GT.M suspends execution during execution when the entry reference
specified by ZBREAK is encountered. If the ZBREAK does not specify an
expression "action", the process uses the default,
BREAK, and puts GT.M into Direct Mode. If the ZBREAK does specify an
expression "action", the process XECUTEs the value of "action", and
does not enter Direct Mode unless the action includes a BREAK. The
action serves as a "trace-point". The trace-point is silent unless the
action specifies terminal output.
Example:
GTM>ZBREAK name+3^dmex:"set bame=name"
This uses a ZBREAK with an action that SETs the variable bame equal to
name.
3 Stepping_Thru_Rtn
Stepping Through a Routine
The
ZSTEP command provides a powerful tool to direct GT.M execution. When
you issue a ZSTEP from Direct Mode, GT.M executes the program to the
beginning of the next target line and performs the ZSTEP action.
The optional keyword portion of the argument specifies the class of
lines where ZSTEP pauses its execution, and XECUTEs the ZSTEP action
specified by the optional action portion of the ZSTEP argument. If the
action is specified, it must be an expression that evaluates to valid
GT.M code. If no action is specified, ZSTEP XECUTEs the code specified
by the $ZSTEP intrinsic special variable; by default $ZSTEP has the
value "B", which causes GT.M to enter Direct Mode.
ZSTEP actions, that include commands followed by a BREAK, perform the
specified action, then enter Direct Mode. ZSTEP actions that do not
include a BREAK perform the command action and continue execution. Use
ZSTEP actions that issue conditional BREAKs and subsequent ZSTEPs to
perform tasks such as test for changes in the value of a variable.
Use ZSTEP to incrementally execute a routine or a series of routines.
Execute any GT.M command from Direct Mode at any ZSTEP pause. To resume
normal execution, use ZCONTINUE. Note that ZSTEP arguments are keywords
rather than expressions, and they do not allow indirection.
Example:
GTM>ZSTEP INTO
Break instruction encountered during ZSTEP action
At M source location print^dmex
GTM>ZSTEP OUTOF
Paul Revere
Name: Q
%GTM-I-BREAKZST, Break instruction encountered during ZSTEP action
At M source location name^dmex
GTM>ZSTEP OVER
Break instruction encountered during ZSTEP action
At M source location name+1^dmex
This example shows using the ZSTEP command to step through the routine
dmex, starting where execution was interrupted by the undefined
variable error. The ZSTEP INTO command executes line name+3 and
interrupts execution at the beginning of line print.
The ZSTEP OUTOF continues execution until line name. The ZSTEP OVER,
which is the default, executes until it encounters the next line at
this level on the M invocation stack. In this case, the next line is
name+1. The ZSTEP OVER could be replaced with a ZSTEP with no argument
because they do the same thing.
3 Cont_Exec_Frm_Breakpt
Continuing Execution From a Breakpoint
Use the
ZCONTINUE command to continue execution from the breakpoint.
Example:
GTM>ZCONTINUE
Paul Revere
Name: q
Name: QUIT
Name: ?
Please use last-name, first name middle-initial
or 'Q' to Quit.
Name:
This uses a ZCONTINUE command to resume execution from the point where
it was interrupted. As a result of the ZBREAK action, bame is defined
and the error does not occur again. Because the process does not
terminate as intended when the name read has q as a value, we need to
continue debugging.
3 Interr_Execution
Interruption Execution
Press <CTRL-C> to interrupt execution, and return to the GTM prompt to
continue debugging the program.
Example:
%GTM-I-CTRLC, CTRLC_C encountered.
GTM>
This invokes direct mode with a <CTRL-C>.
3 Using_Invoc_Stac_in_Debug
Using the Invocation Stack in Debugging
M DOs, XECUTEs, and extrinsics add a level to the invocation stack.
Matching QUITs take a level off the stack. When GT.M executes either of
these commands, an extrinsic function, or an extrinsic special
variable, it "pushes" information about the new environment on the
stack. When GT.M executes the
QUIT, it "pops" the information about the discarded environment off the
stack. It then reinstates the invoking routine information using the
entries that have now arrived at the active end of the stack.
In the M stack model, a
FOR command does not add a stack frame, and a QUIT that terminates
a FOR loop does not remove a stack frame.
4 Deter_Levels_of_Nest
Determining Levels of Nesting
$STACK contains an integer value indicating the "level of nesting"
caused by DO commands, XECUTE commands, and extrinsic functions in the
M virtual stack.
$STACK has an initial value of zero (0), and increments by one with
each DO, XECUTE, or extrinsic function. Any QUIT that does not
terminate a FOR loop or any ZGOTO command decrements $STACK. In
accordance with the M standard, a FOR command does not increase $STACK.
M routines cannot modify $STACK with the SET or KILL commands.
Example:
GTM>WRITE $STACK
2
GTM>WRITE $ZLEVEL
3
GTM>
This example shows the current values for
$STACK and
$ZLEVEL. $ZLEVEL is like $STACK except that uses one (1) as the
starting level for the M stack, which $STACK uses zero (0), which means
that $ZLEVEL is always one more than $STACK. Using $ZLEVEL with "Z"
commands and functions, and $STACK with standard functions avoids the
need to calculate the adjustment.
4 Look_Invoc_Stack
Looking at the Invocation Stack
The $STACK intrinsic special variable and the $STACK() function provide
a mechanism to access M stack context information.
Example:
GTM>WRITE $STACK
2
GTM>WRITE $STACK(2,"ecode")
,M6,Z150373850,
GTM>WRITE $STACK(2,"place")
name+3^dmex
GTM>WRITE $STACK(2,"mcode")
if ln<30,bame?1.a.1"-".a1","1" "1a.ap do print q
GTM>
This example gets the value of $STACK and then uses that value to get
various types of information about that stack level using the
$STACK() function. The "ecode" value of the error information for level
two, "place" is similar to
$ZPOSITION, "mcode" is the code for the level.
In addition to the $STACK intrinsic special variable, which provides
the current stack level, $STACK(-1) gives the highest level for which
$STACK() can return valid information. Until there is an error $STACK
and $STACK(-1) are the same, but once
$ECODE shows that there is an "current" error, the information returned
by $STACK() is frozen to capture the state at the time of the error; it
unfreezes after a SET $ECODE="".
Example:
GTM>WRITE $STACK
2
GTM>WRITE $STACK(-1)
2
GTM>
This example shows that under the conditions created (in the above
example), $STACK and $STACK(-1) have the same value.
The $STACK() can return information about lower levels.
Example:
+1^GTM$DMOD
GTM>WRITE $STACK(1,"ecode")
GTM>WRITE $STACK(1,"place")
beg^dmex
GTM>WRITE $STACK(1,"mcode")
beg for read !,"Name:",namde do name
GTM>
This example shows that there was no error at $STACK level one, as well
as the "place" and "mcode" information for that level.
4 Using_ZSHOW_Ex_Context_Info
Using ZSHOW to Examine Context Information
The ZSHOW command displays information about the M environment.
Example:
GTM>ZSHOW "*"
$DEVICE=""
$ECODE=",M6,Z150373850,"
$ESTACK=2
$ETRAP=""
$HOROLOG="59149,36200"
$IO="/dev/pts/17"
$JOB=310051
$KEY=""
$PRINCIPAL="/dev/pts/17"
$QUIT=0
$REFERENCE=""
$STACK=2
$STORAGE=1072300032
$SYSTEM="47,gtm_sysid"
$TEST=1
$TLEVEL=0
$TRESTART=0
$X=0
$Y=23
$ZA=0
$ZB=$C(13)
$ZCMDLINE=""
$ZCOMPILE=""
$ZCSTATUS=0
$ZDIRECTORY="/ext1/home/"
$ZEDITOR=0
$ZEOF=0
$ZERROR="Unprocessed $ZERROR, see $ZSTATUS"
$ZGBLDIR="/ext1/home/mumps.gld"
$ZININTERRUPT=0
$ZINTERRUPT="IF $ZJOBEXAM()"
$ZIO="/dev/pts/17"
$ZJOB=0
$ZLEVEL=3
$ZMODE="INTERACTIVE"
$ZPOSITION="name+3^dmex"
$ZPROCESS=""
$ZPROMPT="GTM>"
$ZROUTINES=". /usr/library/gtm_dist"
$ZSOURCE=""
$ZSTATUS="150373850,name+3^dmex, %GTM-E-UNDEF, Undefined local
variable: bame"
$ZSYSTEM=0
$ZTRAP="B"
$ZVERSION="GT.M V4.3-001D AIX RS6000"
$ZYERROR=""
bame="?"
ln=12
name=""
/dev/pts/17 OPEN TERMINAL NOPAST NOESCA NOREADS TYPE WIDTH=80 LENG=24
name+3^dmex ($ZTRAP)
(Direct mode)
beg^dmex
^GTM$DMOD (Direct mode)
GTM>
This example uses the asterisk (*) argument to show all information
that ZSHOW offers in this context. First are the Intrinsic Special
Variables ($DEVICE-$ZYERROR, also available with ZSHOW "I"), then the
local variables (bame, ln and name, also available with ZSHOW "V"),
then the ZBREAK locations (name+3^dmex, also available with ZSHOW "B"),
then the device information (also available with ZSHOW "D"), then the M
stack (also available with ZSHOW "S"). ZSHOW "S" is the default for
ZSHOW with no arguments.
Context information that does not exist in this example includes M
LOCKs of this process (
ZSHOW "L").
In addition to directing its output to the current device, ZSHOW can
place its output in a local or global variable array. For more
information, refer to the ZSHOW section of the "Commands" chapter in
GT.M Programmer's Guide.
ZSHOW "V" produces the same output as ZWRITE with no arguments, but
ZSHOW "V" can be directed to a variable as well as a device.
3 Transf_Rtn_Control
Transferring Routine Control
The
ZGOTO command transfers control from one part of the routine to
another, or from one routine to another, using the specified entry
reference. The ZGOTO command takes an optional integer expression that
indicates the M stack level reached by performing the ZGOTO, and an
optional entry reference specifying the location to where ZGOTO
transfers control. A ZGOTO command, with an entry reference, performs a
function similar to the GOTO command with the additional capability of
reducing the M stack level. In a single operation, the process executes
$ZLEVEL-intexpr, implicit QUITs from DO or extrinsic operations, and a
GOTO operation transferring control to the named entry reference.
The ZGOTO command leaves the invocation stack at the level of the value
of the integer expression. GT.M implicitly terminates any intervening
FOR loops and unstacks variables stacked with NEW commands, as
appropriate.
ZGOTO $ZLEVEL:LABEL^ROUTINE takes the same action as GO LABEL^ROUTINE.
ZGOTO $ZLEVEL-1 produces the same result as QUIT (followed by
ZCONTINUE, if in Direct Mode).
If the integer expression evaluates to a value greater than the current
value of $ZLEVEL, or less than zero (0), GT.M issues a run-time error.
If ZGOTO has no entry reference, it performs some number of implicit
QUITs and transfers control to the next command at the specified level.
When no argument is specified, ZGOTO 1 is the result, and operation
resumes at the lowest level M routine as displayed by ZSHOW "S". In the
image invoked by mumps -direct, or a similar image, a ZGOTO without
arguments returns the process to Direct Mode.
3 Disp_Source_code
Displaying Source Code
Use the
ZPRINT command to display source code lines selected by its argument.
ZPRINT allows you to display the source for the current routine and any
other related routines. Use the ZPRINT command to display the last call
level.
Example:
GTM>ZPRINT beg
beg for read !,"Name: ",name do name
This example uses a ZPRINT command to print the line indicated as the
call at the top of the stack. Notice that the routine has an error in
logic. The line starting with the label beg has a FOR loop with no
control variable, no QUIT, and no GOTO. There is no way out of the FOR
loop.
3 Correct_Errs_in_M_Rtn
Correcting Errors in an M Routine
Now that the routine errors have been identified, correct them in the M
source file. Use
ZEDIT to invoke the editor and open the file for editing. Correct the
errors previously identified and exit the editor.
Example:
GTM>ZEDIT "dmex"
dmex ;dmex - Direct Mode example
;
beg for read !,"Name: ",name do name q:name="Q"
quit
name set ln=$l(name)
if ln,$e("QUIT",1,ln)=$tr(name,"quit","QUIT") d q
. s name="Q"
if ln<30,name?1.a.1"-".a1","1" "1a.ap do print q
write !,"Please use last-name, "
write "first-name middle-initial or 'Q' to Quit."
quit
print write !,$p(name,", ",2)," ",$p(name,", ")
quit
GTM>
This example shows the final state of a ZEDIT session of dmex.m. Note
that the infinite FOR loop at line beg is corrected.
3 Relink_Edited_Rtn
Relinking the Edited Routine
Use the ZLINK command to add the edited routine to the current image.
ZLINK automatically recompiles and relinks the routine. If the routine
was the most recent one ZEDITed or ZLINKed, you do not have to specify
the routine name with the ZLINK command.
You may have to issue a ZGOTO or a QUIT command to remove the
unedited version of the routine from the M invocation stack before
ZLINKing the edited version.
Example:
GTM>ZLINK
Cannot ZLINK an active routine
This illustrates a GT.M error report caused by an attempt to ZLINK a
routine that is part of the current invocation stack.
To ZLINK the routine, remove any invocation levels for the routine off
of the call stack. You may use the ZSHOW "S" command to display the
current state of the call stack. Use the QUIT command to remove one
level at a time from the call stack. Use the ZGOTO command to remove
multiple levels off of the call stack.
For further details and examples, refer to the GT.M Programmer's
Guide.
3 Reexec_the_Rtn
Re-executing the Routine
Re-display the DO command using the RECALL command.
Execute the routine using the DO command.
Example:
GTM>D ^dmex
Name: Revere, Paul
Paul Revere
Name: q
This example illustrates a successful execution of dmex.
3 Using_Forked_Proc
Using Forked Processes
The
ZSYSTEM command creates a new process called the child process, and
passes its argument to the shell for execution. The new process
executes in the same directory as the initiating process. The new
process has the same operating system environment, such as environment
variables and input/output devices, as the initiating process. The
initiating process pauses until the new process completes before
continuing execution.
Example:
GTM>ZSYSTEM
$ ls dmex.*
dmex.m dmex.o
$ ps
PID TTY TIME COMMAND
7946 ttyp0 0:01 sh
7953 ttyp0 0:00 gtm
7955 ttyp0 0:00 ps
$ exit
GTM>
This example uses ZSYSTEM to create a child process, perform some shell
actions, and return to GT.M.
1 Lang_Features_M
General Language Features of M
MUMPS is a general purpose language with an embedded database system.
This section of the help file describes the features of the language
that are not covered as Commands, Functions, or Intrinsic Special
Variables.
2 Data_Types
Data Types
M operates with a single basic data type, string. However, M evaluates
data using methods that vary according to context.
3 Num_Expressions
Numeric Expressions
When M syntax specifies a numexpr, M evaluates the data as a sequence
of ASCII characters that specify a number. M stops the evaluation and
provides the result generated from successfully evaluated characters
when it encounters any character that is not the following:
o A digit 0-9
o A plus sign (+) or minus sign (-) and also the first character in
the string
o The first decimal point (.) in the string
3 Num_Accuracy
Numeric Accuracy
GT.M provides 18 digits of accuracy, independent of the decimal point
(.) placement, and a numeric range from 10**(-43) to (10**47). Numbers
with three digits or fewer to the right of the decimal point are
precise.
3 Int_Expressions
Integer Expressions
When M syntax specifies an intexpr, M evaluates the data as it would a
numexpr except that it stops the evaluation at any decimal point
including the first.
3 Truth_valued_Expr
Truth-valued Expressions
When M syntax specifies a tvexpr, M evaluates the data as a numeric.
However, it stops the evaluation and returns a true value (1) as soon
as it encounters a non-zero digit, otherwise it returns a false value
(0). In other words, M treats expressions that have a non-zero numeric
value as true, and expressions that have a zero numeric value as false.
The sign and/or decimal have no affect on the evaluation of a
truth-valued expression.
2 M_Names
M Names
M uses names for variables, LOCK command arguments, labels on lines,
and routine names. M names are alphanumeric and must start with an
alphabetic character or a percent sign (%).
The percent sign can only appear as the first character in a name. By
convention, names starting with percent signs are generally
application-independent or distinguished in some similar way.
M does not reserve any names. That is, M always distinguishes keywords
by context. Therefore, M permits a variable or a label called SET even
though the language has a command called SET.
M names are case sensitive. That is, M treats ABC, Abc, ABc, AbC ABC,
and abc as six different names.
M does not restrict the length of names in the main body of the
standard. However, the portability section of the standard recommends
limiting names to a maximum of eight (8) characters. GT.M effectively
limits names to eight characters by ignoring any characters after the
first eight.
2 Variables
Variables
M does not require predefinition of variable type or size. M variables
are either local or global. Any variable may be unsubscripted or
subscripted.
3 Arrays_Subscripts
Arrays and Subscripts
In M, subscripted variables identify elements in sparse arrays. Sparse
arrays comprise existing subscripts and data nodes - no space is
reserved for potential data nodes. These arrays generally serve
logical, rather than mathematical, purposes.
M array subscripts are expressions, and are not restricted to numeric
values.
The format for an M global or local variable is:
[^]name[(expr1[,...])]
o The optional leading caret symbol (^) designates a global variable.
o The name specifies a particular array.
o The optional expressions specify the subscripts
o and must be enclosed in parentheses and separated by commas (,).
The body of the M standard places no restrictions on variable names.
However, the portability section of the standard does suggest limits on
the length of an individual subscript expression, and on the total
length of a variable name. The measurement for the length of names
includes the length of the global variable name itself, the sum of the
lengths of all the evaluated subscripts, and an allowance for an
overhead of two (2) times the number of subscripts. The total must not
exceed 237. For globals, GT.M permits this total to be modified with
GDE up to 255. For locals, GT.M limits the length of individual
subscripts to the maximum string length of 32,767. GT.M restricts the
number of subscripts for local or global variables to 32.
3 M_Collation_Seq
M Collation Sequences
M collates all canonic numeric subscripts ahead of all string
subscripts, including strings such as those with leading zeros that
represent non-canonic numbers. Numeric subscripts collate from negative
to positive in value order. String subscripts collate in ASCII
sequence. In addition, GT.M allows the empty string subscript in most
contexts, (the null, or empty, string collates ahead of all canonic
numeric subscripts).
GT.M allows definition of alternative collation sequences. For complete
information on enabling this functionality, refer to the
"Internationalization" chapter in GT.M Programmer's Guide.
3 Local_Variables
Local Variables
A local variable in M refers to a variable used solely within the scope
of a single process. Local variable names have no leading delimiter.
M makes a local variable available and subject to modification by all
routines executed within a process from the time that variable is first
SET until it is KILLed, or until the process stops executing M.
However, M "protects" a local variable after that variable appears as
an argument to a NEW command, or after it appears as an element in a
formalist used in parameter passing. When M protects a local variable,
it saves a copy of the variable's value and makes that variable
undefined. M restores the variable to its saved value during execution
of the QUIT that terminates the process stack level associated with the
"protecting" NEW or formalist. For more information on NEW and QUIT,
refer to the "Commands" chapter in GT.M Programmer's Guide.
M restricts the following uses of variables to local variables:
o FOR command control variables.
o Elements within the parentheses of an "exclusive" KILL.
o TSTART [with local variables list].
o A KILL with no arguments removes all current local variables.
o NEW command arguments.
Actualnames used by pass-by-reference parameter passing.
3 Glob_Var_Resrc_Nam_Env
Global Variables and Resource Name Environments
M recognizes an optional environment specification in global names or
in the LOCK resource names (nrefs), which have analogous syntax. Global
variable names have a leading caret symbol (^) as a delimiter.
M makes a global variable available, and subject to modification by all
routines executed within all processes in an environment, from the time
that variable is first SET until it is KILLed.
4 Naked_References
Naked References
M accepts an abbreviation of the global name under some circumstances.
When the leading caret symbol (^) immediately precedes the left
parenthesis delimiting subscripts, the global variable reference is
called a naked reference. M evaluates a naked reference by prefixing
the last used global variable name, except for its last subscript, to
the list of subscripts specified by the naked reference. The prefixed
portion is known as the naked indicator. An attempt to use a naked
reference when the prior global reference does not exist, or did not
contain a subscript, generates an error.
Because M has only one process-wide naked indicator which it maintains
as a side affect of every evaluation of a global variable, using the
naked reference requires an understanding of M execution sequence. M
execution generally proceeds from left to right within a line, subject
to commands that change the flow of control. However, M evaluates the
portion of a SET command argument to the right side of the equal sign
before the left side. Also, M does not evaluate any further $SELECT()
arguments within the function after it encounters a true selection
argument.
In general, using naked references only in very limited circumstances
prevents problems associated with the naked indicator.
4 Glob_Var_Name_Env
Global Variable Name Environments
M recognizes an optional environment specification in global names. The
environment specification designates one of some set of alternative
database files.
The syntax for global variable names that include an environment
specification is:
^|expr|name[(subscript[,...])]
In GT.M, the expression identifies the Global Directory for mapping the
global variable.
Environment specifications permit easy access to global variables in
alternative databases, including other "copies" of active variables in
the current database. Environment specifications are sometimes referred
to as extended global syntax or extended value syntax.
GT.M also allows:
^|expr1,expr2|name[(subscript[,...])]
Where the first expression identifies the Global Directory and the
second expression is accepted but ignored by GT.M.
To improve compatibility with some other M implementations, GT.M also
accepts another non-standard syntax. In this syntax, the leading and
trailing up-bar (|) are respectively replaced by a left square-bracket
([) and a right square-bracket (]). This syntax also requires
expratoms, rather than expressions.
The formats for this non-standard syntax are:
^[expratom1]name[(subscript...)]
or
^[expratom1,expratom2]name[(subscript...)]
Where expratom1 identifies the Global Directory and expratom2 is a
dummy variable. Note that the first set of brackets in each format is
part of the syntax. The second set of square brackets is part of the
meta-language identifying an optional element.
Example:
$ gtmgbldir=Test.GLD
$ export gtmgbldir
$ GTM
GTM>WRITE $ZGBLDIR
TEST.GLD
GTM>WRITE ^A
THIS IS ^A IN DATABASE RED
GTM>WRITE ^|"M1.GLD"|A
THIS IS ^A IN DATABASE WHITE
GTM>WRITE $ZGBLDIR
TEST.GLD
GTM>HALT
$ echo gtmgbldir
TEST.GLD
The statement WRITE ^|"M1.GLD"|A writes variable ^A using the Global
Directory, M1.GLD, but does not change the current Global Directory.
Example:
GTM>WRITE $ZGBLDIR
M1.GLD
GTM>WRITE ^A
THIS IS ^A IN DATABASE WHITE
GTM>WRITE ^|"M1.GLD"|A
THIS IS ^A IN DATABASE WHITE
The statement WRITE ^|"M1.GLD"|A is equivalent to WRITE ^A.
Specifying separate Global Directories does not always translate to
using separate databases.
Example:
GTM>WRITE ^|"M1.GLD"|A,!,^|"M2.GLD"|A,!,^|"M3.GLD"
|A,!
THIS IS ^A IN DATABASE WHITE
THIS IS ^A IN DATABASE BLUE
THIS IS ^A IN DATABASE WHITE
In this example, the WRITE does not display ^A from three GT.M database
files. Mapping specified by the Global Directory Editor (GDE)
determines the database file to which a Global Directory points.
This result could have occurred under the following mapping:
^|"M1.GLD"|A --> REGIONA --> SEGMENTA --> FILE1.DAT
^|"M2.GLD"|A --> REGIONA --> SEGMENT1 --> FILE2.DAT
^|"M3.GLD"|A --> REGION3 --> SEGMENT3 --> FILE1.DAT
For more information on Global Directories, refer to the "Global
Directory Editor" chapter of the GT.M Administration and Operations
Guide.
4 Opt_GTM_Env_Trans_Facility
Optional GT.M Environment Translation Facility
For users who wish to dynamically (at run-time) determine a global
directory from non-global directory information (typically UCI and VOL)
in the environment specification, GT.M provides an interface to add an
appropriate translation.
Using this facility impacts the performance of every global access that
uses environment specification. Make sure you use it only when static
determination of the global directory is not feasible. When used, make
every effort to keep the translation routines very efficient.
The use of this facility is enabled by the definition of the
environment variable gtm_env_translate, which contains the path of a
shared library with the following entry point:
5 gtm_env_xlate
gtm_env_xlate
If the shared object is not accessible or the entry point is not
accessible, GT.M reports an error.
The gtm_env_xlate() routine has the following C prototype:
int gtm_env_xlate(xc_string_t *in1, xc_string_t *in2, xc_string *in3,
xc_string_t *out)
where xc_string_t is a structure defined in gtmxc_types.h as follows:
typedef struct
{
int length;
char *address;
} xc_string_t;
The purpose of the function is to use its three input arguments to
derive and return an output argument that can be used as an environment
specification by GT.M. Note that the input values passed (in1, in2 and
in3) are the result of M evaluation and must not be modified. The first
two arguments are the expressions passed within the up-bars "| |" or
the square-brackets "[ ]", and the third argument is the current
working directory as described by $ZDIRECTORY.
A return value other than zero (0) indicates an error in translation,
and is reported by a GT.M error
If the length of the output argument is non-zero, GT.M appends a
secondary message of GTM-I-TEXT, containing the text found at the
address of the output structure.
GT.M does not do any memory management related to the output argument -
space for the output should be allocated by the external routine. The
routine must place the returned environment specification at the
address it has allocated and adjust the length accordingly. On a
successful return, the return value should be zero. If the translation
routine must communicate an error to GT.M, it must return a non-zero
value, and if it is to communicate additional error information, place
the error text at the address where the environment would normally go
and adjust the length to match the length of the error text.
Length of the return value may range from 0-32767, otherwise GT.M
reports an error.
A zero-length (empty) string specifies the current value of $ZGBLDIR.
Non-zero lengths must represent the actual length of the file
specification pointed to by address, excluding any <NUL> terminator. If
the address field of the output argument is NULL, GT.M issues an error.
The file specification may be absolute or relative and may contain an
environment variable. If the file specified is not accessible, or is
not a valid global directory, GT.M reports errors in the same way it
does for any invalid global directory.
It is possible to write this routine in M (as a call-in), however,
global variables in such a routine would change the naked indicator,
which environment references normally do not. Depending on the
conventions of the application, there might be difficult name-space
management issues such as protecting the local variables used by the M
routine.
While it is possible for this routine to take any form that the
application designer finds appropriate within the given interface
definition, the following paragraphs make some recommendations based on
the expectation that a routine invoked for any more than a handful of
global references should be efficient.
It is expected that the routine loads one or more tables, either at
compilation or the first time it is invoked. The logic of the routine
performs a look up on the entry in the set of tables. The lookup might
be based on the length of the strings and some unique set of characters
in the names, or a hash, with collision provisions as appropriate.
The routine may have to deal with a case where one or both of the
inputs have zero length. A subset of these cases may have the first
string holding a comma limited string that needs to be re-interpreted
as being equivalent to two input strings (note that the input strings
must never be modified). The routine may also have to handle cases
where a value (most likely the first) is accidentally or intentionally,
already a global directory specification.
Example:
> cat gtm_env_translate.c
#include <stdio.h>
#include <string.h>
#include "gtmxc_types.h"
static int init = 0;
typedef struct
{
xc_string_t field1, field2, ret;
} line_entry ;
static line_entry table[5], *line, linetmp;
/* Since these errors may occur before setup is complete, they are
statics */
static char *errorstring1 = "Error in function initialization,
environment variable GTM_CALLIN_START not defined. Environment
translation failed.";
static char *errorstring2 = "Error in function initialization, function
pointers could not be determined. Envrironment translation failed.";
#define ENV_VAR "GTM_CALLIN_START"
typedef int (*int_fptr)();
int_fptr GTM_MALLOC;
int init_functable(xc_string_t *ptr)
{
/* This function demonstrates the initialization of other function
pointers as well (if the user-code needs them for any reason, they
should be defined as globals)*/
char *pcAddress;
long lAddress;
void **functable;
void (*setup_timer) ();
void (*cancel_timer) ();
pcAddress = getenv(ENV_VAR);
if (pcAddress == NULL)
{
ptr->length = strlen(errorstring1);
ptr->address = errorstring1;
return 1;
}
lAddress = -1;
lAddress = atol(pcAddress);
if (lAddress == -1)
{
ptr->length = strlen(errorstring2);
ptr->address = errorstring2;
return 1;
}
functable = (void *)lAddress;
setup_timer = (void(*)()) functable[2];
cancel_timer = (void(*)()) functable[3];
GTM_MALLOC = (int_fptr) functable[4];
return 0;
}
void copy_string(char **loc1, char *loc2, int length)
{
char *ptr;
ptr = (char *) GTM_MALLOC(length);
strncpy( ptr, loc2, length);
*loc1 = ptr;
}
int init_table(xc_string_t *ptr)
{
int i = 0;
char buf[100];
char *buf1, *buf2;
FILE *tablefile;
char *space = " ";
char *errorstr1 = "Error opening table file table.dat";
char *errorstr2 = "UNDETERMINED ERROR FROM GTM_ENV_XLATE";
if ((tablefile = fopen("table.dat","r")) == (FILE *)NULL)
{
ptr->length = strlen(errorstr1);
copy_string(&(ptr->address), errorstr1, strlen(errorstr1));
return 1;
}
while (fgets(buf, (int)SIZEOF(buf), tablefile) != (char *)NULL)
{
line= &table[i++];
buf1 = buf;
buf2 =strstr(buf1, space);
line->field1.length = buf2 - buf1;
copy_string( &(line->field1.address), buf1, line->field1.length);
buf1 = buf2+1;
buf2 = strstr(buf1, space);
line->field2.length = buf2-buf1;
copy_string( &(line->field2.address), buf1, line->field2.length);
buf1 = buf2+1;
line->ret.length = strlen(buf1) - 1;
copy_string( &(line->ret.address), buf1, line->ret.length);
}
fclose(tablefile);
/* In this example, the last entry in the table is the error string
*/
line = &table[4];
copy_string( &(line->ret.address), errorstr2, strlen(errorstr2));
line->ret.length = strlen(errorstr2);
return 0;
}
int cmp_string(xc_string_t str1, xc_string_t str2)
{
if (str1.length == str2.length)
return strncmp(str1.address, str2.address, (int) str1.length);
else
return str1.length - str2.length;
}
int cmp_line(line_entry *line1, line_entry *line2)
{
return (((cmp_string(line1->field1,
line2->field1))||(cmp_string(line1->field2, line2->field2))));
}
int look_up_table(line_entry *aline, xc_string_t *ret_ptr)
{
int i;
int ret_v;
for(i=0;i<4;i++)
{
line = &table[i];
ret_v = cmp_line( aline, line);
if (!ret_v)
{
ret_ptr->length = line->ret.length;
ret_ptr->address = line->ret.address;
return 0;
}
}
/*ERROR OUT*/
line = &table[4];
ret_ptr->length= line->ret.length;
ret_ptr->address = line->ret.address;
return 1;
}
int gtm_env_xlate(xc_string_t *ptr1, xc_string_t *ptr2, xc_string_t
*ptr_zdir, xc_string_t *ret_ptr)
{
int return_val, return_val_init;
if (!init)
{
return_val_init = init_functable(ret_ptr);
if (return_val_init) return return_val_init;
return_val_init = init_table(ret_ptr);
if (return_val_init) return return_val_init;
init = 1;
}
linetmp.field1.length= ptr1->length;
linetmp.field1.address= ptr1->address;
linetmp.field2.length= ptr2->length;
linetmp.field2.address= ptr2->address;
return_val = look_up_table(&linetmp, ret_ptr);
return return_val;
}
> cat table.dat
day1 week1 mumps
day2 week1 a
day3 week2 b
day4 week2 c.gld
This example demonstrates the mechanism. A table is set up the first
time for proper memory management, and for each reference, a table
lookup is performed. Note that for the purpose of simplicity, no error
checking is done, so table.dat is assumed to be in the correct format,
and have exactly four entries.
2 Literals
Literals
M has both string and numeric literals.
3 String_Literals
String Literals
String literals (strlit) are enclosed in quotation marks (" ") and must
only contain graphic characters. In other words, control characters
(ASCII 0-31 and 127) cannot appear in a strlit. M attempts to use
character text that appears outside of quotation mark delimiters
according to context, which generally means as a local variable name.
To include a quotation mark (") within a strlit, use a set of two
quotation marks ("" "").
Example:
GTM>WRITE """"
"
GTM>
The WRITE displays a single quotation mark because the first quotation
mark delimits the beginning of the string literal, the next two
quotation marks denote a single quote within the string, and the last
quotation mark delimits the end of the string literal.
Use the $CHAR function and the concatenation operator to include
control characters within a string.
Example:
GTM>WRITE "A"_$CHAR(9)_"B"
A B
GTM>
The WRITE displays an "A," followed by a tab (<HT>), followed by a "B"
using $CHAR(), to introduce the non-graphic character.
3 Numeric_Literals
Numeric Literals
In M, numeric literals (numlit) are entered without surrounding
delimiters.
Example:
GTM>WRITE 1
1
GTM> WRITE 1.1
1.1
These display numeric literals that are integer and decimal.
M also accepts numeric literals in the form of a mantissa and an
exponent, separated by a delimiter of "E" in uppercase. The mantissa
may be an integer or a decimal fraction. The integer exponent may have
an optional leading minus sign (-).
Example:
GTM>WRITE 8E6
8000000
GTM> WRITE 8E-6
.000008
GTM>
2 Expressions
Expressions
The following items are legal M expression atoms (expratom). An
expression atom is a component of an M expression.
o Local variables
o Global variables
o Intrinsic special variables
o Intrinsic functions
o Extrinsic functions
o Extrinsic special variables
o Numeric literals
o String literals
o An expression enclosed in parentheses
o Any of the above preceded by a unary operator
In addition, any of these items may be combined with a binary operator
and another expression atom.
2 Operators
Operators
M has both unary and binary operators.
3 Precedence
Precedence
All unary operations have right to left precedence.
All M binary operations have strict left to right precedence. This
includes all arithmetic, string, and logical operations. Hierarchies of
operations require explicit establishment of precedence using
parentheses (). Although this rule is counterintuitive, it is easy to
remember and has no exceptions.
3 Arithmetic_Operators
Arithmetic Operators
All arithmetic operators force M to evaluate the expressions to which
they apply as numeric. The arithmetic operators are:
+ as a unary operator simply forces M to evaluate the expression
following as numeric; as a binary operator it causes M to perform
addition.
- as a unary operator causes M to negate the expression following;
as a binary operator it causes M to perform subtraction.
* binary operator for multiplication.
** binary operator for exponentiation.
/ binary operator for fractional division.
\ binary operator for integer division.
# binary operator for modulo, that is, causes M to produce the
remainder from integer division of the first argument by the
second.
Remember that precedence is left to right for all arithmetic operators.
Example:
GTM>WRITE 1+1
2
GTM>WRITE 2-1
1
GTM>WRITE 2*2
4
GTM>WRITE 3**2
9
GTM>WRITE 4/2
2
GTM>WRITE 7
2
GTM>WRITE 7#3
1
GTM>
This simple example demonstrates how each arithmetic binary operation
uses numeric literals.
Example:
GTM>WRITE +"12ABC"
12
GTM>WRITE --"-3-4"
-3
GTM>
The first WRITE shows the unary plus sign (+) operation forcing the
numeric evaluation of a string literal. The second WRITE demonstrates
the unary minus sign (-). Note the second minus sign within the string
literal does not cause subtraction, but rather, terminates the numeric
evaluation with the result of negative three (-3). Each of the leading
minus signs causes one negation and therefore, the result is negative
three (-3).
3 Logical_Operators
Logical Operators
M logical operators always produce a result that is TRUE (1) or FALSE
(0). All logical operators force M to evaluate the expressions to which
they apply as truth-valued. The logical operators are:
' unary NOT operator negates current truth-value; M accepts
placement of the NOT operator next to a relational operator, for
example, A'=B as meaning '(A=B).
& binary AND operator produces a true result only if both of the
expressions are true.
! binary OR operator produces a true result if either of the
expressions is true.
Remember that precedence is always left to right, and that logical
operators have the same precedence as all other operators.
Example:
GTM>WRITE '0
1
GTM>WRITE '1
0
GTM>WRITE '5689
0
GTM>WRITE '-1
0
GTM>WRITE '"ABC"
1
GTM>
The above example demonstrates the unary NOT operation. Note that any
non-zero numeric value is true and has a false negation.
Example:
GTM>WRITE 0&0
0
GTM>WRITE 1&0
0
GTM>WRITE 0&1
0
GTM>WRITE 1&1
1
GTM>WRITE 2&1
1
GTM>WRITE 0!0
0
GTM>WRITE 1!0
1
GTM>WRITE 0!1
1
GTM>WRITE 1!1
1
GTM>WRITE 2!1
1
GTM>
The above example demonstrates all cases covered by the binary logical
operators.
3 String_Operators
String Operators
All string operators force M to evaluate the expressions to which they
apply as strings. The string operator is:
_ binary operator causes M to concatenate the second expression
with the first expresion
Example:
GTM>WRITE "B"_"A"
BA
GTM>WRITE "A"_1
A1
GTM>
The above example demonstrates M concatenation.
3 Num_Relational_Operators
Numeric Relational Operators
M relational operators always generate a result of TRUE (1) or FALSE
(0). All numeric relational operators force M to evaluate the
expressions to which they apply as numeric. The numeric relational
operators are:
> binary arithmetic greater than
< binary arithmetic less than
The equal sign (=) does not force numeric evaluation, and should be
viewed as a string operator. However, the equal sign between two
numeric values tests for numeric equality.
Other numeric relations are formed using the logical NOT operator
apostrophe (') as follows:
'> not greater than, that is, less than or equal to
'< not less than, that is, greater than or equal to
'= not equal, numeric or string operation
Example:
GTM>WRITE 1>2
0
GTM>WRITE 1<2
1
GTM>
The above example demonstrates the basic arithmetic relational
operations.
Example:
GTM>WRITE 1'<2
0
GTM>WRITE 2'<1
1
GTM>
The above example demonstrates combinations of arithmetic, relational
operators with the logical NOT operator.
3 Str_Relational_Operators
String Relational Operators
M relational operators always generate a result of TRUE (1) or FALSE
(0). All string relational operators force M to evaluate the
expressions to which they apply as strings. The string relational
operators are:
= binary operator causes M to produce a TRUE if the expressions are
equal.
[ binary operator causes M to produce a TRUE if the first
expression contains the ordered sequence of characters in the
second expression.
] binary operator causes M to produce a TRUE if the first
expression lexically follows the second expression in the character
encoding sequence, which by default is ASCII.
]] binary operator causes M to produce a TRUE if the first
expression lexically sorts after the second expression in the
subscript collation sequence.
Note that all non-empty strings lexically follow the empty string, and
every string contains the empty string.
Other string relations are formed using the logical NOT operator
apostrophe (') as follows:
'[ does not contain.
'] does not follow, that is, lexically less than or equal to.
']] does not sort after, that is, lexically less than or equal to
in the subscript collation sequence.
'= not equal, numeric or string operation.
Example:
GTM>WRITE "A"="B"
0
GTM>WRITE "C"="C"
1
GTM>WRITE "A"["B"
0
GTM>WRITE "ABC"["C"
1
GTM>WRITE "A"]"B"
0
GTM>WRITE "B"]"A"
1
GTM>WRITE "A"]]"B"
0
GTM>WRITE "B"]]"A"
1
These examples demonstrate the string relational operators using string
literals.
Example:
GTM>WRITE 2]10
1
GTM>WRITE 2]]10
0
GTM>WRITE 0]"$"
1
GTM>WRITE 0]]"$"
0
These examples illustrate that when using the primary ASCII character
set, the main difference in the "follows" (]) operator and the
"sorts-after" (]]) operator is the way they treat numbers.
Example:
GTM>WRITE 1=1
1
GTM>WRITE 1=2
0
GTM>WRITE 1="1"
1
GTM>WRITE 1=01
1
GTM>WRITE 1="01"
0
GTM>WRITE 1=+"01"
1
GTM>
These examples illustrate the dual nature of the equal sign operator.
If both expressions are string or numeric, the results are straight
forward. However, when the expressions are mixed, the native string
data type prevails.
Example:
GTM>WRITE "a"'="A"
1
GTM>WRITE "FRED"'["RED"
0
GTM>WRITE "ABC"']""
0
These examples demonstrate combinations of the string relational
operators with the NOT operator.
3 Pat_Match_Operator
Pattern Match Operator
The pattern match operator (?) causes M to return a TRUE if the
expression ahead of the operator matches the characteristics described
by the pattern following the operator. The pattern is not an
expression.
Patterns are made up of two elements:
o A repetition count
o A pattern code, a string literal or an alternation list
The element following the pattern match operator may consist of an
indirection operator, followed by an element that evaluates to a
legitimate pattern.
The repetition count consists of either a single integer literal or a
period (.) delimiter with optional leading and trailing integer
literals. A single integer literal specifies an exact repetition count.
The period syntax specifies a range of repetitions where the leading
number is a minimum and the trailing number is a maximum. When the
repetition count is missing the leading number, M assumes there is no
minimum, (i.e., a minimum of zero). When the repetition count is
missing the trailing number, M does not place a maximum on the number
of repetitions.
The pattern codes are:
A alphabetic characters upper or lower case
C control characters ASCII 0-31 and 127
E any character; used to pass all characters in portions of the
string where the pattern is not restricted
L lower-case alphabetic characters, ASCII 97-122
N digits 0-9, ASCII 48-57
P punctuation, ASCII 32-47, 58-64, 91-96, 123-126
U upper-case alphabetic characters, ASCII 65-90
Pattern codes may be upper or lower case and may be replaced with a
string literal. GT.M allows the M pattern match definition of patcodes
A, C, N, U, L, and P to be extended or changed, (A can only be modified
implicitly by modifying L or U) and new patcodes added. For detailed
information on enabling this functionality, refer to the
"Internationalization" chapter in GT.M Programmer's Guide.
The GT.M compiler accepts pattern codes other than those explicitly
defined above. If, at run-time, the pattern codes come into use and
no pattern definitions are available, GT.M issues a run-time error
(PATNOTFOUND). GT.M does not currently implement a mechanism for Y
and Z patterns and continues to treat those as compile-time syntax
errors.
Example:
GTM>WRITE "ABC"?3U
1
GTM>WRITE "123-45-6789"?3N1"-"2N1"-"4N
1
The first WRITE has a simple one-element pattern while the second has
multiple elements including both codes and string literals. All the
repetition counts are fixed.
Example:
I x?.E1C.E W !,"Must not contain a control character" Q
This example uses a pattern match to test for control characters.
Example:
I acn?1U.20A1","1U.10A D
.S acn=$G((^ACX($P(acn,","),$P(acn,",",2)))
This example uses a pattern match with implicit minimums to determine
that an "account number" is actually a name, and to trigger a look-up
of the corresponding account number in the ^ACX cross index.
The pattern match operator accepts the alteration syntax. Alteration
consists of a repeat count followed by a comma-delimited list of
patatoms enclosed in parentheses "()". The semantic is that the pattern
matches if any of the listed patterns matches the operand string. For
example, ?1(2N1"-"7N,3N1"-"2N1"-"4N).1U might be a way to match either
a social security number or a taxpayer ID. Since alternation is defined
as one of the ways of constructing a patatom, alternation can nest (be
used recursively).
Complex pattern matches may not be efficient to evaluate, so every
effort should be made to simplify any commonly used pattern and to
determine if more efficient alternative logic would be more
appropriate.
2 Gen_M_Comm
General M Commands
M commands may be abbreviated to a defined prefix. Most commands have
arguments. However, some commands have either optional arguments or no
arguments. When a command has no argument and is followed by more
commands on the same line, at least two spaces (<SP>) must follow the
command without arguments. Commands that accept arguments generally
accept multiple arguments on the same command. M treats multiple
arguments the same as multiple occurrences of the same command, each
with its own argument.
3 Postconditionals
Postconditionals
M provides postconditionals as a tool for placing a condition on the
execution of a single command and, in some cases, a single command
argument. A postconditional consists of a colon (:) delimiter followed
by a truth-valued expression. When the expression evaluates to true, M
executes the command occurrence. When the expression evaluates to
false, M does not execute the command occurrence.
4 Comm_Postconditionals
Command Postconditionals
Command postconditionals appear immediately following a command and
apply to all arguments for the command when it has multiple arguments.
All commands except commands that themselves have a conditional aspect
accept a command postconditional. Among the M standard commands, ELSE,
FOR, and IF do not accept command postconditionals. All the GT.M
command extensions accept command postconditionals.
4 Arg_Postconditionals
Argument Postconditionals
Commands that affect the flow of control may accept postconditionals on
individual command arguments. Because multiple arguments act as
multiple commands, this is a straight-forward application of the same
principal as command postconditional. The only M standard commands that
accept argument postconditionals are DO, GOTO, and XECUTE. The GT.M
command extensions that accept argument postconditionals are BREAK,
ZGOTO, and ZSYSTEM.
3 Timeouts
Timeouts
M provides timeouts as a tool to retain program control over commands
of indefinite duration. A timeout consists of a colon (:) delimiter on
an argument, followed by a numeric expression specifying the number of
seconds for M to attempt to execute the command. When the timeout is
zero (0), M makes a single attempt to complete the command.
GT.M has been designed to allow large timeout values, and to protect
against arithmetic overflow when converting large timeout values to
internal representations. When a command has a timeout, M maintains the
$TEST intrinsic special variable as the command completes. If the
command completes successfully, M sets $TEST to TRUE (1). If the
command times out before successful completion, M sets $TEST to FALSE
(0). When a command argument does not specify a timeout, M does not
maintain $TEST.
The following commands accept timeouts:
o LOCK
o JOB
o OPEN
o READ
o ZALLOCATE
When a READ times out, M returns any characters that have arrived
between the start of the command and the timeout. M does not produce
any partial results for any of the other timed commands.
2 Gen_M_Intrin_Func
General M Intrinsic Functions
M Intrinsic Functions start with a single dollar sign ($) and have one
or more arguments enclosed in parentheses () and separated by commas
(,). These functions provide an expression result by performing actions
that would be impossible or difficult to perform using M commands. It
is now possible to invoke a C function in a package via the external
call mechanism.
2 Gen_M_Intr_Spec_Var
General M Intrinsic Special Variables
M Intrinsic Special Variables start with a single dollar sign ($). GT.M
provides such variables for program examination. In some cases, the
Intrinsic Special Variables may be SET to modify the corresponding part
of the environment.
2 Routines
Routines
M routines have a name and consist of lines of code followed by an
end-of-record which is a carriage return, formfeed (<CR><FF>) sequence.
M separates the name of a routine from the body of the routine with an
end-of-line which is a carriage-return, line-feed (<CR><LF>) sequence.
GT.M stores routine sources in UNIX files and implicitly supplies the
end-of-record and end-of-line character sequences.
In M, a routine has no particular impact on variable management and may
include code that is invoked at different times and has no logical
intersection.
3 Lines
Lines
A line of M code consists of the following elements in the following
order:
o An optional label.
o A line-start delimiter. The standard defines the line-start
delimiter as a space (<SP>) character. In order to enhance routine
readability, GT.M extends M by accepting one or more tab (<HT>)
characters as line-start delimiters.
o Zero or more level indicators, which are periods (.). The level
indicators show the level of nesting for argumentless DO commands:
the more periods, the deeper the nesting. M ignores lines that
contain level indicators unless they directly follow an
argumentless DO command with a matching level of nesting.
o Zero or more commands and their arguments. M accepts multiple
commands on a line. The argument(s) of one command are separated
from the next command by a command-start delimiter, consisting of
one or more spaces (<SP>).
o A terminating end-of-line, which is a carriage return, line feed
(<CR><LF>) sequence.
4 Labels
Labels
In addition to labels that follow the rules for M names, M accepts
labels consisting only of digits. In a label consisting only of digits,
leading zeros are considered significant. For example, labels 1 and 01
are different. Formalists may immediately follow a label. A Formalists
consists of one or more names enclosed in parentheses (). Formalists
identify local variables that "receive" passed values in M parameter
passing.
In GT.M, a colon (:) delimiter may be appended to the label, which
causes the label to be treated as "local." Within the routine in which
they appear, they perform exactly as they would without the trailing
colon but they are inaccessible to other routines. Using local labels
reduces object size and linking overhead, for both ZLINK and host
linking.
4 Comments
Comments
In addition to commands, a line may also contain a comment that starts
with a leading semi-colon (;) delimiter. The scope of a comment is the
remainder of the line. In other words, M ignores anything to the right
of the comment delimiter. The standard defines the comment delimiter
(;) as it would a command, and therefore requires that it always appear
after a linestart. GT.M extends the standard to permit comments to
start at the first character of a line or in an argument position.
3 Entry_Ref
Entry References
M entryrefs provide a generalized target for referring to a line within
a routine. An entryref may contain some combination of a label, an
offset, and a routine name (in that order). The offset is delimited by
a plus sign (+) and the routinename is delimited by a caret symbol(^).
When an entryref does not contain a label, M assumes the offset is from
the beginning of the routine. When an entryref does not contain an
offset, M uses an offset of zero (0). When an entryref does not contain
a routine name, M assumes the routine that is currently executing.
M permits every element in an entryref to have the form of an
indirection operator, followed by an element that evaluates to a
legitimate occurrence of that portion of the entryref.
While most commands and functions that use entryrefs permit
argument indirection, M does not accept indirection that resolves
to a combination of label and offset or offset and routine name.
Offsets provide an extremely useful tool for debugging. However, avoid
their use in production code because they generally produce maintenance
problems.
3 Label_Ref
Label References
M labelrefs are a subset of entryrefs that exclude offsets and separate
indirection. Labelrefs are used with parameter passing.
2 Indirection
Indirection
M provides indirection as a means to defer definition of elements of
the code until run-time. Indirection names a variable that holds or
"points" to the element. The indirection operator is the "at" symbol
(@).
3 Arg_Indirection
Argument Indirection
Most commands accept indirection of their entire argument.
Example:
GTM>SET x="^INDER"
GTM>DO @x
This example is equivalent to DO ^INDER.
3 Atomic_Indirection
Atomic Indirection
Any expratom or any local or global variable name may be replaced by
indirection.
Example:
GTM>SET x="HOOP",b="x"
GTM>WRITE a="HULA "__@b
HULA HOOP
GTM>
This example uses indirection within a concatenation operation.
3 Entryref_Indirection
Entryref Indirection
Any element of an entryref may be replaced by indirection.
Example:
GTM>SET lab="START",routine="PROG"
GTM>DO @lab^@routine
This example is equivalent to DO START^PROG.
3 Patt_Code_Indirection
Pattern Code Indirection
A pattern code may be replaced by indirection.
Example:
GTM>FOR p="1U.20A1"",""1U.20A",5N IF x?@p QUIT
GTM>ELSE WRITE !,"Incorrect format" QUIT
This example uses pattern code indirection to test x for either a name
or a number.
3 Name_Indirection
Name Indirection
Indirection may replace the prefix of a subscripted global or local
variable name. This "name" indirection requires two indirection
operators, a leading operator similar to the other forms of
indirection, and a trailing operator marking the transition to those
subscripts that are not specified by indirection.
Example:
GTM>SET from="B",to="^A(15),x=""
GTM>FOR SET x=$O(@from@(x)) Q:x="" S @to@(x)=@from@(x)
This example uses name indirection to copy the level contents of a
local array to a part of a global array. The example assumes that all
existing first level nodes of variable B have data.
3 Indirection_Concerns
Indirection Concerns
M indirection provides a very powerful tool for allowing program
abstraction. However, because indirection is frequently unnecessary and
has some disadvantages, use it carefully.
Because routines that use indirection in some ways do not contain
adequate information for easy reading, such routines tend to be more
difficult to debug and maintain.
To improve run-time performance, GT.M tends to move work from run-time
to compile-time. Indirection forces compiler actions to occur at
run-time, which minimizes the benefits of compilation.
M allows most forms of indirection to be recursive. However, in real
applications, recursive indirection typically makes the code obscure
and slow.
There are circumstances where indirection serves a worthwhile purpose.
For instance, certain utility functions with a general nature may be
clearly abstracted and coded using indirection. Because M has no "CASE"
command, DO (or GOTO) with argument indirection provides a clear
solution to the problem of providing complex branching.
Some M users prototype with indirection and then replace indirection
with generated code that reduces run-time overhead. In any case, always
consider whether indirection can be replaced with a clearer or more
efficient approach.
2 Param_Passing
Parameter Passing
Parameter passing provides a way of explicitly controlling some or all
of the variable context transferred between M routines.
M uses parameter passing for:
o A DO command with parameters
o Extrinsic functions and special variables
Parameter passing is optional on DO commands.
Parameter passing uses two argument lists: the actuallist that
specifies the parameters that M passes to an invoked routine, and the
formalist that specifies the local variables to receive or associate
with the parameters.
3 Actuallists
Actuallists
An actuallist specifies the parameters M passes to the invoked routine.
The actuallist contains a list of zero or more parameters enclosed in
parentheses, immediately following a DO or extrinsic function.
An actuallist:
o Is made up of items separated by commas
o Contains expressions and/or actualnames. Items may be missing, that
is, two commas may appear next to each other, with nothing between
them.
o Must be used in an invocation of a label with a formallist, except
in the case of extrinsic special variables.
o Must not contain undefined variables.
o Must not have more items than a formallist with which it is used.
o May contain the same item in more than one position.
Example:
GTM>DO MULT(3,X,.RESULT)
This example illustrates a DO with parameters. The actuallist contains:
o 3 - a numeric literal
o X - a local variable
o .RESULT - an actualname
3 Actualnames
Actualnames
An actualname starts with a leading period (.) delimiter, followed by
an unsubscripted local variable name. Actualnames identify variables
that are passed by reference, as described in a subsequent section.
While expressions in an actualname are evaluated when control is
transferred to a formallabel, the variables identified by actualnames
are not; therefore, they do not need to be defined at the time control
is transferred.
3 Formallists
Formallists
A formallist specifies the variables M uses to hold passed values. A
formallist contains a list of zero or more parameters enclosed in
parentheses, immediately following a label.
A formallist:
o Is made up of items separated by commas.
o Contains unsubscripted local variable names.
o Must be used and only used with a label invoked with an actuallist
or an extrinsic.
o May contain undefined variables.
o May have more items than an actuallist with which it is used.
o Must not contain the same item in more than one position.
o Must contain at least as many items as the actuallist with which it
is used.
Example:
MULT(MP,MC,RES)
SET RES=MP*MC
QUIT RES
In this example, illustrating a simple parameterized routine, the
formallist contains the following items:
o MP
o MC
o RES
An example in the section describing "Actuallists" shows an invocation
that matches this routine.
3 Formallabel
Formallabel
A label followed by a formallist is called a formallabel.
3 Param_Pass_Operation
Parameter Passing Operation
M performs an implicit NEW on the formallist names and replaces the
formallist items with the actuallist items.
M provides the actuallist values to the invoked procedure by giving
each element in the formallist the value or reference provided by the
corresponding element in the actuallist. M associates the first name in
the formallist with the first item in the actuallist, the second name
in the formallist with the second item in the actuallist and so on. If
the actuallist is shorter than the formallist, M ensures that the
formallist items with no corresponding value are in effect NEWed. If
the formallist item has no corresponding item in the actuallist
(indicated by two adjacent commas in the actuallist), that item in the
formallist becomes undefined.
If the actuallist item is an expression and the corresponding
formallist variable is an array, parameter passing does not affect the
subscripted elements of the array. If an actualname corresponds to a
formallist variable, M reflects array operations on the formallist
variable, by reference, in the variable specified by the actualname.
M treats variables that are not part of the formallist as if parameter
passing did not exist (i.e., M makes them available to the invoked
routine).
M initiates execution at the first command following the formallabel.
A QUIT command terminates execution of the invoked routine. At the time
of the QUIT, M restores the formallist items to the values they had at
the invocation of the routine.
In the case where a variable name appears as an actualname in the
actuallist, and also as a variable in the formallist, the restored
value reflects any change made by reference.
A QUIT from a DO does not take an argument, while a QUIT from an
extrinsic must have an argument. This represents one of the two major
differences between the DO command with parameters and the extrinsics.
M returns the value of the QUIT command argument as the value of the
extrinsic function or special variable. The other difference is that M
stacks $TEST for extrinsics.
Example:
SET X=30,Z="Hello"
DO WRTSQR(X)
ZWRITE
QUIT
WRTSQR(Z)
SET Z=Z*Z
WRITE Z,!
QUIT
Produces:
900
X=30
Z="Hello"
3 Param_Pass_Mechanism
Parameter Passing Mechanisms
M passes the actuallist values to the invoked routine using two
parameter-passing mechanisms:
o Call-by-Value - where expressions appear
o Call-by-Reference - where actualnames appear
A call-by-value passes a copy of the value of the actuallist expression
to the invoked routine by assigning the copy to a formallist variable.
If the parameter is a variable, the invoked routine may change that
variable. However, because M constructs that variable to hold the copy,
it deletes the variable holding the copy when the QUIT restores the
prior formallist values. This also means that changes to the variable
by the invoked routine do not affect the value of the variable in the
invoking routine.
Example:
SET X=30
DO SQR(X)
ZWRITE
QUIT
SQR(Z) SET Z=Z*Z
QUIT
Produces:
X=30
A period followed by a name identifies an actualname and causes a
call-by-reference.
A call-by-reference passes a pointer to the variable of the invoked
routine so operations on the assigned formallist variable also act on
the actualname variable. Changes, including KILLs to the formallist
variable, immediately have the same affect on the corresponding
actualname variable. This means that M passes changes to formallist
variables in the invoked routine back to the invoking routine as
changes in actualname variables.
Example:
SET X=30
DO SQR(.X)
ZWRITE
QUIT
SQR(Z) SET Z=Z*Z
QUIT
Produces:
X=900
3 GTM_Param_Pass_Extn
GT.M Parameter Passing Extensions
The standard does not provide for indirection of a labelref because the
syntax has an ambiguity.
Example:
DO @X(1)
This example could be:
o An invocation of the label specified by X with a parameter of 1.
o An invocation of the label specified by X(1) with no parameter
list.
GT.M processes the latter interpretation as illustrated in the
following example.
Example:
The syntax:
SET A(1)="CUBE",X=5
DO @A(1)(.X)
WRITE X,!
QUIT
CUBE(C) ;cube a variable
SET C=C*C*C
QUIT
Produces the result:
125
GT.M follows analogous syntax for routine indirection:
DO ^@X(A) invokes the routine specified by X(A).
DO ^@(X)(A) invokes the routine specified by X and passes the parameter
A.
DO ^@X(A)(A) invokes the routine specified by X(A) and passes the
parameter A.
2 Ext_Calls
External Calls
GT.M allows references to a GT.M database from programs written in
other programming languages that run under UNIX.
In GT.M, calls to C language routines may be made with the following
syntax:
DO &[packagename.]name[^name][parameter-list]
or as an expression element,
$&[packagename.]name[^name][parameter-list]
Where packagename, like the name elements is a valid M name. Because of
the parsing conventions of M, the identifier between the ampersand (&)
and the optional parameter-list has precisely constrained punctuation -
a latersection describes how to transform this into a more richly
punctuated name should that be appropriate for the called function.
While the intent of the syntax is to permit the name^name to match an M
labelref, there is no semantic implication to any use of the up-arrow
(^).
2 Extrinsic_Func
Extrinsic Functions
An extrinsic function is an M subroutine that another M routine can
invoke to return a value.
The format for extrinsic functions is:
$$[label][^routinename]([expr|.lname[,...]])
o The optional label and optional routinename make up the formallabel
that specifies the name of the subroutine performing the extrinsic
function. The formallabel must contain at least one of its optional
components.
o The optional expressions and actualnames make up the actuallist
that specifies the list of actual parameters M passes to the
invoked routine.
M stacks $TEST for extrinsic functions. This is one of the two major
differences between the DO command with parameters and extrinsics. On
return from an extrinsic function, M restores the value of $TEST to
what it was before the extrinsic function, regardless of the actions
executed by the invoked routine.
M requires a routine that implements an extrinsic function to terminate
with an explicit QUIT command which has an argument. M returns the
value of the QUIT command argument as the value of the extrinsic
function. This is the other major difference between the DO command
with parameters and extrinsics. It is now possible to invoke a C
function in a package via the external call mechanism.
Example:
GTM>ZPRINT ^POWER
POWER(V,X,S,T) ;extrinsic to raise to a power
;ignores fractional powers
SET T=1,S=0
IF X<0 SET X=-X,S=1
FOR X=1:1:X S T=T*V
QUIT $S(S:1/T,1:T)
GTM> WRITE $$^POWER(3,4)
81
GTM>
The POWER routine uses a formallist that is longer than the
"expected" actuallist to protect local working variables. Such
practice may be encouraged or discouraged by your institution's
standards.
2 Extrinsic_Spc_Vars
Extrinsic Special Variables
An extrinsic special variable is a user-written M subroutine that
another M routine can invoke to return a value.
The format for extrinsic special variables is:
$$[label][^routinename]
o The optional label and optional routinename make up the
formallabel, which specifies the name of the subroutine performing
the extrinsic function. The formallabel must contain at least one
of its optional component.
An extrinsic special variable can be thought of as an extrinsic
function without input parameters. $$x is equivalent in operation to
$$x(). Extrinsic special variables are the only case where invocation
of a formallabel does not require an actuallist. M stacks $TEST for
extrinsic special variables.
M requires that a routine that implements an extrinsic special variable
terminate with an explicit QUIT command which has an argument. M
returns the value of the QUIT command argument as the value of the
extrinsic special variable.
Example:
GTM>ZPRINT ^DAYOWEEK
DAYOWEEK() ;extrinsic special variable to
;provide the day of the week
QUIT $ZD($H,"DAY")
GTM>WRITE $$DAYOWEEK^DAYOWEEK
MON
2 Trans_Processing
Transaction Processing
Transaction Processing (TP) provides a way for M programs to organize
database updates into logical groups that occur as a single event
(i.e., either all the database updates in a transaction occur, or none
of them occur). No other process may behave as if it observed any
intermediate state.
Transaction processing has been designed to improve output and
eliminate "live lock" conditions. The number of attempts to complete
the transaction is limited to four. The fourth attempt is made inside a
"critical section" with all other processes temporarily locked out of
the database. Between the second and third tries, GT.M waits for a
random interval between 0 and 500 milliseconds.
3 TP_Def
TP Definitions
In M, a transaction is a sequence of commands that begins with a TSTART
command, ends with a TCOMMIT command, and is not within the scope of
another transaction.
A successful transaction ends with a COMMIT that is triggered by the
TCOMMIT command at the end of the transaction. A COMMIT causes all the
database updates performed within the transaction to become available
to other processes.
An unsuccessful transaction ends with a ROLLBACK. ROLLBACK is invoked
explicitly by the TROLLBACK command, or implicitly at a process
termination that occurs during a transaction in progress. An error
within a transaction does not cause an implicit ROLLBACK. A ROLLBACK
removes any database updates performed within the transaction before
they are made available to other processes. ROLLBACK also releases all
resources LOCKed since the start of the transaction, and makes the
naked reference undefined.
A RESTART is a transfer of control to the TSTART at the beginning of
the transaction. RESTART implicitly includes a ROLLBACK and may
optionally restore local variables to the values they had when the
initial TSTART was originally executed. A RESTART always restores $TEST
and the naked reference to the values they had when the initial TSTART
was executed. RESTART does not manage device state information. A
RESTART is invoked by the TRESTART command or by M if it is determined
that the transaction is in conflict with other database updates.
RESTART can only successfully occur if the initial TSTART includes an
argument that enables RESTART.
3 TP_Characteristics
TP Characteristics
Most transaction processing systems try to have transactions meet the
"ACID" test-Atomic, Consistent, Isolated, and Durable. To conform with
the M approach of providing maximum flexibility and, when possible,
backwards compatibility with older versions of the standard, M
transaction processing requires the use of programming conventions that
meet the ACID test.
For example, some effects of the BREAK, CLOSE, JOB, OPEN, READ, USE
WRITE, and ZSYSTEM commands may be observed by parties to the system.
Because the effects of these commands might cause an observing process
or person to conclude that a transaction executing them was in progress
and perhapsfinished, they violate, in theory, the principle of
Isolation.
The LOCK command is another example. A program may attempt to use a
LOCK to determine if another process has a transaction in progress. The
answer would depend on the management of LOCKs within transactions,
which is implementation-specific. This would therefore clearly violate
the principle of Isolation. The LOCK command is discussed later in this
section.
The simplest way to construct a transaction that meets the ACID test is
not to use any commands within a transaction whose affects may be
immediately "visible" outside the transaction. Unfortunately, because M
applications are highly interactive, this is not entirely
straightforward. When a user interaction relies on database
information, one solution is for the program to save the initial values
of any global values that could affect the outcome, in local variables.
Then, once the interaction is over and the transaction has been
initiated, the program checks the saved values against the
corresponding global variables. If they are the same, it proceeds. If
they differ, some other update has changed the information, and the
program must issue a TROLLBACK, and initiate another interaction as a
replacement.
Even when the "visible" commands appear within a transaction, an M
application may provide wholesome operation by relying on additional
programming or operating conventions.
A program using LOCKs to achieve serializability relies on properly
designed and universally followed LOCKing conventions to achieve
Isolation with respect to database operations. LOCKs placed outside the
transaction (usually a LOCK immediately before the TSTART and an unlock
immediately after the TCOMMIT) achieve serializability by actually
serializing any approximately concurrent transaction. LOCKs placed
inside the transaction (frequently a LOCK immediately after the TSTART
and an unlock immediately before the TCOMMIT) signal M to ensure that
no operations using the same LOCK resource(s) overlap. Within a
transaction, an M implementation may defer both LOCKing and unlocking
to achieve its goal of serializability. A program using TSTARTs with
the SERIAL keyword replaces the convention with a guarantee from M that
all the database activity of the transaction meets the test of
Isolation with respect to database activity.
In GT.M the Durability aspect of the ACID properties relies on the
journaling feature. When journaling is on, every transaction is
recorded in the journal file as well as in the database. The journal
file constitutes a serial record of database actions and states. It is
always written before the database updates and is designed to permit
recovery of the database if the database should be damaged. By default
when a process commits a transaction, it does not return control to the
application code until the transaction has reached the journal file.
The exception to this is that when the TSTART specifies
TRANSACTIONID="BATCH" the process resumes application execution without
waiting for the file system to confirm the successful write of the
journal record. The idea of the TRANSACTIONID="BATCH" has nothing
inherently to do with "batch" processing - it is to permit maximum
throughput for transactions where the application has its own
check-pointing mechanism, or method of recreating the transaction in
case of a failure. The real durability of transactions is a function of
the durability of the journal files. Putting journal files on reliable
devices (RAID with UPS protection) and eliminating common points of
failure with the path to the database (separate drives, controllers
cabling) improve durability. The use of the replication feature can
also improve durability by moving the data to a separate site in real
time.
Attempting to QUIT (implicitly or explicitly) from code invoked by a
DO, XECUTE, or extrinsic after that code issued a TSTART not yet
matched by a TCOMMIT, produces an error. Although this is a consequence
of the RESTART capability, it is true even when that capability is
disabled. For example, this means that an XECUTE containing only a
TSTART fails, while an XECUTE that performs a complete transaction
succeeds.
3 TP_Performance
TP Performance
To achieve the best GT.M performance, transactions should:
o be as short as possible
o consist, as much as possible, only of global updates
o be SERIAL with no associated LOCKs
o have RESTART enabled with a minimum of local variables protected by
a restart portion of the TSTART argument.
Large concurrent transactions using TCOMMIT may result in repeated and
inefficient attempts by competing processes to capture needed scarce
resources, resulting in poor performance.
Example:
TSTART ():SERIAL
SET (ACCT,^M(0))=^M(0)+1
SET ^M(ACCT)=PREC,^PN(NAM)=ACCT
TCOMMIT
This transaction encapsulates these two SETs. The first increments the
tally of patients registered, storing the number in local variable ACCT
for faster access in the current program, and in global variable ^M(0).
The second SET stores a patient record by account number and the third
cross-references the account number with the patient name. Placing the
SETs within a single transaction ensures that the database always
receive either all of the SETs or none of them, thus protecting
database integrity against process or system failure. Similarly,
another concurrent process, whether using transactions or not, never
finds one of the SETs in place without also finding the other one.
Example:
TSTART ():SERIAL
IF $TRESTART>3 DO QUIT
.TROLLBACK
.WRITE !,"Too many RESTARTs"
.QUIT
SET (NEXT,^ID(0))=^ID(0)+1
SET ^ID(NEXT)=RECORD,^XID(ZIP,NEXT)=""
TCOMMIT
This transaction will automatically restart if it cannot serialize the
SETs to the database, and will terminate with a TROLLBACK if more than
3 RESTARTs occur.
GT.M provides a way to monitor transaction restarts by reporting them
to the operator logging facility. If the environment variable
TPRESTART_SYSLOG_DELTA is defined, GT.M reports every Nth restart where
N is the numeric evaluation of the value of TPRESTART_SYSLOG_DELTA. If
the environment variable TPRESTART_SYSLOG_LIMIT is defined, the restart
reporting begins after the number of restarts specified by the value of
TPRESTART_SYSLOG_LIMIT. For example, defining both the environment
variable to the value 1, causes all TP restarts to be logged. When
TPRESTART_SYSLOG_DELTA is defined, leaving TPRESTART_SYSLOG_LIMIT
undefined is equivalent to giving it the value 1.
For more information on enhancements related to TP performance
refer to the "NOISOLATION" section under VIEW command topic in the
"Commands" chapter in GT.M Programmer's Guide.
3 TP_Example
TP Example
Here is a transaction processing example that lets you exercise the
concept. If you use this example, be mindful that the functions
"holdit" and "trestart" are included as tools to allow you access to
information within a transaction which would normally be hidden from
users. These types of functions would not normally appear in production
code. Comments have been inserted into the code to explain the function
of various segments.
trans
;This sets up the program constants
;for doit and trestart
n
s $p(peekon,"V",51)=""
s $p(peekon,"V",25)="Peeking inside Job "_$j
s $p(peekoff,"^",51)=""
s $p(peekoff,"^",25)="Leaving peeking Job "_$j
;This establishes the main loop
s CNFLTMSG="Conflict, please reenter"
f r !,"Name: ",nam q:'$l(nam) d
.i nam="?" d q
..w !,"Current data in ^trans:",! d:$d(^trans) q
...zwrite ^trans
.f s ok=1 d q:ok w !,$C(7),CNFLTMSG,$C(7),!
..s old=$g(^trans(nam),"?")
..i old="?" w !,"Not on file" d q
...;This is the code to add a new name
...f d q:data'="?"
....r !,"Enter any info using '#' delimiter: ",!,data
...i data="" w !,"No entry made for ",nam q
...TSTART ():SERIAL i $$trestart ;$$trestart for demo
...i $d(^trans(nam)) s ok=^trans(nam)=data TRO q
...s ^trans(nam)=data
...TCOMMIT:$$doit ;$$doit for demo
..;This is the beginning of the change and delete loop
..f d q:fld=+fld!'$l(fld) w " must be numeric"
...w !,"Current data: ",!,old
...r !,"Piece no. (negative to delete record) : ",fld
..i 'fld w !,"no change made" q
..;This is the code to delete a new name
..i fld<0 d q ; delete record
...f d q:"YyNn"[x
....w !,"Ok to delete ",nam," Y(es) or N(o) <N>? "
....r x s x=$e(x)
...i "Yy"'[x!'$l(x) w !,"No change made" q
...TSTART ():SERIAL i $$trestart ;$$trestart for demo
...i $g(^trans(nam),"?")'=old TROLLBACK s ok=0 q
...kill ^trans(nam)
...TCOMMIT:$$doit; $$doit for demo
..;This is the code to change a field
..f r !,"Data: ",data q:data'="?"&(data'["#") d
...w " must not be a single '?' or contain any '#'"
..TSTART ():SERIAL i $$trestart ;$$trestart for demo
..i '$d(^trans(nam)) s ok=0 TROLLBACK q
..i $p(^trans(nam),"#",fld)=$p(old,"#",fld) d q
...s ok=$p(^trans(nam),"#",fld)=data TROLLBACK
..s $p(^trans(nam),"#",fld)=data
..TCOMMIT:$$doit; $$doit for demo
q
doit()
;This inserts delay and an optional
;rollback only to show how it works
w !!,peekon d disp
f d q:"CR"[act
.r !,"C(ommit), R(ollback), or W(ait) <C>? ",act
.s act=$tr($e(act),"cr","CR")
.i act="?" d disp
i act="R" TROLLBACK w !,"User requested DISCARD"
w !,peekoff,!
q $TLEVEL
trestart()
;This is only to show what is happening
i $TRESTART d
.w !!,peekon,!,">>>RESTART<<<",! d disp w !,peekoff,!
q 1
disp
w !,"Name: ",nam
w !,"Original data: ",!,old,!,"Current data: "
w !,$g(^trans(nam),"KILLED!")
q
Generally, this type of program would be receiving data from multiple
sessions into the same global.
1 BREAK
Break
The BREAK command pauses execution of the code and initiates Direct
Mode.
The format of the BREAK command is:
B[REAK][:tvexpr] [expr[:tvexpr][,...]]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o The optional expression contains a fragment of GT.M code to XECUTE
before the process enters Direct Mode.
o The BREAK command without an argument causes a pause in execution
of the routine code and immediately initiates Direct Mode. In this
case, at least two (2) spaces must follow the BREAK to separate it
from the next command on the line.
o The optional truth-valued expression immediately following the
expression is the argument postconditional that controls whether
GT.M XECUTEs the argument. If present and true, the process
executes the code before entering Direct Mode. If present and
false, the process does not execute the code before entering Direct
Mode.
o An indirection operator and an expression atom evaluating to a list
of one or more BREAK arguments form a legal argument for a BREAK.
Issuing a BREAK command inside a transaction destroys the Isolation of
that transaction. Beacuse of the way that GT.M implements transaction
processing, a BREAK within a transaction may suffer an indefinite
number of restarts ("live lock").
Generally, programs in production must not include BREAK commands.
Therefore, GT.M provides the ZBREAK and ZSTEP commands, which insert
temporary breakpoints into the process rather than the source code.
BREAKs inserted with ZBREAK only exist until the image terminates or
until explicitly removed by another ZBREAK command. ZSTEP also inserts
temporary BREAKs in the image that only exist for the execution of the
ZSTEP command. In the GT.M debugging environment, ZBREAKs and ZSTEPs
that insert BREAKs provide a more flexible and less error-prone means
of setting breakpoints than coding BREAKs directly into a routine. For
more information on ZBREAK and ZSTEP, refer to the sections that
describe those commands.
To resume execution of the interrupted program, use the ZCONTINUE
command.
GT.M displays messages identifying the source of a BREAK as:
o The body of a program
o A
o ZBREAK action
o A device EXCEPTION
o A ZSTEP action
The VIEW "BREAKMSG" mask selectively enables or disables these
messages. See the section on "VIEW" for an explanation of the mask. By
default, a process executing a GT.M image displays all BREAK messages.
When a process encounters a BREAK, it displays a prompt indicating
readiness to process commands in Direct Mode. By default, Direct Mode
displays the GTM> prompt. SETting the $ZPROMPT intrinsic special
variable alters the prompt.
2 Ex_of_Break
Examples of BREAK
Example:
LOOP0 F S act=$O(^act(act)) Q:act="" B:debug D LOOP1
This FOR loop contains a BREAK with a command postconditional.
Example:
B:$D(x) "W !,""OK""":x,"W !,""Wrong again""":'x
This uses a BREAK with both command and argument postconditionals. The
actions display debugging messages.
1 CLOSE
Close
The CLOSE command breaks the connection between a process and a device.
The format of the CLOSE command is:
C[LOSE][:tvexpr] expr[:(keyword[=expr][:...])][,...]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o The required expression specifies the device to CLOSE.
o The optional keywords specify device parameters that control device
behavior; some device parameters take arguments delimited by an
equal sign (=). If there is only one keyword, the surrounding
parentheses are optional.
o An indirection operator and an expression atom evaluating to a list
of one or more CLOSE arguments form a legal argument for a CLOSE.
1 DO
Do
The DO command makes an entry in the GT.M invocation stack and
transfers execution to the location specified by the entryref.
The format of the DO command is:
D[O][:tvexpr] [entryref[(expr|.lvn[,...])][:tvexpr][,...]]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o The optional entryref specifies a location (with some combination
of label, offset, and routinename) at which execution continues
immediately following the DO.
o A DO command without an argument (that is, a DO followed by two (2)
spaces) transfers execution to the next line in the routine if that
line contains a number of periods (.) after the optional label and
before the required linestart. These periods indicate the current
level of "immediate" nesting caused by argumentless DOs. If the
line following the DO contains too many periods, GT.M reports an
error; if the line following the DO contains too few periods, GT.M
ignores the DO command.
o A DO command without an argument stacks the current value of $TEST,
in contrast to a DO with an argument, which does not protect the
current value of $TEST.
o The optional parameter list enclosed in parentheses ( ) contains
parameters to pass to the routine entry point.
o If the DO specifies a parameter list, the entryref location must
start with a label and an argument list (that is, GT.M prohibits
entryrefs with offsets during parameter passing).
o If an element in the parameter list starts with a period, it
specifies an unsubscripted local variable name and the DO passes
that variable by reference. Otherwise, the element specifies an
expression that the DO evaluates and passes as a value.
o The optional truth-valued expression following the parameter list,
or the entryref if the argument contains no parameter list,
specifies the argument postconditional and controls whether GT.M
performs a DO with that argument.
o An indirection operator and an expression atom evaluating to a list
of one or more DO arguments form a legal argument for a DO.
An explicit or implicit QUIT within the scope of the DO, but not within
the scope of any other DO, FOR, XECUTE, or extrinsic, returns execution
to the instruction following the calling point. This point may be the
next DO argument or another command. At the end of a routine, or the
end of a nesting level created by an argumentless DO, GT.M performs an
implicit QUIT. Any line that reduces the current level of nesting by
changing the number of leading periods (.) causes an implicit QUIT,
even if that line only contains a comment.
Terminating the image and execution of ZGOTO commands are the only ways
to avoid eventually returning execution to the calling point. A DO
command may optionally pass parameters to the invoked subroutine.
2 Ex_of_Do
Examples of DO
Example:
GTM>DO ^%RD
This example invokes the routine directory utility program (%RD) from
Direct Mode. The caret symbol (^) specifies that the DO command invokes
%RD as an external routine.
Example:
GTM>DO A(3)
This example invokes the subroutine at label A and passes the value 3
as a parameter. Because the DO argument does not have a caret symbol
(^), it identifies A as a label in the current routine.
Example:
Label A;
SET di="" U outfile
FOR SET di=$O(^div(di)) Q:di="" D PREP D D POST
.SET de="",(nr,gr)=0
.WRITE "Division ",di,! F S de=$O(^de(di,de)) Q:de="" D
..WRITE "Department ",de," Gross Rev: ",^grev(di,de),!
..WRITE "Department ",de," Net Rev: ",^nrev(di,de),!
..SET gr=gr+^grev(di,de),nr=nr+^nrev(di,de)
.W "Division Gross Rev: ",gr,!,"Division Net Rev: ",nr,!
DO PRINT^OUTPUT(outfile)
QUIT
This routine first uses a DO with a label argument (PREP) to do some
pre-processing. Then, it uses an argumentless DO to loop through each
division of a company to format a report. Within the first argumentless
DO, a second argumentless DO (line 4) loops through and formats each
department within a division. After the processing of all departments,
control returns to the first argumentless DO, which prints a summary of
the division. Following processing of all divisions, a DO with a label
argument (POST) does some post-processing. Finally, at the next-to-last
line, the routine uses a DO that invokes a subroutine at a label
(PRINT) in an external routine (^OUTPUT), passing the name of the
output file (outfile) as a parameter.
1 ELSE
Else
GT.M executes the remainder of the line after the ELSE if $TEST is
FALSE (0). GT.M does not execute the rest of the line if $TEST is TRUE
(1).
The format of the ELSE command is:
E[LSE]
o Because ELSE is a conditional command, it does not support a
command postconditional.
o The scope of the ELSE is the remainder of the line.
o Because the ELSE has no argument, at least two (2) spaces must
follow the command to separate it from the next command on the
line.
Because the scopes of both the IF and the ELSE commands extend to the
rest of the GT.M line, placing an ELSE on the same line as the
corresponding IF cannot achieve the desired result. If an ELSE were
placed on the same line as its corresponding IF, then the expression
tested by the IF would be either TRUE or FALSE. If the condition is
TRUE, the code following the ELSE would not be executed. If the
condition is FALSE, the ELSE and everything following it would not be
executed.
ELSE is analogous to IF '$TEST, except the latter statement switches
$TEST to its complement and ELSE never alters $TEST.
The scope of an ELSE can be extended with DO or XECUTE commands.
2 Ex_of_Else
Examples of Else
Example:
IF x=+x SET x=x+y
ELSE WRITE !,x
The IF command evaluates the conditional expression x=+x and sets
$TEST. If $TEST=1 (TRUE), GT.M executes the commands following the IF.
The ELSE on the following line specifies an alternative action to take
if the expression is false.
Example:
IF x=+x DO ^GOFISH
ELSE SET x=x_"^"_y
The DO with an argument after the IF raises the possibility that the
routine ^GOFISH changes the value of $TEST, thus making it possible to
execute both the commands following the IF and the commands following
the ELSE.
Example:
OPEN dev::0 ELSE WRITE !,"Device unavailable" QUIT
This ELSE depends on the result of the timeout on the OPEN command. If
the OPEN succeeds, it sets $TEST to one (1) and GT.M skips the rest of
the line after the ELSE. If the OPEN fails, it sets $TEST to zero (0),
and GT.M executes the remainder of the line after the ELSE.
1 FOR
For
The FOR command provides a looping mechanism in GT.M. A FOR command
does not generate an additional level on the GT.M invocation stack.
The format of the FOR command is:
F[OR][lvn=expr[:numexpr1[:numexpr2]][,...]]]
o Because FOR is a conditional command, it does not support a command
postconditional.
o The scope of the FOR is the remainder of the line.
o When the FOR has no argument, at least two (2) spaces must follow
the command to separate it from the next command on the line. This
specifies a loop that must be terminated by a QUIT, HALT, GOTO, or
ZGOTO.
o The optional local variable name specifies a loop control variable
delimited by an equal sign (=). A FOR command has only one control
variable, even when it has multiple arguments.
o When initiating the FOR, GT.M assigns the loop control variable the
value of the expression. When only an initial value appears, GT.M
executes the remainder of the line once for that argument without
forcing the control variable to be numeric.
o If the argument includes an increment and, optionally, a
terminator, GT.M treats the initial expression as a number.
o The optional numeric expression after the first colon (:) delimiter
specifies the increment for each iteration. The FOR command does
not increment the control variable on the first iteration.
o The optional numeric expression after the second colon (:)
delimiter specifies the limiting value for the control variable.
This expression is evaluated only when the control variable is
initialized to the corresponding initial value, then used for all
subsequent iterations.
o GT.M does not execute the commands on the same line following the
FOR if:
The increment is non-negative and the initial value of the control
variable is greater than the limiting value.
The increment is negative and the initial value of the control variable
is less than the limiting value.
o After the first iteration, GT.M does not alter the control variable
and ceases execution under the control of the FOR if:
The increment is non-negative, and altering the control variable by the
increment would cause the control variable to be greater than the
limiting value.
The increment is negative, and altering the control variable by the
increment would cause the control variable to be less than the limiting
value.
o When the FOR has multiple arguments, each one affects the loop
control variable in sequence. For an argument to gain control, no
prior argument to the FOR can have an increment without a limit.
Increments and limits may be positive, negative, an integer, or a
fraction. GT.M never increments a control variable "beyond" a limit.
Other commands may alter a control variable within the extended scope
of a FOR that it controls. When the argument includes a limit, such
modification can cause the FOR argument to yield control at the start
of the next iteration.
The scope of a FOR can be extended with DO or XECUTE commands.
GT.M terminates the execution of a FOR when it executes an explicit
QUIT or a GOTO (or ZGOTO in GT.M) that appears on the line after the
FOR. FOR commands with arguments that have increments without limits
and argumentless FORs can be infinite loops. Such FORs must terminate
with a QUIT or a GOTO within the immediate scope of the FOR. Also, such
FORs can, but seldom, terminate by a HALT within the scope of the FOR
as extended by DOs, XECUTEs, and extrinsics. FORs terminated by such
commands act as "while" or "until" control mechanisms.
2 Ex_of_For
Examples of FOR
Example:
GTM>KILL i FOR i=1:1:5 WRITE !,i
1
2
3
4
5
GTM>WRITE i
5
GTM>
This FOR loop has a control variable, i, which has the value one (1) on
the first iteration, then the value two (2), and so on, until in the
last iteration i has the value five (5). The FOR terminates because
incrementing i would cause it to exceed the limit. Notice that i is not
incremented beyond the limit.
Example:
GTM>FOR x="hello",2,"goodbye" WRITE !,x
hello
2
goodbye
GTM>
This FOR loop uses the control variable x and a series of arguments
that have no increments or limits. Notice that the control variable may
have a string value.
Example:
GTM>FOR x="hello":1:-1 WRITE !,x
GTM>ZWRITE x
x=0
GTM>
Because the argument has an increment, the FOR initializes the control
variable x to the numeric evaluation of "hello" (0). Then, GT.M never
executes the remainder of the line because the increment is positive,
and the value of the control variable (0) is greater than the limiting
value (-1).
Example:
GTM>FOR y=-1:-3:-6,y:4:y+10,"end" WRITE !,y
-1
-4
-4
0
4
end
GTM>
This FOR uses two limited loop arguments and one value argument. The
first argument initializes y to negative one (-1), then increments y to
negative four (-4). Because another increment would cause y to be less
than the limit (-6), the first argument terminates with y equal to
negative four (-4). The second argument initializes the loop control
variable to its current value and establishes a limit of six (6=-4+10).
After two iterations, incrementing y again would cause it to be greater
than the limit (6), so the second argument terminates with y equal to
four (4). Because the final argument has no increment, the FOR sets y
to the value of the argument, and GT.M executes the commands following
the FOR one more time.
Example:
GTM>S x="" F S x=$O(ar(x)) Q:x="" W !,x
This example shows an argumentless FOR used to examine all first level
subscripts of the local array ar. When $ORDER indicates that this level
contains no more subscripts, the QUIT with the postconditional
terminates the loop.
1 GOTO
Goto
The GOTO command transfers execution to a location specified by its
argument.
The format of the GOTO command is:
G[OTO][:tvexpr] entryref
[:tvexpr][,...]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o The required entryref specifies the target location for the control
transfer.
o The optional truth-valued expression immediately following the
entryref specifies the argument postconditional, and controls
whether GT.M performs a GOTO with that argument.
o An indirection operator and an expression atom evaluating to a list
of one or more GOTO arguments form a legal argument to a GOTO.
A GOTO command within a line following a FOR command terminates that
FOR command.
2 Ex_of_Goto
Examples of GOTO
Example:
GTM>GOTO TIME+4
This GOTO command transfers control from Direct Mode to the line that
is four (4) lines after the line labeled TIME (in the currently active
routine). Using an offset is typically a debugging technique and rarely
used in production code.
Example:
GOTO A:x<0,^A:x=0,A^B
This GOTO command transfers control to label A in the current routine,
if x is less than zero (0), to routine ^A if x is equal to zero (0), or
to label A in routine ^B. Once any of the transfers occurs, the rest of
the arguments have no effect.
1 HALT
Halt
The HALT command stops GT.M program execution and causes GT.M to return
control to the operating system environment that invoked the GT.M
image.
The format of the HALT command is:
H[ALT][:tvexpr]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether GT.M
executes the command.
o Because the HALT command has no argument, at least two (2) spaces
must follow the command to separate it from the next command on the
line. Note that additional commands do not serve any purpose unless
the HALT has a postconditional.
A HALT releases all shared resources held by the process, such as
devices OPENed in GT.M, databases, and GT.M LOCKs. If the value of
$TLEVEL is greater than zero (0), a ROLLBACK is performed.
Because HALT and HANG share the same abbreviation (H), GT.M
differentiates them based on whether an argument follows the command.
Example:
$ gtm
GTM>HALT
$
Because we invoke this GT.M image interactively, the HALT in Direct
Mode leaves the process at the shell prompt.
1 HANG
Hang
The HANG command suspends GT.M program execution for a period of time
specified by the command argument.
The format of the HANG command is:
H[ANG][:tvexpr] numexpr[,...]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o The numeric expression specifies the time in seconds to elapse
before resuming execution; actual elapsed time may vary slightly
from the specified time. If the numeric expression is negative,
HANG has no effect. Portability requirements for GT.M only
guarantee accuracy to the nearest second.However, more accuracy can
be found on different UNIX systems.
o An indirection operator and an expression atom evaluating to a list
of one or more HANG arguments form a legal argument to a HANG.
A process that repeatedly tests for some event, such as a device
becoming available or another process modifying a global variable, may
use a HANG to limit its consumption of computing resources.
Because HALT and HANG share the same abbreviation (H), GT.M
differentiates them based on whether an argument follows the command.
2 Ex_of_Hang
Examples of HANG
Example:
FOR QUIT:$D(^CTRL(1)) HANG 30
This FOR loop repeatedly tests for the existence of ^CTRL(1), and
terminates when that global variable exists. Otherwise the routine
HANGs for 30 seconds and tests again.
Example:
SET t=1 F Q:$D(^CTRL(1)) H t I t<30 S t=t+1
This is similar to the previous example, except that it uses an
adaptive time that lengthens from 1 second to a limit of 30 seconds if
the routine stays in the loop.
1 IF
IF
The IF command provides conditional execution of the remaining commands
on the line. When IF has an argument, it updates $TEST with the truth
value of its evaluated argument. GT.M executes the remainder of a line
after an IF statement when $TEST is 1 (TRUE). When $TEST is 0 (FALSE),
GT.M does not execute the rest of the line.
The format of the IF command is:
I[F] [tvexpr[,...]]
o Because IF is a conditional command, it does not support a command
postconditional.
o The scope of the IF is the remainder of the line.
o The action of IF is controlled by the value of the expression and
by $TEST, if there is no expression.
o IF with no argument acts on the existing value of $TEST (which it
does not change); in this case, at least two (2) spaces must follow
the IF to separate it from the next command on the line.
o An indirection operator, and an expression atom evaluating to a
list of one or more IF arguments form a legal argument to IF.
Example:
IF A,B ...
is equivalent to
IF A IF B
An IF with more than one argument behaves as if those arguments were
logically "ANDed." However, execution of the line ceases with the
evaluation of the first false argument. For IF argument expressions
containing the "AND" operator (&), execution still ceases with the
evaluation of the first false argument. Any global references within
the expression act in sequence to maintain the naked reference.
Postconditionals perform a function similar to IF; however, their scope
is limited to a single command or argument, and they do not modify
$TEST. For more information on postconditionals.
2 Ex_of_IF
Examples of IF
Example:
IF x=+x!(x="") DO BAL
In this example, the DO executes if x contains a number or a null
string.
Example:
WRITE !,?50,BAL IF 'BAL WRITE "****"
IF S EMPTY(acct)=""
The IF in the first line changes the value of $TEST, determining the
execution of the code following the argumentless IF in the second line.
Such argumentless IFs may serve as a form of line continuation.
Example:
GTM>SET X=1,Y=1,Z=2 KILL UNDEF
GTM>IF X=1,Y=1,Z=3,UNDEF=0 W "HI"
GTM>
The IF command causes GT.M to cease executing the line after it
determines Z is not equal to three (3). Therefore, GT.M never evaluates
the reference to the undefined variable and never generates an error.
Example:
GTM>SET X=1 KILL UNDEF
GTM>IF X=1!(UNDEF=3) WRITE "HI"
HI
GTM>
Because GT.M recognizes that the X=1 fulfills the IF, it skips
evaluation of the UNDEF variable and executes this IF command without
generating an error. Because GT.M does not require such optimizations
and in fact discourages them by requiring that all global references
maintain the naked indicator, other implementations may generate an
error.
1 JOB
Job
The JOB command initiates another GT.M process that executes the named
routine.
$ZJOB is set to the pid of the process created by the JOB command. For
details refer to the "$ZJOB" section in the "Intrinsic Special
Variable" chapter of GT.M Programmer's Guide.
The format of the JOB command is:
J[OB][:tvexpr] entryref
[(expr[,...])]
[:[(keyword[=value][:...])][:numexpr]][,...]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o The required entryref specifies a location at which the new process
starts.
o The optional parameter list enclosed in parentheses () contains
parameters to pass to the routine entry point.
o If the JOB specifies a parameter list, the entryref location must
start with a label and a formallist. GT.M prohibits entryrefs with
offsets during parameter passing.
o The optional elements in the parameter list specify expressions
that the JOB evaluates and passes as values.
o The keywords specify optional processparameters that control
aspects of the environment for the new process.
o If the JOB command has only one processparameter, the surrounding
parentheses are optional.
o Some keywords take numeric or string literals delimited by an equal
sign (=) as arguments. Because the values are constants, strings
must be enclosed in quotation marks (" "), and variable arguments
require that the entire argument be constructed and referenced
using indirection.
o The optional numeric expression specifies a time in seconds after
which the command should timeout if unsuccessful; 0 results in a
single attempt.
o When a JOB command contains no processparameters, double colons
(::) separate the time-out numeric expression from the entryref.
o An indirection operator and an expression atom, evaluating to a
list of one or more JOB command arguments, form a legal argument
for a JOB command.
o The maximum command-line length from a JOB command is 8192 bytes.
The operating system deletes the resultant process when execution of
its GT.M process is complete. The resultant process executes
asynchrounously with the current process. Once GT.M starts the
resultant process, the current process continues.
If a JOB command specifies a timeout, and GT.M creates the resultant
process before the timeout elapses, JOB sets $TEST to true (1). If GT.M
cannot create the process within the specified timeout, JOB sets $TEST
to false (0). If a JOB command does not specify a timeout, the
execution of the command does not affect $TEST.
If GT.M cannot create the process because of something that is unlikely
to change during the timeout interval, such as invalid DEFAULT
directory specification, or the parameter list is too long, the JOB
command generates a run-time error. If the command does not specify a
timeout and the environment does not provide adequate resources, the
process waits until resources become available to create the resultant
process.
2 The_JOB_Env
The JOB Environment
When the JOB is forked, UNIX creates the environment for the new
process by copying the environment of the process issuing the JOB
command and making a few minor modifications.By default, the standard
input is assigned to the null device, the standard output is assigned
to routinename.mjo, and the standard error is assigned to
routinename.mje.
3 JOB_Impl_for_Dir
JOB Implications for Directories
By default, GT.M uses the current working directory of the parent
process for the working directory of the initiated process.
If the files specified by processparameters do not exist, and GT.M does
not have permission to create them, the JOBed process terminates. When
the corresponding files are in the current working directory, the
OUTPUT, INPUT, and ERROR processparameters do not require a full
pathname.
2 JOB_ProcParam
JOB Processparameters
The following sections describe the processparameters available for the
JOB command in GT.M.
3 DEFAULT
DEF[AULT]=strlit
The string literal specifies the default directory.
The maximum directory length is 255 characters.
If the JOB command does not specify a DEFAULT directory, GT.M uses the
current default directory of the parent process.
3 ERROR
ERR[OR]=strlit
The string literal specifies a value for stderr.
The maximum string length is 255 characters.
By default, JOB constructs the error file from the routinename using a
file extension of .mje: the default directory of the process created by
the JOB command.
3 GBLDIR
GBL[DIR]=strlit
The string literal specifies a value for the environment variable
gtmgbldir.
The maximum length of the value permitted is 255 characters.
By default, the job uses the same specification for gtmgbldir as that
defined for the process using the JOB command.
3 INPUT
IN[PUT]=strlit
The string literal specifies a value for stdin.
The maximum string length is 255 characters.
GT.M does not supply a default file extension.
By default, the job takes its input from the null device.
3 OUTPUT
OUT[PUT]=strlit
The string literal specifies a value for stdout.
The maximum string length is 255 characters.
By default, JOB constructs the output file pathname from the
routinename using a file extension of .mjo and the current default
directory of the process created by the JOB command.
3 STARTUP
STA[RTUP]=strlit
The string literal specifies a command line that GT.M invokes a shell
to execute before executing the GT.M routine. The command line may
invoke a shell script or other images.
The executed command does not affect the environment of the JOBed
process.
2 Ex_of_JOB
Examples of JOB
Example:
GTM>JOB ^TEST
This creates a job that starts doing the routine ^TEST in the current
working directory.
Example:
JOB PRINTLABELS(TYPE,PRNTR,WAITIM)
This passes three values (TYPE, PRNTR, and WAITIM) to the new job,
which starts at the label PRINTLABELS of the current routine.
1 KILL
Kill
The KILL command deletes local or global variables and their descendant
nodes.
The format of the KILL command is:
K[ILL][:tvexpr] [glvn|[(]lvn[,...][)][,...]]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o The optional global or local variable name specifies the variable
to delete; KILL deletes not only the variable specified in the
argument, but also all variables descended from that variable, that
is, those starting with the identical key-prefix.
o KILLing a variable that does not currently exist has no effect.
o The KILL command without an argument deletes all currently existing
local variables; in this case, at least two (2) spaces must follow
the KILL to separate it from the next command on the line.
o When a KILL argument is enclosed in parentheses, that "exclusive"
KILL deletes all local variables except those listed in the
argument.
o An indirection operator and an expression atom evaluating to a list
of one or more KILL arguments
o form a legal argument for a KILL.
KILL does not affect copies of local variables that have been "stacked"
by NEW or parameter passing.
Because a KILL can have a major impact, use KILL with caution.
2 Ex_of_Kill
Examples of KILL
Example:
GTM>KILL SET a=0,a(1)=1,a(1,1)="under" KILL a(1) ZWR
a=0
GTM>
This uses an argumentless KILL to get a "fresh start" by deleting all
existing local variables. After SETting a, a(1), and a(1,1), the KILL
deletes a(1) and its descendants. The ZWRITE shows only a remaining.
Example:
GTM>KILL (a,b),^AB(a,b)
The first argument (an exclusive KILL) specifies to KILL all local
variables except a and b. The second argument deletes ^AB(a,b) and any
descendants of that global variable node.
1 LOCK
Lock
The LOCK command is used to reserve and release resource names,
providing a semaphore capability for GT.M processes. This capability
can be used for interprocess synchronization and signaling.
Assigning a LOCK does not specify any explicit control over variables
and does not directly effect either read or write access to global (or
local) data. However, an application that adheres to clearly defined
conventions of LOCKing before any access can indirectly achieve such an
effect.
The format of the LOCK command is:
L[OCK][:tvexpr] [[-|+]nref|(nref[,...])[:numexpr]
[,...]]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o The nref argument specifies a resource name in the format of the
GT.M name, with or without subscripts and with or without a
preceding caret (^). An nref can optionally have an environment
specification, including one without a preceding caret (^).
o Outside of transactions, only one process in an environment can own
a particular LOCK at any given time.
o Because the data storage in GT.M uses hierarchical sparse arrays,
and LOCK frequently serves to protect that data from inappropriate
"simultaneous" access by multiple processes, LOCK treats resource
names in a hierarchical fashion; a LOCK protects not only the named
resource, but also its ancestors and descendants.
o When one or more nrefs are enclosed in parentheses (), LOCK
reserves all the enclosed names "simultaneously," that is, it
reserves none of them until all become available.
o A LOCK with no argument or an argument with no leading sign
releases all names currently reserved with previous LOCK commands
by the process; when a LOCK has no argument, at least two (2)
spaces must follow the LOCK to separate it from the next command on
the line.
o A LOCK argument with a leading plus sign (+) acquires the named
resources without releasing currently held resources; if the named
resource is already LOCKed, such a LOCK "counts up" the process
interest in the resource.
o A LOCK argument with a leading minus sign (-) "counts down" the
process interest in a named resource; if the count on a particular
lock reaches zero (0), GT.M releases the lock without releasing any
other currently held locks; a LOCK that releases a named resource
not currently owned by the process has no effect.
o The optional numeric expression specifies a time in seconds after
which the command should timeout if unsuccessful; 0 provides a
single attempt.
o An indirection operator and an expression atom evaluating to a list
of one or more LOCK arguments form a legal argument for a LOCK.
GT.M records LOCK and ZALLOCATE information in the "lock database."
GT.M distributes the lock database in space associated with the
database identified by the current Global Directory. However, the lock
database does not overlap or coincide with the body of the database
files holding the global data. Only the LOCK, ZALLOCATE and ZDEALLOCATE
commands, and the LKE utility program access the lock database.
GT.M maps reservations of names starting with ^ to the database file
used to map global variables of the same name. If the Global Directory
maps the name A to file A.DAT, GT.M maps all reservations on ^A to file
space associated with A.DAT.
GT.M maps reservations on names not starting with ^ to the region of
the database specified with the GDE command LOCK -REGION=. By default,
when GDE creates a Global Directory any reservations of local names are
mapped to the region DEFAULT.
These two factors effect the following result in the programming
environment:
o ^ reservations automatically intersect for all users of the same
data in any database file independent of the Global Directory
mapping that file.
o reservations without a leading ^ intersect in an arbitrary pattern
dependent on the Global Directory and therefore controlled by a
design decision made independently of application code design.
Since GT.M uses resource names as semaphores for signaling among
multiple processes in a database environment, they interlock in a tree
structured fashion. When LOCK or ZALLOCATE reserves a subscripted
resource name such as ^D(1), other users of the database mapped by the
LOCKing (or ZALLOCATEing) process cannot reserve ancestors of that
name, such as ^D, or descendants, such as ^D(1,2), until LOCK or
ZDEALLOCATE releases that name.
Execution of the LOCK command does not affect the value or the state of
a variable. LOCK tests each argument to determine whether the process
can claim the name space. If another GT.M process has a LOCK on that
name space, GT.M suspends the current process until the other process
releases the name space. To prevent the potential "infinite" suspension
of a routine execution, specify a timeout for the LOCK command.
LOCK with a leading plus (+) or minus (-) sign (incremental LOCKing)
allows the acquisition of locks without releasing currently held locks.
This can lead to deadlocks.
To avoid deadlocks, use LOCK without a leading + or - sign on its
arguments because such a command releases all previously LOCKed
resources; or use a timeout with the LOCK command.
If a LOCK command specifies a timeout, and GT.M acquires ownership of
the named resource before the timeout elapses, LOCK
sets $TEST to TRUE (1). If GT.M cannot acquire ownership of the named
resource within the specified timeout, LOCK sets $TEST to FALSE (0). If
a LOCK command does not specify a timeout, the execution of the command
does not affect $TEST. If a LOCK with an argument having a leading
minus sign (-) specifies a timeout, the command always sets $TEST to
TRUE (1).
If a process issues a LOCK command for a named resource already
ZALLOCATEd by that process, the resource is both ZALLOCATEd and LOCKed.
LOCK does not release ZALLOCATEd resources. To release such a named
resource, the process must both ZDEALLOCATE and unLOCK the resource.
For more information on ZALLOCATE, refer to the "ZALLOCATE".
2 Locks_within_Trans
Using Locks within Transactions
Within transactions LOCKs are used by GT.M to ensure the ability to
serialize. There is no guarantee, however, that attempts by other
processes to examine LOCKs held with a transaction will produce the
same results as when LOCKs are outside of a transaction. In other
words, LOCKs within transactions should never be used as simple
semaphores.
The LOCK command locks a specified resource name that controls a tree
structured name space. Outside of transactions when one process in an
environment acquires a LOCK or a ZALLOCATE on a named resource, no
other GT.M process in that environment can LOCK a resource with an
"overlapping" name until the first process releases the LOCK that it
holds.
2 Ex_of_Lock
Examples of LOCK
Example:
LOCK A,^B,@C
LOCK (A,B,@C)
The first LOCK command LOCKs A and unLOCKs A before LOCKing ^B, then
unLOCKs ^B before locking the name specified by the variable C. The
second LOCK command acquires all three resources at once. GT.M waits
until all the named resources in the argument list become available
before LOCKing all the resources. For example, if the resource
specified by the variable C is not available for LOCKing, GT.M waits
until that resource becomes available before LOCKing A and ^B.
Example:
LOCK (A,B)
LOCK +C
LOCK -B
This LOCKs A and B, then incrementally LOCKs C. Finally it releases the
LOCK on B, while retaining the LOCKs on A and C.
Example:
LOCK (A,B,C)
LOCK +(B,C)
LOCK -(B)
This LOCKs A, B and C together. It then increments the lock "counts" of
B and C. The last LOCK command removes one "count" of B, leaving one
count of A and B and two counts of C.
Example:
LOCK ^D:5
This command attempts to LOCK ^D with a timeout of five seconds. If
LOCK acquires the named resource before the timeout elapses, GT.M sets
$TEST to 1 (TRUE). If LOCK fails to acquire the named resource before
the timeout elapses, GT.M sets $TEST to 0 (FALSE).
1 MERGE
Merge
The MERGE command copies a variable and all its descendants into
another variable. MERGE does not delete the destination variable, nor
any of its descendants.
The format of MERGE command is:
M[ERGE][:tvexpr] glvn1=glvn2[,...]
o The optional truth-valued expression immediately following the
command is a command post conditional that controls whether or not
GT.M executes the command.
o When both glvn1 and glvn2 are local variables, the naked indicator
is not changed.
o If glvn2 is a global variable and glvn1 is a local variable, then
the naked indicator references glvn2.
o When both are global variables, the state of the naked indicator is
unchanged if glvn2 is undefined ($DATA(glvn2)=0).
o In all other cases including $DATA(glvn2)=10, the naked indicator
takes the same value that it would have if the SET command replaced
the MERGE command and glvn2 had a value.
o If glvn1 is a descendant of glvn2, or if glvn2 is a descendant of
glvn1; GT.M generates an error.
o An indirection operator and an expression atom evaluating to a list
of one or more MERGE arguments form a legal argument for a MERGE.
MERGE simplifies the copying of a sub-tree of a local or global
variable to another local or global variable. A sub-tree is all global
or local variables that are descendants of an specified variable. MERGE
offers a one-command alternative to the current technique for doing
sub-tree copy (that is, a series of SET commands with $ORDER
references).
GT.M may permit certain syntax or actions that are described by the
standard as in error. For example, a MERGE command that specifies
an operation where the source and destination overlap but
$DATA(source)=0 does not produce an error (which is equivalent to a
no-operation).
2 Ex_of_Merge
Examples of MERGE
Example:
GTM>SET ^gbl1="one"
GTM>SET ^gbl1(1,1)="oneone"
GTM>SET ^gbl1(1,1,3)="oneonethree"
GTM>SET ^gbl1(1,2,4)="onetwofour"
GTM>SET ^gbl2(2)="gbl2_2"
GTM>SET ^gbl2(2,1,3)="gbl2_2_1_3"
GTM>SET ^gbl2(2,1,4,5)="gbl2_2_1_4_5"
GTM>MERGE ^gbl1(1)=^gbl2(2)
GTM>WRITE $REFERENCE
^gbl1(1)
GTM>ZWRITE ^gbl1
^gbl1="one"
^gbl1(1)="gbl2_2"
^gbl1(1,1)="oneone"
^gbl1(1,1,3)="gbl2_2_1_3"
^gbl1(1,1,4,5)="gbl2_2_1_4_5"
^gbl1(1,2,4)="onetwofour"
GTM>ZWRITE ^gbl2
^gbl2(2)="gbl2_2"
^gbl2(2,1,3)="gbl2_2_1_3"
^gbl2(2,1,4,5)="gbl2_2_1_4_5"
GTM>
The example illustrates how MERGE copies a sub-tree of one global into
another. The nodes in the sub-tree of ^gbl(2), for which $DATA() value
is 1 or 11, are copied to sub-tree of ^gbl1(1) as follows:
^gbl1(1) is updated with value of ^gbl2(2)
^gbl1(1,1,3) is updated with value of ^gbl2(2,1,3)
^gbl1(1,1,4,5) is updated with value of ^gbl2(2,1,4,5)
Since ^gbl1(2,1) and ^gbl2(2,2,4) do not have values ($DATA()=0), the
corresponding nodes ^gbl1(1,1) and ^gbl(1,2,4) respectively are left
unchanged. The naked indicator takes the value ^gbl(1) as if SET
replaced MERGE. Notice that the MERGE command does not change ^gbl2(2)
or its descendants. Ancestor nodes of ^gbl(1) are also left unchanged.
Example:
GTM>KILL
GTM>SET ^gbl(1,2)="1,2"
GTM>MERGE lcl(3,4)=^gbl(1)
GTM>SET ^("naked")=2
GTM>ZWRITE ^gbl
^gbl(1,2)="1,2"
^gbl("naked")=2
GTM>ZWRITE lcl
lcl(3,4,2)="1,2"
GTM>
The example illustrates how MERGE creates a sub-tree of a variable when
the variable does not exist. Also, notice how the naked indicator is
set when the source of the MERGE is a global and the destination a
local.
1 NEW
New
The NEW command "stacks" copies of local variables and reinitializes
the variables. An explicit or implicit QUIT from a DO, XECUTE or
extrinsic function "unstacks" the NEWed variables, that is, restores
the variable to the stacked value. A NEW lasts only for the current
scope of execution.
The format of the NEW command is:
N[EW][:tvexpr] [[(]lvn[,...][)][,...]]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o NEW arguments are unsubscripted local variable names; NEW affects
not only the variable specified in the argument, but also all
variables descended from that variable.
o When an undefined variable is NEWed, the fact that it is undefined
is "stacked", and when leaving the current scope, it returns to
being undefined, that is, the variable is KILLed.
o Without an argument GT.M NEWs all currently existing local
variables; in this case, at least two (2) spaces must follow the
NEW to separate it from the next command on the line.
o When a NEW argument is enclosed in parentheses, that NEW is
considered "exclusive" and the variables inside the parentheses are
excluded from the effect of the NEW.
o When the flow of execution leaves the scope of an argumentless or
an exclusive NEW, GT.M restores all stacked variables to their
previous values, and deletes all other local variables.
o The intrinsic special variables $ESTACK, $ETRAP, $ZGBLDIR, and
$ZYERROR can be an explicit argument of a NEW.
o The intrinsic special variable $ZTRAP can also be an explicit
argument of a NEW; this stacks the current value of $ZTRAP and
assigns $ZTRAP a null value ($ZTRAP="").
o An indirection operator and an expression atom evaluating to a list
of one or more NEW arguments form a legal argument for a NEW.
The NEW command provides a means of confining the scope of local
variables. NEW operates only on unsubscripted local names and acts on
the entire named array.
2 Ex_of_New
Examples of NEW
Example:
SET A(1)=1,B=4,C=5
WRITE !,"VARIABLES BEFORE NEW:",!
ZWRITE
DO LABEL
WRITE !,"VARIABLES AFTER RETURN:",!
ZWRITE
QUIT
LABEL NEW A SET C=7
WRITE !,"VARIABLES AFTER NEW:",!
ZWRITE
QUIT
Produces the results:
VARIABLES BEFORE NEW:
A(1)=1
B=4
C=5
VARIABLES AFTER NEW:
B=4
C=7
VARIABLES AFTER RETURN:
A(1)=1
B=4
C=7
Example:
SET (A,B,C,D)="TEST"
DO LABEL
WRITE !,"VARIABLES AFTER RETURN:",!
ZWRITE
QUIT
LABEL NEW (B,C) SET (A,B,Z)="NEW"
WRITE !,"VARIABLES AFTER EXCLUSIVE NEW:",!
ZWRITE
QUIT
Produces the results:
VARIABLES AFTER EXCLUSIVE NEW:
A="NEW"
B="NEW"
C="TEST"
Z="NEW"
VARIABLES AFTER RETURN:
A="TEST"
B="NEW"
C="TEST"
D="TEST"
1 OPEN
Open
The OPEN command creates a connection between a GT.M process and a
device.
The format of the OPEN command is:
O[PEN][:tvexpr] expr[:[(keyword[=expr][:...])]
[:numexpr]][,...]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o The required expression specifies the device to OPEN.
o The optional keywords specify deviceparameters that control device
behavior; some deviceparameters take arguments delimited by an
equal sign (=); if the argument only contains one deviceparameter,
the surrounding parentheses are optional.
o The optional numeric expression specifies a time in seconds after
which the command should timeout if unsuccessful; choosing 0
results in a single attempt to open the device.
o When an OPEN command specifying a timeout contains no
deviceparameters, double colons (::) separate the timeout numeric
expression from the device expression.
o An indirection operator and an expression atom evaluating to a list
of one or more OPEN arguments form a legal argument for an OPEN.
1 QUIT
Quit
Except when a QUIT appears on a line after a FOR, the QUIT command
terminates execution of the current GT.M invocation stack level
initiated by a DO, XECUTE, extrinsic function or special variable, and
returns control to the next "lower" level. In this case, QUIT restores
any values stacked at the current level by NEWs or by parameter
passing. When a QUIT appears on the line following a FOR, it terminates
execution of the FOR.
The format of the QUIT command is:
Q[UIT][:tvexpr] [expr]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o When a QUIT terminates an extrinsic function, it must have an
argument that supplies the value returned by the function; in all
other cases, QUIT must not have an argument and must be followed by
at least two (2) spaces to separate it from the next command on the
line.
o An indirection operator and an expression atom evaluating to a QUIT
argument form a legal argument for a QUIT.
The QUIT performs two similar, but different, functions depending on
its context. Because FORs do not add levels to the GT.M invocation
stack, QUITs inside FOR loops simply terminate the loop. QUITs that
terminate DOs, XECUTEs and extrinsics remove a GT.M invocation stack
level and therefore may adjust the local variable environment resulting
from previous NEWs or parameter passing. A QUIT from an extrinsic or a
frame created by an argumentless DO restores $TEST to its stacked
value.
Attempting to QUIT (implicitly or explicitly) from code invoked by a
DO, XECUTE or extrinsic after that code issued a TSTART not yet matched
by a TCOMMIT, produces an error.
2 Ex_of_Quit
Examples of QUIT
Example:
DO A
QUIT
A WRITE !,"This is label A"
The explicit QUIT at the line preceding the label A prevents line A
from executing twice. The sub-routine at line A terminates with the
implicit QUIT at the end of the routine.
Example:
WRITE $$ESV
QUIT
ESV()
QUIT "value of this Extrinsic Special Variable"
Because the label ESV has an argument list (which is empty), GT.M can
only legally reach that label with a extrinsic invocation. The QUIT on
the second line prevents execution from erroneously "falling through"
to the line labelled ESV. Because ESV identifies a subroutine that
implements an extrinsic special variable, the QUIT on the line after
ESV has an argument to provide the value of the extrinsic.
Example:
SET x="" F S x=$O(^BAL(x)) Q:x]]"AR5999"!'$L(x) D STF
The postconditional QUIT terminates the FOR loop.
1 READ
Read
The READ command transfers input from the current device to a global or
local variable specified as a READ argument. For convenience, READ also
accepts arguments that perform limited output to the current device.
The format of the READ command is:
R[EAD][:tvexpr] (glvn|*glvn|glvn#intexpr)[:numexpr]|strlit|fcc[,...]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o A subscripted or unsubscripted global or local variable name
specifies a variable into which to store the input; the variable
does not have to exist prior to the READ; if the variable does
exist prior to the READ, the READ replaces its old value.
o When an asterisk (*) immediately precedes the variable name, READ
accepts one character of input and places the ASCII code for that
character into the variable.
o When a number-sign (#) and a non-zero integer expression
immediately follow the variable name, the integer expression
determines the maximum number of characters accepted as input to
the read; such reads terminate when GT.M reads the number of
characters specified by the integer expression or a terminator
character in the input stream, whichever occurs first.
o The optional numeric expression specifies a time in seconds at
most, for which the command waits for input to be terminated. When
a timeout is specified, if the input has been terminated before the
timeout expires, $TEST is set to 1 (true), otherwise, $TEST is set
to 0 (false).
o To provide a concise means of issuing prompts, GT.M sends string
literal and format control character (!,?intexpr,#) arguments of a
READ to the current device as if they were arguments of a WRITE.
o An indirection operator and an expression atom evaluating to a list
of one or more READ arguments form a legal argument for a READ.
1 SET
Set
SET assigns values to variables or to a selected portion of a variable.
The format of the SET command is:
S[ET][:tvexpr] glvn|$EXTRACT()|$PIECE()|(glvn[,...])=expr[,...]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o A subscripted or unsubscripted local or global variable name on the
left of the equal-sign (=) specifies a variable in which to store
the expression found on the right side of the equal-sign; the
variable need not exist prior to the SET; if the variable exists
prior to the SET, the SET replaces its old value.
o During a SET, GT.M evaluates the right side of the equal sign
before the left; this is an exception to the left-to-right order of
evaluation in GT.M and means that GT.M maintains the naked
indicator using the expression on the right-hand side of the equal
sign (=) before setting the variable.
o When the portion of the argument to the left of the equal-sign is
in the form of a list of variables enclosed in parentheses, SET
assigns the value of the expression on the right of the equal sign
to all the variables.
o When the portion of the argument to the left of the equal sign is
in the form of a $PIECE function, SET replaces the specified piece
or pieces of the variable (specified as the first argument to the
$PIECE() form) with the value of the expression on the right side
of the equal-sign; if the variable did not exist prior to the SET
or does not currently contain the pieces identified by the optional
third and fourth arguments to the $PIECE() form, SET adds
sufficient leading delimiters, as specified by the second argument
to the $PIECE form, to make the assignment fit the $PIECE() form.
Note that if the fourth argument exceeds the third argument, the
target glvn is not changed and the naked indicator is also not
modifed.
o When the portion of the argument to the left of the equal sign is
in the form of a $EXTRACT function, SET replaces the specified
character or characters of the variable (specified as the first
argument to the $EXTRACT() form) with the value of the expression
on the right side of the equal-sign; if the variable did not exist
prior to the SET or does not contain the characters identified by
the optional second and third arguments to the $EXTRACT() form, SET
adds sufficient leading spaces to make the assignment fit the
$EXTRACT() form. Note that if the third argument exceeds the second
argument, the target glvn is not changed and the naked indicator is
also not modifed.
o The left-hand side of the equal-sign may also contain any of the
following Intrinsic Special Variables:
$ECODE
$ETRAP
$X
$Y
$ZCOMPILE
$ZDIRECTORY
$ZERROR
$ZGBLDIR
$ZINTERRUPT
$ZMAXTPTIME
$ZPROMPT
$ZROUTINES
$ZSOURCE
$ZSTATUS
$ZSTEP
$ZTRAP
$ZYERROR
o An indirection operator and an expression atom evaluating to a list
of one or more SET arguments form a legal argument for a SET.
Because GT.M does not require predeclaration or typing of variables, a
SET with proper syntax always succeeds regardless of the prior state or
value of the variable, as long as GT.M can evaluate the expression to
the right of the equal sign (=).
2 Ex_of_Set
Examples of SET
Example:
GTM>KILL SET a="x",(b,c)=1,@a="hello" ZWRITE
a=x
b=1
c=1
x="hello"
GTM>
The KILL command deletes any previously defined local variables. The
SET command has three arguments. The first shows a simple direct
assignment. The second shows the form that assigns the same value to
multiple variables. The third shows atomic indirection on the left of
the equal sign. The ZWRITE command displays the results of the
assignments.
Example:
GTM>SET ^(3,4)=^X(1,2)
Because GT.M evaluates the right-hand side of the equal sign before the
left-hand side within a SET argument, the right-hand expression
determines the
naked reference indicator prior to evaluation of the left-hand side.
Therefore, this example assigns ^X(1,3,4) the value of ^X(1,2).
Example:
GTM>KILL x SET $P(x,"^",3)="piece 2" ZWRITE x
x="^^piece 2"
GTM>
This SET demonstrates a "setpiece" and shows how SET generates missing
delimiters when required.
Example:
GTM>SET x="I love hotdogs"
GTM>SET $EXTRACT(x,3,6)="want"
GTM>WRITE x
I want hotdogs
GTM>SET $EXTRACT(x,7)=" many "
GTM>WRITE x
I want many hotdogs
GTM>
The SET $EXTRACT command replaces and extracts the specified characters
with the value of the expression on the right hand side of the
equal-sign (=).
1 TCOMMIT
TCommit
The TCOMMIT command marks the end of a transaction or sub-transaction
and decrements $TLEVEL. If TCOMMIT marks the end of a transaction
(decrements $TLEVEL to zero), it invokes a COMMIT, which makes the
database updates performed by the transaction generally available. A
TCOMMIT issued when no transaction is in progress ($TLEVEL=0) produces
an error.
The format of the TCOMMIT command is:
TC[OMMIT][:tvexpr]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o Because TCOMMIT has no argument, at least two (2) spaces must
follow the command to separate it from the next command on the
line.
For an example of the use of the TCOMMIT command, refer to the chapter
on General Language Features of M in GT.M Programmer's Guide.
1 TRESTART
TREstart
The TRESTART command attempts to RESTART the current transaction. A
RESTART transfers control back to the initial TSTART and restores much
of the process state to what it was when that TSTART was executed.
Errors are produced if a TRESTART is used when no transaction is in
progress ($TLEVEL=0) and when the transaction does not have RESTART
enabled.
The format for the TRESTART command is:
TRE[START][:tvexpr]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o Because TRESTART has no argument, at least two (2) spaces must
follow the command to separate it from the next command on the
line.
TRESTARTs (and implicit RESTARTs) do not restore any device states;
they do restore the following to the state they had when GT.M executed
the initial TSTART:
o $TEST
o The naked indicator
o LOCKs held by the process
They also restore any local variables named by one or more active
TSTARTs to the values they had when they were first named.
For an example of the use of the TRESTART command, refer to the chapter
on "General Language Features of M" in the GT.M Programmer's Guide.
1 TROLLBACK
TROllback
The TROLLBACK command terminates a transaction by causing a ROLLBACK,
which removes all database updates performed within a transaction.
TROLLBACK also sets $TLEVEL and $TRESTART to zero (0). Issuing a
TROLLBACK when no transaction is in progress ($TLEVEL=0) produces an
error.
The format of the TROLLBACK command is:
TRO[LLBACK][:tvexpr] [intexpr]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o The optional integer expression indicates an argument specifying
incremental rollback. If the value of the argument expression is
greater than zero, it specifies the value of $TLEVEL to be achieved
by the rollback. If the value of the expression is less than zero,
the result is the number of levels to rollback. For example; -1
means rollback one level. If the argument expression is zero, the
effect is same as not specifying the argument, that is, the entire
GT.M transaction is rolled back.
Attempting to rollback more than $TLEVEL levels (the outermost
transaction) generates an error.
o When the TROLLBACK has no argument, at least two (2) spaces must
follow the command to separate it from the next command on the
line.
In order to allow for error recovery and/or access to the global
context of the error, errors do not initiate implicit ROLLBACKs.
Therefore, the code for handling errors during transactions should
generally include a TROLLBACK. Because the TROLLBACK releases resources
held by the transaction, it should appear as early as possible in the
error handling code.
A TROLLBACK does not cause a transfer of control but is typically
associated with one such as a QUIT or GOTO.
For an example of the use of the TROLLBACK command, refer to the
chapter on "General Language Features of M" in the GT.M Programmer's
Guide.
1 TSTART
TStart
A TSTART command marks the beginning of a transaction or
sub-transaction and increments $TLEVEL. When TSTART marks the beginning
of a transaction ($TLEVEL=1), its arguments determine whether the
transaction may RESTART and whether serializability is enforced. If a
transaction may RESTART, the TSTART arguments determine which local
variables are restored during a RESTART. Serializability is enforced by
LOCK commands or, if the SERIAL keyword is specified, by GT.M.
The format of the TSTART command is:
TS[TART][:tvexpr] [([lvn...])|lvn|*|][:keyword|(keyword...)]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o If $TLEVEL is 0 before the TSTART, the TSTART starts a transaction;
otherwise it starts a sub-transaction.
o If the TSTART initiates a transaction and the portion of the
argument before the colon (:) delimiter is empty, the transaction
is not eligible for RESTART. If the TSTART starts a transaction
($TLEVEL=0) and the portion of the argument before the colon is not
empty, the transaction is eligible for RESTART. If the TSTART is
nested (starts a sub-transaction), its arguments have no effect on
whether the transaction is eligible for RESTART.
o If the portion of the argument before the colon is an asterisk (*),
any subsequent RESTART restores all local variables to the value
they had when the TSTART was executed.
o If the portion of the argument before the colon is an unsubscripted
local variable name or a list of such names enclosed in
parentheses, a RESTART restores the named variables to the value
they had when the TSTART was executed.
o If the portion of the argument before the colon is a set of empty
parentheses (), a RESTART does not restore any local variables.
o The optional portion of the argument after the colon is a keyword
or a colon-separated list of keywords enclosed in parentheses,
where the keywords specify transaction characteristics.
o An indirection operator and an expression atom evaluating to a
TSTART argument form a legal argument for a TSTART.
A TSTART within a transaction starts a sub-transaction. The argument to
such a TSTART has no effect on whether the existing transaction may
RESTART or whether serializability of the transaction is enforced. This
type of TSTART may add local variables to be restored in a transaction
that has RESTART enabled.
It is good coding practice to synchronize enabling of RESTART on
TSTARTs at all levels of a transaction. A nested TSTART that does not
permit RESTART where the transaction does, may indicate that the
sub-transaction has not been coded to properly handle RESTART.
Sub-transactions cannot COMMIT independently from the transaction, nor
can they RESTART independently. Sub-transactions exist largely as a
programming convenience to allow flexibility in organizing code in a
modular fashion, and in addition to allow incremental ROLLBACKs.
When journaling, a transaction with an initial TSTART that has an
argument specifying TRANSACTIONID=expr, where expr is an expression
that evaluates to the keyword (case insensitive) BA[TCH], does not wait
for the journal update to be written before returning control to the
application after a successful TCOMMIT. The goal of this feature is to
permit application control over any performance impact of journaling on
any subset of transactions that can be recreated or recovered by means
other than journaling.
For an example of the use of the TSTART command, refer to the chapter
on "General Language Features of M" in the GT.M Programmer's Guide.
The following keywords may appear in a TSTART argument:
2 SERIAL
S[ERIAL]
The SERIAL keyword indicates that GT.M must ensure the serializability
of the transaction. When the SERIAL keyword is absent, the GT.M program
must ensure serializability by proper use of LOCK commands. On a nested
TSTART, this portion of the argument is ignored.
2 TRANSACTIONID
T[RANSACTIONID]=expr
The TRANSACTIONID keyword declares an arbitrary transaction
identification.
If TRANSACTIONID="BATCH" or "BA" at transaction completion, the process
immediately continues execution. When a process issues a [final]
TCOMMIT for a transaction and journaling is active, by default the
process waits until the entire transaction is written to the journal
file(s) before executing the next command. This ensures that every
transaction is durable before the process moves on to the next step.
Transactions flagged as "BATCH" have lower latency and higher
throughput, but a lower guarantee of durability. Normally this flag is
used when operational procedures (such as a backup) or application code
(such as a checkpoint algorithm) provides an acceptable alternative
means of ensuring durability.
1 USE
Use
The USE command selects the current device for READs (input) and WRITEs
(output).
The format of the USE command is:
U[SE][:tvexpr] expr[:(keyword[=expr][:...])][,...]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o The required expression specifies the device to make the current
device.
o A USE that selects a device not currently OPENed by the process
causes a run-time error.
o The optional keywords specify deviceparameters that control device
behavior; some deviceparameters take arguments delimited by an
equal sign (=); if the argument only contains one deviceparameter,
the surrounding parentheses are optional.
o An indirection operator and an expression atom evaluating to a list
of one or more USE arguments form a legal argument for a USE.
For more information on USE, devices and deviceparameters, refer to the
"Input/Output Processing" chapter in the GT.M Programmer's Guide.
1 VIEW
View
The VIEW command adjusts an environmental factor selected by a keyword
argument. For example, VIEW controls journal buffer flushing,
determines whether GT.M reports undefined variables as errors or treats
them as null, and determines which BREAK commands should display
messages.
The format of the VIEW command is:
V[IEW][:tvexpr] keyword[:expr2[:...]][,...]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o The keyword specifies the environmental factor to change.
o The optional expression following the keyword specifies the nature
of the change to the environmental factor.
o An indirection operator and an expression atom evaluating to a list
of one or more VIEW arguments form a legal argument for a VIEW
2 Key_Words_View
Key Words in VIEW Command
The following sections describe the keywords available for the VIEW
command in GT.M.
3 BREAKMSG
"BREAKMSG":value
Sets the value of the BREAK message mask. When GT.M processes a BREAK
command, the BREAK message mask controls whether to display a message
describing the source of the BREAK.
The mask uses the following four values that are added together to
provide the BREAKMSG value.
1 - BREAKs within the body of a program
2 - BREAKs within a ZBREAK action
4 - BREAKs within a device EXCEPTION
8 - BREAKs within a ZSTEP action
By default GT.M displays all BREAK messages.
Example:
GTM>VIEW "BREAKMSG":5
In this example the BREAKMSG value is 5, representing the sum of 1 and
4. This enables BREAKS within the body of a program (value 1) and for a
device EXCEPTION (value 4).
3 GDSCERT
"GDSCERT":value
Enables (value=1) or disables (value=0) database block certification.
Database block certification causes GT.M to check the internal
integrity of every block as it writes the block. Block certification
degrades performance and exists primarily as a tool for use by Sanchez.
The default is GDSCERT:0.
3 JNLFLUSH
"JNLFLUSH"[:region]
Writes or flushes journaling buffers associated with the given region
to permanent storage, for example, to disk. If the VIEW "JNLFLUSH" does
not specify the optional region, GT.M flushes all active regions of the
current Global Directory.
Normally GT.M writes journal buffers when it fills the journal buffer
pool or when some period of time passes with no journal activity.
For more information on journaling, refer to the "GT.M Journaling"
chapter in the GT.M Administration and Operations Guide.
3 JNLWAIT
"JNLWAIT"
Causes a process to pause until its journaling buffers have been
written. JNLWAIT ensures that GT.M successfully transfers all database
updates issued by the process to the journal file before the process
continues. Normally, GT.M performs journal buffer writes asynchronously
while the process continues execution.
For more information on journaling, refer to the "GT.M Journaling"
chapter in the GT.M Administration and Operations Guide.
3 JOBPID
"JOBPID":"value"
Enables (value=1) or disables (value=0) the addition of the child
process ID to the output and error filenames generated by the JOB
command.
This option prevents output files generated by the JOB command from
being overwritten each time a new job is spawned from the GT.M source
file.
3 LABELS
"LABELS":"value"
Enables (value="LOWER") or disables (value="UPPER") case sensitivity
for labels within routines.
It is important to have the same case handling at compile-time and
run-time.
Because GT.M stores routines as regular files and file names are case
sensitive on UNIX, GT.M always treates routine names as case sensitive.
3 LVNULLSUBS
"[NO]LVNULLSUBS"
Allows or disallows local arrays to have null subscripts. The default
is LVNULLSUBS.
3 NOISOLATION
"NOISOLATION":<expr>
where expr must evaluate to one of the following forms
o "", that is, empty string : turn off the feature for all globals
for which it has previously been turned on
o "^gvn1,^gvn2,..." : turn on the feature for the globals in the
list, turning it off for globals for which it has previously been
turned on
o "+^gvn1,^gvn2,..." : add these globals to the list of globals that
have this feature turned on
o "-^gvn1,^gvn2,..." : turn off the feature for these globals leaving
the status for other globals unchanged
GT.M transaction processing permits the application to specify a set of
globals that do not require GT.M to preserve Isolation, one of the
"ACID" properties of TP. This shifts the responsibility for Isolation
from GT.M to the application logic, and permits GT.M to relax its TP
Isolation rules. This avoids TP restarts in certain cases thus
improving the performance of the application. For example, if a global
variable includes $JOB as a subscript, the application may be written
and scheduled in such a way that no more than one process uses a node
of that global at any given time. Specifying such a global as
"NOISOLATED" avoids transaction restarts that occur when different
processes concurrently update and access nodes that share the same GDS
block.
The rules for enforcement by GT.M of Isolation, and therefore
potentially Consistency, are relaxed for application-specified global
variables in order to allow the application to manage these properties.
GT.M is responsible for Atomicity and Durability, as well as for
database integrity for all variables, and for Isolation and Consistency
for any global variables for which the application does not accept
responsibility.
Note that if an application incorrectly specifies a global to be
NOISOLATED, severe, and possibly intermittent and difficult to diagnose
damage to application-level integrity is likely to result. A thorough
understanding of the application is necessary before declaring a global
to be noisolated. GT.M preserves database integrity (accessibility) for
NOISOLATED, as well as ISOLATED global variables.
GT.M ignores attempts to turn on (or off) the feature for globals that
already have the feature turned on (or off). It is an error to modify
the isolation-status of a global variable within a transaction across
different references (either reads or writes) of that global
variable.The VIEW command by itself is not considered to be a reference
of the global variable. While not recommended programming practice,
this means that a process can change a global's isolation-status within
a transaction as long as it hasn't referenced it yet.
Any reads on a NOISOLATION global are validated at the time of the read
and not re-validated at TCOMMIT time. This means that if the value that
was read changed after the read but before the TCOMMIT, the transaction
would still be committed. Therefore it is important that any reads on a
NOISOLATED global (if any) should be of data that does not change with
time. Sanchez has not identified applications where this could be an
issue.
3 PATCODE
"PATCODE":"tablename"
Identifies the alternative table of unique patterns for use with the
"?" operator to be loaded from the pattern definition file. For
additional information refer to the "Internationalization" chapter in
the GT.M Programmer's Guide.
3 PATLOAD
"PATLOAD":"file-specification"
Identifies the file containing definitions of unique patterns for use
with the "?" operator. These pattern definitions can be used in place
of, or in addition to, the standard C, N, U, L, and P.
3 UNDEF
"[NO]UNDEF"
Enables or disables handling of undefined variables as errors. With
UNDEF, GT.M handles all references to undefined local or global
variables as errors. With NOUNDEF, GT.M handles all references to
undefined local or global variables as if the variable had a value of
the null string. In other words, GT.M treats all variables appearing in
expressions as if they were the argument of an implicit $GET(). UNDEF
is the default.
3 TRACE
"TRACE":value<expr>
Traces GT.M program execution and generates profiling information about
the lines and functions executed; with low impact on the run-time
performance.
The feature turns on (value=1) or turns off (value=0) tracing. <expr>
must evaluate to a string containing the name of a GT.M global
variable. The global may also have subscripts; however the subscripts
must be literals or the special variable $JOB.
The <expr> is optional when turning tracing off, if it exists, it
overrides the global variable set when tracing was turned on.
GT.M-tracing uses a technique called Basic Block Counting where calls
are made to special profiling functions at key points in a GT.M
program. A trace consists of the following run-time data as output for
each GT.M function, as well as for each GT.M statement:
o The number of times it is executed.
o The total CPU time spent across all invocations for each function
and each GT.M statement as three values: user time, system time,
and total time.
Instead of modifying the generated code as done by common profiling
tools, such as gprof, GT.M tracing operates entirely within the GT.M
run-time system; therefore, this feature does not require a special
compilation, has no effect on code size and minimizes run-time
overhead.
When the feature is turned on, it gathers profiling information for
each line and GT.M function invocation. The reported time for a GT.M
line is the time spent in generated code for that line, and does not
include time spent in entreyrefs called from that line. When profiling
is turned off, the accumulated statistics are loaded into a GT.M
global. GT.M profiling accumulates and provides the data; the user may
choose tools and techniques to analyze the data.
The trace information is stored in the variable in the following
format:
o If <expr> is a global variable without subscripts name such as
"^foo", the trace information is stored in the nodes
^foo(<routine>,<label>) and ^foo(<routine>,<label>,<offset>), each
of which has a value in the form
"<count>:<usertime>,:<systemtime>,:<total_time>" on UNIX.
o If <expr> has a value such as "^foo("MYTRACE",$J)", the trace
information is stored in the nodes
^foo("MYTRACE",<pid>,<routine>,<label>) and
^foo("MYTRACE",<pid>,<routine>,<label>,<offset>), each of which has
a value in the form "<count>,<usertime>,<systemtime>,<total_time>"
on UNIX as described above.
o For FOR loops, information for each level of the loop is stored in
the nodes as described above, with the extra subscipts "FOR_LOOP".
<for_level> is the value of the number of iterations at that level
of the FOR loop.
Thus, if the GT.M program lv1.m is:
lv1 f i=1:1:10 d
.s l(i)=i
.d bar
for i=1:1:5 for j=1:1:4 s lij(i,j)=i+j
q
bar s l(-i)=-i
q
And the program lv2.m is:
lv2 VIEW "TRACE":1:"^lvtr"
d ^lv1
VIEW "TRACE":0:"^lvtr"
zwr ^lvtr
q
On executing lv2, the output looks like this (times in the example were
chose for clarity of illustration and are not typical):
^lvtr("lv1","bar")="10:8:1:9"
^lvtr("lv1","bar",0)="10:5:1:6"
^lvtr("lv1","bar",1)="10:3:0:3"
^lvtr("lv1","lv1")="1:37:2:39"
^lvtr("lv1","lv1",0)="1:8:0:8"
^lvtr("lv1","lv1",0,"FOR_LOOP",1)=10
^lvtr("lv1","lv1",1)="10:3:1:4"
^lvtr("lv1","lv1",2)="10:19:2:21"
^lvtr("lv1","lv1",3)="1:15:0:15"
^lvtr("lv1","lv1",3,"FOR_LOOP",1)=5
^lvtr("lv1","lv1",3,"FOR_LOOP",2)=20
^lvtr("lv1","lv1",4)="1:0:0:0"
^lvtr("lv2","lv2",1)="1:47:3:50"
In this case, ^lvtr("lv1","bar",0)="10:5:1:6" means that the statement
bar s l(-i)=-i was executed 10 times, with a total of 5 microseconds of
user time and 1 microsecond of system time.
^lvtr("lv1","lv1")="1:37:2:39" means that 37 microseconds of user time
was spent within that GT.M frame (lv1^lv1), and does not include time
spent in routines called from it (such as bar^lv1), whereas
^lvtr("lv1","lv1",3)= "1:15:0:15" includes the time spent at bar^lv1.
Note that there is no data in ^lvtr("lv2","lv2",0) or for
^lvtr("lv2","lv2",2) because the execution of the lines containing the
VIEW commands that turn profiling on and off are not profiled.
Because of the underlying timers provided by the operating systems,
times of less than a microsecond are measured as zero. Therefore, even
if a statement executes one million times, it may report zero time if
it took less than a microsecond each time.
GT.M profiling cannot handle more than 1024 levels. If the GT.M code
executed has more than 1024 levels, frame information cannot be
recorded, and frame information upto the first point where this limit
is reached is reported with a note (":INCOMPLETE DATA: MAXTRACELEVEL" )
appended to the data.
2 Ex_of_View
Examples of VIEW
Example 1:
GTM>KILL A
GTM>VIEW "NOUNDEF"
GTM>WRITE A,?10,$L(A)
0
GTM>
This demonstrates how a VIEW that specifies NOUNDEF prevents UNDEFined
errors.
Example 2:
GTM>ZL "NOSENSE"
%GTM-E-LABELMISSING Label referenced but
not defined:lab
%GTM-I-SRCNAM in source module /usr/work/NOSENSE.m
GTM>
GTM>ZPRINT ^NOSENSE
NOSENSE;
DO lab
QUIT
LAB WRITE !,"THIS IS NOSENSE"
QUIT
GTM>VIEW "LABELS":"UPPER"
GTM>ZLINK "NOSENSE.m"
GTM>DO ^NOSENSE
THIS IS NOSENSE
GTM>
This demonstrates use of VIEW "LABELS" to make label handling case
insensitive. Notice that the routine was ZLINKed with an extension of
.m to force a recompile and ensure that the object code and the
run-time handling of labels is the same.
1 WRITE
Write
The WRITE command transfers a character stream specified by its
arguments to the current device.
The format of the WRITE command is:
W[RITE][:tvexpr] expr|*intexpr|fcc[,...]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o An expression argument supplies the text of a WRITE.
o When a WRITE argument consists of a leading asterisk (*) followed
by an integer expression, WRITE outputs one ASCII character
associated with the ASCII code specified by the integer evaluation
of the expression.
o WRITE arguments may also be format control characters; format
control characters modify the position of a virtual cursor: an
exclamation point (!) produces a new line, a number-sign (#)
produces a new page and a question-mark (?) followed by an
expression moves the virtual cursor to the column specified by the
integer evaluation of the expression provided that the virtual
cursor is to the "left" of the specified column; if the virtual
cursor is not to the left of the specified column, then the text is
printed at the current cursor position.
o An indirection operator and an expression atom evaluating to a list
of one or more WRITE arguments form a legal argument for a WRITE.
For more information on WRITE, devices, input, output and format
control characters, refer to the "Input/Output Processing" chapter in
GT.M Programmer's Guide.
1 XECUTE
Xecute
The XECUTE command makes an entry in the GT.M invocation stack and
executes the argument as GT.M code.
The format of the XECUTE command is:
X[ECUTE]:tvexpr expr[:tvexpr][,...]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o The required expression specifies a fragment of GT.M source code.
o The optional truth-valued expression immediately following the
argument expression specifies the argument postconditional and
controls whether GT.M performs an XECUTE with that argument.
o An indirection operator and an expression atom evaluating to a list
of one or more XECUTE arguments form a legal argument for an
XECUTE.
An explicit or implicit QUIT within the scope of the XECUTE, but not
within the scope of any other DO, FOR, XECUTE or extrinsic, returns
execution to the instruction following the calling point. This may be
the next XECUTE argument or another command. At the end of the code
specified by the XECUTE argument expression, GT.M performs an implicit
QUIT.
Because XECUTE causes run-time compilation in GT.M, and because it
tends to obscure code, use XECUTE only when other approaches clearly do
not meet your particular requirement.
2 Ex_of_Xecute
Examples of XECUTE
Example:
GTM>SET A="HELLO" XECUTE "WRITE A"
HELLO
GTM>
This demonstrates a simple use of XECUTE.
Example:
SET x="" F S x=$O(^%x(x)) Q:x="" X x
This $ORDER() loop XECUTEs code out of the first level of the global
array ^%x. Note that, in most cases, having the code in a GT.M source
file, for example TMPX.m, and using a DO ^TMPX improves efficiency.
1 ZALLOCATE
ZAllocate
The ZALLOCATE command reserves the specified name without releasing
previously reserved names. Other GT.M processes cannot reserve the
ZALLOCATEd name with a ZALLOCATE or LOCK command.
The ZALLOCATE command provides compatibility with some other GT.M
implementations. The M Development Committee chose to add the + and -
delimiters to the LOCK command (incremental locking) rather than adopt
the ZALLOCATE and ZDEALLOCATE approach. Therefore, when a design
requires an incremental lock mechanism, LOCK +/- has the advantage over
ZALLOCATE / ZDEALLOCATE of being part of the M standard. LOCK +/- also
has the advantage of working symmetrically when routines using LOCKs
are nested. That is, a ZALLOCATE command issued by a process for a
named resource already ZALLOCATEd by that process results in no change
of state. This means that routines that do ZALLOCATE followed by a
ZDEALLOCATE on a named resource that is already ZALLOCATEd by the same
process (at routine entry time), will end up ZDEALLOCATEing the named
resource (which might not be desired). On the other hand, a LOCK +
command issued by a process for a named resource already LOCKed by that
process causes the LEVEL of the LOCK to be incremented (as seen in a
ZSHOW "L" output). Every LOCK - command on that named resource causes
the LEVEL to be decremented. When the LEVEL becomes 0, the named
resource is no longer LOCKed.
For more information on troubleshooting LOCKs with the GT.M Lock
Utility (LKE), refer to the appropriate chapter of the GT.M
Administration and Operations Guide.
The format of the ZALLOCATE command is:
ZA[LLOCATE][:tvexpr] [(]nref[,...][)][:intexpr][,...]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o The nref argument specifies a name in the format of a GT.M name
with or without subscripts, and with or without a preceding caret
(^).
o Outside of transactions, only one process in an environment can
ZALLOCATE (or LOCK) a particular resource name at any given time.
o Because the data storage in GT.M uses hierarchical sparse arrays
and ZALLOCATE may serve to protect that data from inappropriate
"simultaneous" access by multiple processes, ZALLOCATE treats
resource names in a hierarchical fashion; a ZALLOCATE protects not
only the named resource, but also its ancestors and descendants.
o When one or more nrefs are enclosed in parentheses (), ZALLOCATE
reserves all the enclosed names "simultaneously," that is, it
reserves none of them until all become available.
o The optional numeric expression specifies a time in seconds after
which the command should timeout if unsuccessful; choosing 0
results in a single attempt.
o An indirection operator and an expression atom evaluating to a list
of one or more ZALLOCATE arguments form a legal argument for a
ZALLOCATE.
For an explanation of the LOCK command see the "LOCK" section in the M
LOCK Utility chapter of GT.M Administration and Operations Guide.
If a ZALLOCATE command specifies a timeout, and GT.M acquires ownership
of the named resource before the timeout elapses, ZALLOCATE sets $TEST
to TRUE (1). If GT.M cannot acquire ownership of the named resource
within the specified timeout, ZALLOCATE sets $TEST to FALSE (0). If a
ZALLOCATE command does not specify a timeout, the execution of the
command does not affect $TEST.
When given a list of nrefs, ZALLOCATE tries to reserve each nref from
left to right in the order specified taking into account the timeout
specified for each. If the timeout elapses before reserving an nref,
GT.M terminates the ZALLOCATE command. Any nrefs already acquired as
part of the current ZALLOCATE command stay acquired.
2 Ex_of_ZAllocate
Examples of ZALLOCATE
Examples:
ZALLOCATE A
ZALLOCATE ^A
ZALLOCATE ^A(1)
ZALLOCATE (^B("smith"),^C("jones"))
ZALLOCATE @A
The first command ZALLOCATEs A; the second, ^A; the third, ^A(1) and
the fourth, both ^B("smith") and ^C("jones") simultaneously. The last
command ZALLOCATEs the resources named by the value of the variable A.
Example:
ZALLOCATE A,^B,@C
ZALLOCATE (A,B,C)
If ZALLOCATE arguments are enclosed in parentheses, the command waits
until all names in the argument list become available before reserving
any of the names. For example, in the statement ZA (A,B,C), if the
resource named C is not available, ZALLOCATE waits until C becomes
available before reserving A and B. Using the format illustrated in the
first line above, can cause deadlocks because the resource names are
reserved as they come available.
When a process attempts to ZALLOCATE a name currently ZALLOCATEd or
LOCKed (with the LOCK command) by another process, the ZALLOCATEing
process hangs until the other process releases the name. In the event
that names remain unavailable for significant periods of time, timeouts
allow the process issuing a ZALLOCATE to regain program control.
Example:
ZALLOCATE ^D:5
This example specifies a timeout of five seconds. If GT.M reserves ^D
before the five seconds elapses, ZALLOCATE sets $TEST to TRUE. If GT.M
cannot reserve ^D within the five second timeout, ZALLOCATE sets $TEST
to FALSE.
When you ZALLOCATE a name, no names previously reserved with ZALLOCATE
or the LOCK command are released (similarly, LOCKing a name does not
release names that have been ZALLOCATEd). For example, after
ZALLOCATEing A and LOCKing B, LOCKing B does not release A, and
ZALLOCATEing C does not release A or B.
To release a ZALLOCATEd name, use the ZDEALLOCATE command. The
ZDEALLOCATE command can only release previously ZALLOCATEd (not LOCKed)
names.
Resource name arguments for LOCKs and ZALLOCATEs intersect. That is, if
one process holds a LOCK or ZALLOCATE, another process can neither LOCK
nor ZALLOCATE any name falling in the hierarchy of the resource name
held by the first process. When a process holds a LOCK or ZALLOCATE,
that same process may also LOCK or ZALLOCATE resource names falling in
the hierarchy of the currently held resource name. When a single
process holds both LOCKs and ZALLOCATEs, a LOCK does not release the
ZALLOCATEd resource(s) and a ZDEALLOCATE does not release the LOCKed
resource(s).
Example:
L ^AR(PNT)
.
.
.
ZALLOCATE ^AR(PNT,SUB)
.
.
.
L ^TOT(TDT)
.
.
.
ZDEALLOCATE ^AR(PNT,SUB)
This LOCKs ^AR(PNT), then, after performing some unspecified commands,
it ZALLOCATEs ^AR(PNT,SUB). Because ZALLOCATE does not imply any change
to LOCKs or existing ZALLOCATEd resource names, the LOCK of ^AR(PNT)
remains in effect. Assuming the routine does not modify the variable
PNT, ^AR(PNT,SUB) is already protected by the LOCK. Next, because an
unsigned LOCK releases all resource names currently LOCKed by the
process, the routine releases ^AR(PNT) with the LOCK of ^TOT(TDT). This
leaves the ZALLOCATE of ^AR(PNT,SUB). The name ^AR and all its
subscripts except for those that begin with ^AR(PNT,SUB) are now
available for LOCKing by other processes. Finally the routine releases
^AR(PNT,SUB) with a ZDEALLOCATE command. The ZDEALLOCATE does not
affect the LOCK on ^TOT(TDT). Note that this example was constructed to
illustrate the interaction between LOCK, ZALLOCATE and ZDEALLOCATE, and
not to illustrate sound programming practice.
1 ZBREAK
ZBreak
The ZBREAK command sets or clears routine breakpoints during debugging.
The format of the ZBREAK command is:
ZB[REAK][:tvexpr] [-]entryref[:[expr][:intexpr]]
[,...]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o The required entryref specifies a location within a routine at
which to set or remove a breakpoint.
o The optional minus sign (-) specifies that ZBREAK remove the
breakpoint; -* means remove all breakpoints.
o The optional expression specifies a fragment of GT.M code to XECUTE
when GT.M execution encounters the breakpoint; if the ZBREAK
argument does not specify an action, the default action is "BREAK".
o The optional integer expression immediately following the
expression specifies a count of process transits through the
breakpoint before the breakpoint action takes effect; once GT.M
exhausts the count and the action takes effect, the action occurs
every time the process encounters the breakpoint. If the action
expression is omitted, the optional integer expression must be
separated from the entryref by two adjacent colons (::).
o An indirection operator and an expression atom evaluating to a list
of one or more ZBREAK arguments form a legal argument for a ZBREAK.
When GT.M encounters the entryref, GT.M suspends execution of the
routine code and XECUTEs the breakpoint action before executing any of
the commands on the line.
When the optional integer expression is used, GT.M activates the
breakpoint on the intexpr-th time the process encounters the breakpoint
during routine execution. Once GT.M activates the breakpoint, that
breakpoint remains active for the process until explicitly replaced or
removed, or until the process terminates.
2 Ex_of_ZBreak
Examples of ZBREAK
Example:
GTM>ZPRINT ^ZBTEST
ZBTEST;
DO SUB
QUIT
SUB WRITE !,"This is ZBTEST"
QUIT
GTM>ZBREAK SUB^ZBTEST
GTM>DO ^ZBTEST
%GTM-I-BREAKZBA, Break instruction encountered
during ZBREAK action
At M source location SUB^ZBTEST
GTM>
ZSHOW "B"
SUB^ZBTEST
This inserts a ZBREAK with a default action at SUB^ZBTEST. After GT.M
encounters the BREAK, the ZSHOW "B" displays this as the only ZBREAK in
the image.
Example:
GTM>ZBREAK -*
GTM>ZGOTO
GTM>ZBREAK SUB^ZBTEST:"W !,""Trace"""
GTM>DO ^ZBTEST
Trace
This is ZBTEST
GTM>
This removes all existing ZBREAKs with a ZBREAK -*. Note that it is not
necessary to remove ZBREAKs before modifying them. It also clears the
process invocation stack with an argumentless ZGOTO. Then it uses a
ZBREAK to insert a trace-point. Every time GT.M executes the line to
where ZBREAK has established a trace-point, it performs the specified
action without entering Direct Mode.
Example:
ZBREAK PRINT^TIME::5
This BREAKs execution at line PRINT in routine just before the fifth
time the line is executed.
Example:
ZBREAK PRINT^TIME:"WRITE AVE BREAK":3
This inserts a ZBREAK action of WRITE AVE and BREAK before the third
execution of PRINT^TIME.
1 ZCOMPILE
ZCOMpile
The ZCOMPILE command invokes the GT.M compiler from within the GT.M
run-time environment.
Within GT.M itself, ZCOMPILE provides the functionality of the mumps
command, except for mumps -direct.
The format of the ZCOMPILE command is:
ZCOM[PILE][:tvexpr] expr[,...]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o The expression argument specifies one or more filenames, which must
include the .m extension. Wildcards are acceptable in the filename
specification. The filename specification can be optionally
prefixed by qualifiers valid for a mumps command.
The $ZCSTATUS intrinsic special variable holds the value of the status
code for the compilation performed by a ZCOMPILE command.
2 Ex_of_ZCOMpile
Examples of ZCOMPILE
ZCOMPILE "EXAMPLE.m"
This compiles EXAMPLE.m in the current working directory.
Example:
ZCOMPILE "-list A*.m"
This compiles all files starting with a [capital] A and an extension of
.m in the current working directory.
1 ZCONTINUE
ZContinue
The ZCONTINUE command continues routine execution after a BREAK command
or a <CTRL-C>.
The format of the ZCONTINUE command is:
ZC[ONTINUE][:tvexpr]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o Because ZCONTINUE changes the flow of execution away from control
of the principal device back to the current routine, it is usually
the final command on a line; however, if it is not, because the
ZCONTINUE has no argument, at least two (2) spaces must follow the
command to separate it from the next command on the line.
o If the process is not in Direct Mode, ZCONTINUE has no effect.
1 ZDEALLOCATE
ZDeallocate
The ZDEALLOCATE command releases a specified resource name or names
previously reserved by the ZALLOCATE command. The ZDEALLOCATE command
releases only the specified name(s) without releasing other names
previously reserved with the ZALLOCATE or LOCK command.
The ZDEALLOCATE command provides compatibility with some other GT.M
implementations. The M Development Committee choose to add the + and -
delimiters to the LOCK command rather than adopt the ZALLOCATE and
ZDEALLOCATE approach. Therefore, when a design requires an incremental
lock mechanism, LOCK +/- has the advantage of being part of the M
standard. LOCK +/- also has the advantage of working symmetrically when
routines using LOCKs are nested.
The format of the ZDEALLOCATE command is:
ZD[EALLOCATE][:tvexpr] [nref[,...]]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command
o The nref argument specifies a name in the format of a GT.M name
with or without subscripts and with or without a leading caret (^).
o A ZDEALLOCATE with no argument releases all names currently
reserved with ZALLOCATE by the process; in this case, at least two
(2) spaces must follow the ZDEALLOCATE to separate it from the next
command on the line.
o ZDEALLOCATEing a named resource that is not currently owned by the
process has no effect.
o An indirection operator and an expression atom evaluating to a list
of one or more ZDEALLOCATE arguments form a legal argument for a
ZDEALLOCATE.
1 ZEDIT
ZEDit
The ZEDIT command invokes the editor specified by the EDITOR
environment variable for GT.M and opens the specified file for editing.
If the EDITOR environment variable is undefined, ZEDIT tries to invoke
the UNIX vi editor.
By default, ZEDIT puts a new file into the first source directory in
$ZROUTINES. Previously, it used the current working directory. The old
behavior can be obtained by specifying the current working directory
explicitly in the argument to the ZEDIT command:
o ZEDIT "./file"
The format of the ZEDIT command is:
ZED[IT][:tvexpr] [expr[,...]]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o The optional expression(s) specifies the name of a file to edit;
note the argument is an expression rather than a routinename; ZEDIT
rejects arguments with a file extension of .o as illegal. A valid
GT.M file name with no extension will be given an extension of .m;
therefore it is not possible, through ZEDIT, to edit a file with a
valid GT.M filename and no extension.
o If ZEDIT has an argument, it not only invokes the editor, but also
sets $ZSOURCE=expr.
o If ZEDIT has no argument or expr="", the command acts as a ZEDIT
$ZSOURCE; at least two (2) spaces must follow a ZEDIT command with
no argument to separate it from the next command on the line.
o GT.M stores source code in files with standard operating system
format; generally the file name is the same as the GT.M routinename
with a default type of .m.
o An indirection operator and an expression atom evaluating to a list
of one or more ZEDIT arguments form a legal argument for a ZEDIT
If the expression includes a directory, ZEDIT searches only that
directory. If $ZROUTINES is not null, a ZEDIT command that does not
specify a directory uses $ZROUTINES to locate files. If $ZROUTINES is
null, ZEDIT edits a new file in the first source directory specified in
$ZROUTINES.
When the argument to a ZEDIT includes a file or path name, $ZSOURCE
maintains that as a default for ZEDIT and ZLINK.
2 Ex_of_ZEDit
Examples of ZEDIT
Example:
GTM>ZEDIT "BAL"
This invokes the editor for a file with a name of BAL and an extension
of .m. Notice that BAL is a string literal.
Example:
GTM>SET prog="BAL"
GTM>ZEDIT prog
This is similar to the first example except that it uses a variable
argument rather than a string literal.
Example:
GTM>zedit ".login"
This invokes the editor for a file with the name .login. Notice that in
this case the file is not a GT.M file, since .login starts with a
period, and therefore, cannot be a GT.M file.
1 ZGOTO
ZGoto
The ZGOTO command transfers control to various levels in the GT.M
invocation stack. It also can transfer control from one part of the
routine to another or from one routine to another using the specified
entryref.
The format of the ZGOTO command is:
ZG[OTO][:tvexpr] [[intexpr][:entryref
[:tvexpr]],...]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o The optional integer expression specifies the stack frame nesting
level reached by performing the ZGOTO.
o A ZGOTO with no argument returns control to the next command at the
bottom of the stack (level 1); in this case, at least two (2)
spaces must follow the command to separate it from the next command
on the line.
o The optional entryref specifies a location to which ZGOTO transfers
control.
o If ZGOTO specifies no entryref, it returns control to the next
command at the level specified by the integer expression.
o The optional truth-valued expression immediately following the
entryref specifies the argument postconditional and controls
whether GT.M uses the argument.
o If the ZGOTO includes the level and the argument postconditional
but not the entryref, two colons (::) separate the integer
expression from the truth-valued expression.
o An indirection operator and an expression atom evaluating to a list
of one or more ZGOTO arguments form a legal argument for a ZGOTO.
A ZGOTO command with an entryref performs a similar function to the
GOTO command, with the additional capability of reducing the GT.M stack
level. In a single operation, ZGOTO executes ($ZLEVEL - intexpr)
implicit QUITs and a GOTO operation, transferring control to the named
entryref.
The ZGOTO command leaves the invocation stack at the level specified by
the integer expression. GT.M implicitly terminates any intervening FOR
loops and unstacks variables stacked with NEW commands as appropriate.
Using ZGOTO results in an exit from the current GT.M invocation. ZGOTO
resembles HALT (and not QUIT) in that it causes an exit regardless of
the number of active levels in the current invocation. ZGOTO resembles
QUIT (and not HALT) in that it destroys the GT.M context and terminates
the process only if the current GT.M invocation is at the base of the
process. Understanding the difference between ZGOTO and HALT has an
impact only in an environment where GT.M is invoked recursively from
other languages.
ZGOTO $ZLEVEL:LABEL^ROUTINE produces identical results to GOTO
LABEL^ROUTINE. ZGOTO $ZLEVEL-1 responds like a QUIT (followed by
ZCONTINUE, if in Direct Mode). If the integer expression evaluates to a
value greater than the current value of $ZLEVEL or less than zero (0),
GT.M issues a run-time error.
If ZGOTO has no entryref, it performs some number of implicit QUITs and
transfers control to the next command at the specified level. If ZGOTO
has no argument, it behaves like ZGOTO 1, which resumes operation of
the lowest level GT.M routine as displayed by ZSHOW "S". In the image
invoked by $gtm_dist mumps -direct, a ZGOTO without arguments returns
the process to Direct Mode.
ZGOTO provides a useful debugging tool in Direct Mode. However, because
ZGOTO is not conducive to structured coding, it is best to restrict its
use in production programs to error handling.For more information on
error handling, refer to the "Error Processing" chapter in GT.M
Programmer's Guide.
2 Ex_of_ZGOTO
Examples of ZGOTO
Example:
GTM>ZGOTO
GTM>ZSHOW
+1^GTM$DMOD (Direct mode)
GTM>
This uses ZGOTO to clear all levels of the GT.M invocation stack. ZSHOW
with no arguments displays the stack.
Example:
SET $ZTRAP="ZGOTO "_$ZLEVEL_":^ERROR"
This SETs $ZTRAP to contain a ZGOTO, so if an error causes GT.M to
XECUTE $ZTRAP, the routine ERROR executes at the same level as the SET
command shown in the example.
1 ZHELP
ZHelp
The ZHELP command provides access to help information from the GTM help
library or from any help library specified in the command argument.
The format of the ZHELP command is:
ZH[ELP][:tvexpr] [expr1[:expr2],...]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o The optional first expression specifies the help topic.
o If ZHELP has no argument or expr1="", ZHELP invokes base level
help; at least two (2) spaces must follow a ZHELP command with no
argument to separate it from the next command on the line.
o The optional second expression specifies the name of a Global
Directory containing ^HELP.
o If ZHELP does not specify the second expression, the name of the
Global Directory defaults to $gtm_dist/gtmhelp.gld.
o An indirection operator and an expression atom evaluating to a list
of one or more ZHELP arguments form a legal argument for a ZHELP
2 Ex_of_ZHelp
Examples of ZHELP
Example:
GTM>zhelp "func $data"
This lists the help for function $DATA, which is a subtopic of
functions topic.
Example:
GTM>zhelp
This uses ZHELP to list all the keywords in the help library.
Example:
GTM>zhelp "ZSHOW"
This lists the help for command ZSHOW.
1 ZLINK
ZLink
If the current process does not contain a copy of a routine, the ZLINK
command adds an executable GT.M routine to the current process. If the
current process contains a copy of a routine and the routine is not
active, the ZLINK command replaces the current routine process with a
"new" version. If necessary, the ZLINK command compiles the routine
prior to integrating it with the process.
The format of the ZLINK command is:
ZL[INK][:tvexpr] [expr1[:expr2][,...]]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o The optional first expression specifies the pathname of a routine
to ZLINK; if ZLINK has an argument, it not only adds the routine to
the image, but also sets $ZSOURCE=expr.
o If ZLINK has no argument, or expr="", it uses value of $ZSOURCE as
the routine specification filename; at least two (2) spaces must
follow a ZLINK command with no argument to separate it from the
next command on the line.
o The optional second expression specifies a string holding MUMPS
command qualifiers delimited by a dash (-); the qualifiers control
compile options when the current ZLINK requires a compile; if ZLINK
omits the second expression, the command uses the $ZCOMPILE
intrinsic special variable to determine the compile qualifiers.
o An indirection operator and an expression atom evaluating to a list
of one or more ZLINK arguments form a legal argument for a ZLINK.
ZLINK cannot change a routine that GT.M is currently executing. An
attempt to ZLINK an active routine results in a run-time error because
changing a routine in progress could have unpredictable results. Before
ZLINKing the routine, use the ZSHOW command to display the currently
active routines, then remove it from the GT.M stack using ZGOTO, or the
appropriate number of QUITs.
When the ZLINK command specifies a file, GT.M sets $ZSOURCE to that
filename. By default, ZLINK and ZEDIT use $ZSOURCE for a filename when
they have a missing or null argument. A subsequent ZLINK without an
argument is equivalent to ZLINK $ZSOURCE.
In order to ensure compatibility with GT.M versions that do not
permit the percent sign (%) in a file name, use an underscore (_)
in place of the percent in the ZLINK file name for routines
beginning with a percent sign.
If the expression includes an explicit directory, ZLINK searches only
that directory. Otherwise, if $ZROUTINES is not null, a ZLINK command
uses $ZROUTINES to locate files. If $ZROUTINES is null, ZLINK uses the
current directory.
If the filename contains an explicit file extension, ZLINK processes
the file according to the extension, object (.o) or source (usually
.m). If the file name does not specify a file extension, ZLINK attempts
to find and match both the object and source for a routine.
2 ZLINK_Compilation
ZLINK Compilation
If ZLINK compiles a routine and the -OBJECT= qualifier does not
redirect the output, it places the resulting object file in the
directory indicated by the search criteria. ZLINK incorporates the new
object file into the image, regardless of its directory placement.
If the command does not specify compile qualifiers (with expr2) and
$ZCOMPILE is null, GT.M uses the default M command qualifiers, -ignore,
-labels=lower, -nolist, and -object. For more information on $ZCOMPILE,
refer to the appropriate section in the "Intrinsic Special Variables"
chapter in this manual.
For information on producing object files, but not adding them to the
current image, refer to ZCOMPILE.
2 Ex_of_ZLink
Examples of ZLINK
Example:
GTM>ZLINK "test"
If ZLINK finds test.m or test.o, it adds the routine test to the
current image. If ZLINK does not find test.o, or finds that test.o is
older than test.m, GT.M compiles test.m to produce a new test.o, and
adds the contents of the new object file to the image.
Example:
GTM>
zlink "test.m":"-noobject -list"
This compiles the routine "test" and produces a listing but no object
file. Because the example produces no object file, it does not change
the current image.
2 Auto_ZLink
Auto-ZLINK
If a GT.M routine refers to a routine that is not linked to the GT.M
image, GT.M automatically attempts to ZLINK that routine. An auto-ZLINK
is functionally equivalent to an explicit ZLINK of a routine without a
specified directory or file extension.
The following GT.M commands and functions can initiate auto-ZLINKing:
DO
GOTO
ZBREAK
ZGOTO
ZPRINT
$TEXT()
GT.M auto-ZLINKs the routine if the following conditions are met:
o ZLINK can locate and process the routine file, as indicated in the
previous ZLINK Operation Summary table
o The name of the routine is the same as the name of the source file;
the only exception is in cases where GT.M converts a leading
percent sign (%) in a file name to an underscore (_)
2 ZL_AutoZL_and_Rtn_Nam
ZLINK, Auto-ZLINK and Routine Names
In GT.M, the name of the source file determines the name of the GT.M
routine. The file name of the object file is not required to match the
name of the routine. Linking the object file makes the internal routine
name (derived from the source file) known to GT.M. This can lead to
potential confusion, however, since both ZLINK and auto-ZLINK use the
name of the object file to find the routine. When the object file name
differs from the name of the routine, auto-ZLINK generates a run-time
error.
1 ZKILL
ZKill
The ZKILL command KILLs the data value for a variable name without
affecting the nodes descended from that node.
The format of the ZKILL command is:
ZK[ILL][:tvexpr] glvn
The functionality of ZKILL is identical to ZWITHDRAW. For a
comprehensive description of the format and usage, refer to the entry
for ZWITHDRAW.
1 ZMESSAGE
ZMessage
The ZMESSAGE command signals a specified condition.
The format of the ZMESSAGE command is:
ZM[ESSAGE][:tvexpr] intexpr
[:expr...][,...]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o The required integer expression specifies the exception condition
to signal.
o The additional expressions specify one or more arguments passed to
the GT.M message formatter to substitute as parameters to the
message text. For example, if the message associated with the
condition contains a corresponding !AD substitution directive,
passing a string as an additional expression causes the string to
be inserted in the message text instead of the !AD. $ZMESSAGE
function returns the message text with the substitution directives
for a given message number.
2 Ex_of_ZMessage
Examples of ZMESSAGE
All of the following examples issue ZMESSAGE from Direct Mode where
exception conditions do not invoke $ZTRAP. ZMESSAGE allows you to feed
an undefined message number back into GT.M to try and determine the
message and/or mnemonic associated with it.
Example:
GTM>ZMESSAGE 2
%SYSTEM-E-ENO2, No such file or directory
This ZMESSAGE does not specify substitution text and the message does
not include any substitution directives.
Example:
GTM>ZMESSAGE 150372994
%GTM-E-GVUNDEF, Global Variable undefined:
The message specified by this ZMESSAGE command includes a substitution
directive but the command does not supply any text.
Example:
GTM>ZMESSAGE 150373850:"x"
%GTM-E-GVUNDEF, Undefined local variable: x
This ZMESSAGE command supplies the substitution text for the message.
GT.M treats odd-numbered conditions as "successful." GT.M handles
successful conditions by displaying the associated message and
continuing execution. GT.M treats even-numbered conditions as failures.
GT.M handles failure conditions by storing the error information in
$ZSTATUS and XECUTEing $ZTRAP or by terminating if $ZTRAP="". In Direct
Mode, GT.M only reports failure conditions to the principal device and
does not XECUTE $ZTRAP or set $ZSTATUS. For more information on error
handling, refer to the "Error Processing" chapter in GT.M Programmer's
Guide.
1 ZPRINT
ZPrint
The ZPRINT command displays source code lines selected by its argument.
The format of the ZPRINT command is:
ZP[RINT][:tvexpr][entryref
[:label[+intexpr]][,...]]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o A ZPRINT with no argument prints the entire current routine, which
is the routine closest to the top of an invocation stack, as
displayed by a ZSHOW "S"; in this case, at least two (2) spaces
must follow the command to separate it from the next command on the
line.
o The optional entryref specifies the location in a routine at which
to start printing; the entryref can include either a routinename or
a label plus a routinename in the format LABEL^ROUTINENAME or
LABEL+OFFSET^ROUTINENAME; if the entryref does not contain a
routinename, ZPRINT defaults to the current routine.
o The optional label following the entryref identifies a location at
which to stop printing; the optional integer expression specifies
an offset from the label; the label and offset together are
referred to as a lineref and this lineref identifies the last line
to print; if the offset is specified without the label, the offset
in the optional lineref is always counted from the beginning of the
routine, even when the entryref specifies a label.
o If the ZPRINT argument includes the colon (:) delimiter, then the
argument must also include at least one component of the optional
lineref.
o If the ZPRINT argument contains only the entryref, with no
components of the optional lineref and the entryref contains a
label or offset, ZPRINT displays only the one line that occurs at
that entryref.
o If the entryref contains only a routinename, ZPRINT displays the
entire routine.
o If the entryref contains only a routinename and the argument
includes the optional lineref, ZPRINT starts the display at the
beginning of the routine.
o If the optional lineref specifies a line prior to the lineref
specified within the entryref, ZPRINT does not display any lines.
o If the offset in the optional lineref specifies a line beyond the
end of the routine, ZPRINT displays the remainder of the routine.
o If ZPRINT cannot locate the routine or if either of the labels does
not appear in the routine, ZPRINT issues an error.
o An indirection operator and an expression atom evaluating to a list
of one or more ZPRINT arguments form a legal argument for a ZPRINT.
Note that the routinename may only appear before the colon (:)
delimiter. The integer expression offsets may be positive or negative,
but they must always be delimited by a plus sign (+).
2 Ex_of_ZPrint
Examples of ZPRINT
Example:
GTM>ZPRINT X^RTN
This example displays the line beginning with the label X in the
routine RTN.
Example:
GTM>ZPRINT X^RTN:X+5
GTM>ZPRINT X+-5^RTN:X
GTM>ZPRINT X^RTN:X+-5^RTN
The first line displays the line beginning with the label X and the
next 5 lines in routine RTN. The second line displays the 5 lines
preceding label X in the same routine and the line beginning with label
X. The third line generates a run-time error because the routine name
must appear only before the colon in the argument.
1 ZSHOW
ZSHow
The ZSHOW command displays information about the current GT.M
environment.
The format of the ZSHOW command is:
ZSH[OW][:tvexpr][expr[:glvn][,...]]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o The optional expression specifies one or more codes determining the
nature of the information displayed.
o A ZSHOW with no argument defaults to ZSHOW "S"; in this case, at
least two (2) spaces must follow the ZSHOW to separate it from the
next command on the line.
o The optional global or local variable name specifies the
destination for the ZSHOW output; if the ZSHOW argument does not
contain a global or local variable name, ZSHOW directs its display
to the current device ($IO).
o An indirection operator and an expression atom evaluating to a list
of one or more ZSHOW arguments form a legal argument for a ZSHOW.
2 ZSH_Info_Codes
ZSHOW Information Codes
A ZSHOW argument is an expression containing codes selecting one or
more types of information.
B displays active ZBREAK breakpoints
C displays available external call table entry names
D displays device information
I displays the current values of all intrinsic special variables
L displays GT.M LOCKs and ZALLOCATEs held by the process
S displays the GT.M invocation stack
V displays local variables
* displays all possible types of ZSHOW information
Codes may be upper- or lower-case. Invalid codes produce a run-time
error. Multiple occurrences of the same code in one ZSHOW argument only
produce one output instance of the corresponding information. The order
of the first appearance of the codes in the argument determines the
order of the corresponding output instances.
If you are using a local variable destination and place another
code ahead of "V", the effect is to have the results of the earlier
code also appear in the results of the "V" code.
If the wildcard (*) occurs in the list, ZSHOW uses the default order:
o intrinsic special variables
o local variables
o ZBREAK information
o device information
o LOCK and ZALLOCATE information
o the GT.M stack
2 Ex_of_ZSHow
Examples of ZSHOW
Example:
GTM>ZSHOW "db"
This command displays all devices with deviceparameters reflecting
their current characteristics followed by any current ZBREAK locations
with their corresponding actions.
Example:
GTM>ZSHOW "dbd"
This command displays the same output as the previous example.
Example:
GTM>ZSHOW "ax"
This command generates a run-time error.
Example:
LAB1 DO LAB2
QUIT
LAB2 DO LAB3
QUIT
LAB3 ZSHOW
QUIT
Produces the results:
LAB3^RTN
LAB2^RTN
LAB1^RTN
2 ZSH_Destination_Vars
ZSHOW Destination Variables
ZSHOW may specify an unsubscripted or subscripted global or local
variable name (glvn) into which ZSHOW places its output. If the
argument does not include a global or local variable name, ZSHOW
directs its output to the current device.
When ZSHOW directs its output to a variable, it adds two levels of
descendants to that variable. The first level subscript contains a
one-character string from the set of upper-case ZSHOW action codes,
identifying the type of information. ZSHOW implicitly KILLs all
descendants of the first level nodes. ZSHOW stores information elements
at the second level using ascending integers, starting at 1.
When a ZSHOW "V" directs its output to a local variable (lvn), the
result does not contain a copy of the descendants of the resulting "V"
node.
Example:
GTM>KILL SET b(1,"two")="test" ZSHOW "v":a ZWR
a("V",1)="b(1,""two"")=""test"""
b(1,"two")="test"
GTM>
This ZSHOW stores all local variables in the local variable a. Note
that ZSHOW does not replicate a("V") and a("V",1).
Example:
GTM>KILL SET a(1,"D",3,5)="stuff",a(1,"X",2)="",a(1)=1
GTM>zsh "d":a(1)
GTM>zwrite
a(1)=1
a(1,"D",1)="/dev/ttyp8 OPEN TERMINAL NOPAST NESCA
NOREADS TYPE WIDTH=80 LENG=52"
a(1,"X",2)=""
GTM>
This ZSHOW stores the current open device information under a(1).
Notice how the ZSHOW deletes a(1,"D",3,5).
Example:
GTM>KILL ^ZSHOW
GTM>ZB -*,lab^rout ZSH "B":^ZSHOW
GTM>ZWRITE ^ZSHOW
^ZSHOW("B",1)="LAB^ROUT"
GTM>
This ZSHOW stores the current ZBREAK information under the global
variable ^ZSHOW.
2 Use_of_ZSHow
Use of ZSHOW
Use ZSHOW as
o a debugging tool to display information on the environment.
o an error-handling tool to capture context information after an
unpredictable error with output directed to a sequential file or a
global.
o part of a context-switching mechanism in a server program that must
manage multiple contexts.
o a development tool to determine the external call table entries
available from the current process.
To prevent confusing data interactions, avoid directing ZSHOW output
into variables holding other kinds of information and directing ZSHOW
"V" output into local variables. For a comparison of ZSHOW "V" and
ZWRITE, refer to the ZWRITE section in the "Commands" chapter in GT.M
Programmer's Guide.
1 ZSTEP
ZSTep
The ZSTEP command provides the ability to control GT.M execution. When
a ZSTEP is issued from Direct Mode, execution continues to the
beginning of the next target line and then GT.M XECUTEs the ZSTEP
action. The keyword in the optional ZSTEP argument determines the class
of eligible target lines.
The format of the ZSTEP command is:
ZST[EP][:tvexpr] [keyword[:expr]][,...]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o The optional keyword specifies the nature of the step; the keywords
are INTO, OVER, and OUTOF.
o A ZSTEP with no argument performs the default action OVER; in this
case, at least two (2) spaces must follow the ZSTEP to separate it
from the next command on the line, which will be ignored.
o The optional expression specifies GT.M code to XECUTE when the
ZSTEP arrives at its destination.
o If the ZSTEP argument does not contain an expression argument,
ZSTEP defaults the action to the value of $ZSTEP, which defaults to
"BREAK."
The ZSTEP argument keywords are not expressions and ZSTEP does not
accept argument indirection.
In Direct Mode, ZSTEP performs an implicit ZCONTINUE and therefore GT.M
ignores all commands on the Direct Mode command line after the ZSTEP.
The keyword arguments define the class of lines where ZSTEP next pauses
execution to XECUTE the ZSTEP action. When a ZSTEP command has multiple
arguments, it ignores all arguments except the last.
2 ZSTEP_Into
ZSTEP Into
ZSTEP INTO pauses at the beginning of the next line, regardless of
transfers of control. When the ZSTEPed line invokes another routine or
a subroutine in the current routine, ZSTEP INTO pauses at the first
line of code associated with the new GT.M stack level.
2 ZSTEP_OUtof
ZSTEP OUtof
ZSTEP OUTOF pauses at the beginning of the next line executed after an
explicit or implicit QUIT from the current GT.M invocation stack level.
A ZSTEP OUTOF does not pause at lines associated with the current GT.M
stack level or with levels invoked from the current level.
2 ZSTEP_OVer
ZSTEP OVer
ZSTEP OVER pauses at the beginning of the next line in the code
associated with either the current GT.M stack level or a previous GT.M
stack level if the ZSTEPed line contains an explicit or implicit QUIT
from the current level. A ZSTEP OVER does not pause at lines invoked
from the current line by DOs, XECUTEs or extrinsics.
2 ZSTEP_Actions
ZSTEP Actions
The optional action parameter of a ZSTEP must contain an expression
evaluating to valid GT.M code. By default, ZSTEP uses the value of
$ZSTEP, which defaults to "B" ("BREAK"), and enters Direct Mode. When a
ZSTEP command specifies an action, the process does not enter Direct
Mode unless the action explicitly includes a BREAK command.
2 ZSTEP_Interact
ZSTEP Interactions
ZSTEP currently interacts with certain other elements in the GT.M
environment.
o If a <CTRL-C> or a CTRAP character arrives at certain points in
ZSTEP processing, there is a small chance GT.M may ignore the
<CTRL-C> or CTRAP; in a later release, <CTRL-C> and CTRAPs will
always have priority over ZSTEP.
o If GT.CM reports an asynchronous network error, a ZSTEP may cause
the network error to go unreported; the chance of such an
occurrence is small and the chance the error would subsequently be
reported is high; in a later release, network errors will always be
given priority over ZSTEP.
2 Use_of_ZSTEP
Use of ZSTEP
Use ZSTEP to incrementally execute a routine or series of routines.
Execute any GT.M command from Direct Mode at any ZSTEP pause. To resume
normal execution, use ZCONTINUE.
Note that ZSTEP arguments are keywords rather than expressions. They do
not allow indirection, and argument lists have no utility.
ZSTEP actions that include commands followed by a BREAK perform some
action before entering Direct Mode. ZSTEP actions that do not include a
BREAK perform the command action and continue execution. Use ZSTEP
actions that issue conditional BREAKs and subsequent ZSTEPs to do such
things as test for changes in the value of a variable.
2 Ex_of_ZSTEP
Examples of ZSTEP
Example:
GTM>ZSTEP INTO:"W ! ZP @
$ZPOS W !"
This ZSTEP resumes execution of the current routine. At the beginning
of the next line executed, the ZSTEP action ZPRINTs the source code for
that line. Because the specified action does not contain a BREAK
command, execution continues to the next line and all subsequent lines
in the program flow.
Example:
GTM>S curx=$g(x),zact="ZST:curx=$g(x) I:zact B:curx'=$g(x)"
GTM>ZSTEP INTO:zact
This sequence uses ZSTEP to invoke Direct Mode at the beginning of the
first line after the line that alters the value of x.
1 ZSYSTEM
ZSYstem
The ZSYSTEM command creates a child of the current process.
The format of the ZSYSTEM command is:
ZSY[STEM][:tvexpr] [expr[:tvexpr][,...]]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o The optional expression specifies the command passed to the shell;
after processing the command, the shell returns control to GT.M.
o If ZSYSTEM has no argument or expr="", the shell prompts for input
until provided with an exit command; at least two (2) spaces must
follow a ZSYSTEM command with no argument to separate it from the
next command on the line.
o The optional truth-valued expression following the argument
expression specifies the argument postconditional and controls
whether ZSYSTEM processes that argument.
o An indirection operator and an expression atom evaluating to a list
of one or more ZSYSTEM arguments form a legal argument for a
ZSYSTEM.
The ZSYSTEM command creates a new process and passes its argument to
the shell for execution. The new process executes in the same directory
as the initiating process using the shell specified by the SHELL
environment variable, or if that is not defined, the Bourne shell. The
new process has the same operating system environment, such as
environment variables and input/output devices, as the initiating
process. The initiating process pauses until the new process completes
before continuing execution. The return status of the forked process is
reflected in $ZSYSTEM.
If a ZSYSTEM command has multiple arguments, it starts a new process
for each argument, one at a time. ZSYSTEM waits for one process to
complete before starting the next one.
A ZSYSTEM with a null argument creates a shell with the standard input
and output devices. When the shell exits, control is returned to GT.M.
For an interactive process, both stdin and stdout are generally the
user's terminal. A ZSYSTEM with no arguments is equivalent to a ZSYSTEM
with a single null string argument.
If a command postconditional is false, GT.M does not process the
ZSYSTEM command. If an argument postconditional is false, GT.M does not
process that argument.
Issuing a ZSYSTEM command inside a transaction destroys the Isolation
of that transaction. Because of the way that GT.M implements
transaction processing, a ZSYSTEM within a transaction may suffer an
indefinite number of restarts ("live lock").
2 Ex_of_ZSYSTEM
Examples of ZSYstem
Example:
GTM>ZSYSTEM "ls *.m"
This uses ZSYSTEM to fork a process that then performs the ls command
with *.m as an argument to ls. Once the command completes, the forked
process terminates.
Example:
GTM>ZSYSTEM
$
This ZSYSTEM has no argument so the forked process prompts for input.
1 ZTCOMMIT
ZTCommit
The ZTCOMMIT command marks the end of a logical transaction within a
GT.M program. ZTCOMMIT used with ZTSTART "fences" transactions (that
is, marks the end and beginning). Fencing transactions allows the MUPIP
JOURNAL facility to prevent incomplete application transactions
consisting of multiple global updates from affecting the database
during a database recovery.
The format of the ZTCOMMIT command is:
ZTC[OMMIT][:tvexpr] [intexpr]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o The optional integer expression specifies the number of currently
open ZTSTARTs for the ZTCOMMIT to close.
o A ZTCOMMIT with no argument closes one ZTSTART; in this case, at
least two (2) spaces must follow the command to separate it from
the next command on the line; with an argument of 0, ZTCOMMIT
closes all open ZTSTARTs.
o An indirection operator and an expression atom evaluating to a list
of one or more ZTCOMMIT arguments form a legal argument for a
ZTCOMMIT.
When an application requires sub-transactions, it may nest ZTSTARTs and
ZTCOMMITs to a maximum depth of 255. However, a ZTCOMMIT must "close"
the outer-most ZTSTART before journaling accepts any part of the
"transaction" as complete.
2 Ex_of_ZTCommit
Examples of ZTCOMMIT
Example:
GTM>ZTCOMMIT 0
This ZTCOMMIT issued from Direct Mode would close any open ZTSTARTs.
Example:
1 ZTSTART
ZTStart
The ZTSTART command marks the beginning of a logical transaction within
a GT.M program. ZTSTART and ZTCOMMIT "fence" transactions (that is,
mark the beginning and end). Fenced transactions prevent the MUPIP
JOURNAL facility from recovering incomplete transactions. All ZTSTARTs
must be matched with ZTCOMMITs before the journal processing facility
recognizes the transaction as complete.
The format of the ZTSTART command is:
ZTS[TART][:tvexpr]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o Because ZTSTART has no argument, at least two (2) spaces must
follow the command to separate it from the next command on the
line.
For more information on Journaling and transaction fencing, refer to
the section on ZTCOMMIT and the "GT.M Journaling" chapter in the GT.M
Administration and Operations Guide.
2 Ex_of_ZTStart
Examples of ZTSTART
Example:
LOCK ^P(t)
ZTSTART
SET ^P(t)=prec,^($H)=$G(^P(t,+$H))+1,^(+$H,s)=hrec
ZTCOMMIT
LOCK
This uses a LOCK on ^P(t) to serialize the transaction. The logical
transaction consists of three global sets that are enclosed within a
ZTSTART and a ZTCOMMIT.
Example:
BASE DO WORK
QUIT
GRP LOCK ^FAM(prn)
SET b=^FAM(prn)
ZTSTART
FOR i=1:1:$L(b,"|") D GET,WORK
ZTCOMMIT
LOCK
QUIT
WORK LOCK +^ACT(acct)
ZTSTART
SET ^ACT(acct)=actrec
SET ^ACTX(lname,fname,acct)=""
ZTCOMMIT
LOCK -^ACT(acct)
This has a sub-routine WORK, which BASE invokes directly and GRP
invokes to perform a sub-transaction.
1 ZWITHDRAW
ZWIthdraw
The ZWITHDRAW command KILLs the data value for a variable name without
affecting the nodes descended from that node.
The format of the ZWITHDRAW command is:
ZWI[THDRAW][:tvexpr] glvn
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o The global or local variable name identifies the variable for which
ZWITHDRAW removes the data value.
o An indirection operator and an expression atom evaluating to a list
of one or more ZWITHDRAW arguments form a legal argument for a
ZWITHDRAW.
ZWITHDRAW provides a tool to quickly restore a node to a state where it
has descendants and no value-that is, where $DATA for that node will
have a value of 10-for the case where such a state has some control
meaning. GT.M also provides the ZKILL command, with functionality
identical to ZWITHDRAW.
2 Ex_of_ZWIthdraw
Examples of ZWITHDRAW
Example:
KILL A
SET A="A",A(1)=1,A(1,1)=1
WRITE $D(A(1)),!
ZWITHDRAW A(1)
WRITE $D(A(1)),!
ZWRITE A
QUIT
produces the result:
11
10
A="A"
A(1,1)=1
This sets up local variables A and A(1) and A(1,1). It then deletes the
data for A(1) with ZWITHDRAW. The ZWRITE command shows ZWITHDRAW KILLed
A(1) but left A and A(1,1).
1 ZWRITE
ZWRite
The ZWRITE command displays the current value of one or more local or
global variables. ZWRITE formats its output so that each item in the
display forms a valid argument to a SET @ command. This means ZWRITE
encloses string values in quotes and represents non-graphic (control)
characters in $CHAR() syntax.
The format of the ZWRITE command is:
ZWR[ITE][:tvexpr] [zwrglvn[,...]]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o The optional global or local variable name specifies the variable
for ZWRITE to display.
o ZWRITE accepts several alternative syntaxes in place of subscripts;
ZWRITE also accepts arguments specifying naked references to
globals. Because ZWRITE is primarily a debugging tool, ZWRITE does
not affect the naked indicator.
o ZWRITE accepts null subscripts in its arguments, when these are
allowed, and reports array nodes that have null subscripts.
o A ZWRITE with no arguments displays all the currently available
local variables; in this case, at least two (2) spaces must follow
the command to separate it from the next command on the line.
o If the global or local variable name is unsubscripted, ZWRITE
displays the unsubscripted variable and all subscripted
descendants.
o If an asterisk (*) appears in the space normally occupied by the
last subscript in a subscripted variable name, ZWRITE displays all
variable nodes descended from the previously specified subscripts.
o ZWRITE accepts GT.M pattern-match syntax in place of both variable
names and subscripts.
o ZWRITE <name>(), where <name> is a local or a global is treated as
a synonym for ZWRITE <name>.
o A colon acts as a range operator for subscript values; ZWRITE
displays all subscripts of the variable starting with the value on
the left side of the colon and ending with the value on the right
side of the colon; if the range delimiter has no left-hand value,
or has the empty string as the left-hand value, the display begins
at the first subscript; if the range delimiter has no right-hand
value or has the empty string as the right-hand value, the display
ends at the last subscript at that level; if the range delimiter
has no values or empty strings on either side, ZWRITE displays all
subscripts at that level; an empty subscript level also displays
all subscripts at that level.
o An indirection operator and an expression atom evaluating to a list
of one or more ZWRITE arguments form a legal argument for a ZWRITE.
o Long ZWRITE format records can be loaded.
2 Ex_of_ZWRite
Examples of ZWRITE
Example:
GTM>ZWRITE ^?1"%"2U(0:":",)
This command displays the descendants of all subscripts between 0 and
":" of all global names starting with a "%" and having two upper case
letters-for example, "%AB".
Example:
GTM>ZWRITE A(,:,3)
This command displays all of the third level nodes with a subscript of
3 for local variable A.
Example:
ZWRITE ?1"A".E(?1"X"3N)
This would display data for any local variables starting with "A",
optionally followed by any characters, and having any subscripts
starting with "X" followed by three numerics.
1 Functions
Functions
M Intrinsic Functions start with a single dollar sign ($) and have one
or more arguments enclosed in parentheses () and separated by commas
(,). These functions provide expression results by performing actions
that are impossible or difficult to perform using M commands.
2 $ASCII()
$ASCII()
The $ASCII function returns the integer ASCII code for a character in a
string.
The format for the $ASCII function is:
$A[SCII](expr[,intexpr])
o The expression acts as the source string from which $ASCII()
extracts the character it decodes.
o The optional integer expression contains the position within the
expression of the character that $ASCII() decodes. If this argument
is missing, $ASCII() returns a result based on the first character
position. $ASCII() starts numbering character positions at one (1),
(i.e., the first character of a string is at position one (1)).
o If the explicit or implicit position is before the beginning or
after the end of the expression, $ASCII() returns a value of
negative one (-1).
$ASCII() provides a means of examining non-graphic characters in a
string. Used with $CHAR(), $ASCII() also provides a means to perform
arithmetic operations on the codes associated with characters.
3 Ex_of_$ASCII()
Examples of $ASCII()
Example:
GTM> FOR i=0:1:3 WRITE !,$A("HI",i)
-1
72
73
-1
GTM>
This loop displays the result of $ASCII() specifying a character
position before, first and second positions, and after the string.
2 $Char()
$CHAR()
The $CHAR function returns a string of one or more characters
corresponding to integer ASCII codes specified in its argument(s).
The format for the $CHAR function is:
$C[HAR](intexpr[,...])
o The integer expression(s) specify the ASCII codes of the
character(s) $CHAR() returns.
The M standard does not restrict the number of arguments to $CHAR().
However, GT.M does limit the number of arguments to a maximum of 254.
$CHAR() provides a means of producing non-graphic characters, as such
characters cannot appear directly within an M string literal. Used with
$ASCII(), $CHAR() can also perform arithmetic operations on the codes
associated with characters.
3 Ex_of_$CHAR()
Examples of $CHAR()
Example:
GTM> WRITE $CHAR(77,85,77,80,83,7)
MUMPS
GTM>
This example uses $CHAR() to WRITE the word MUMPS and signal the
terminal "bell."
Example:
SET nam=$E(nam,1,$L(nam)-1)_$C($A(nam,$L(nam))-1))
This example uses $CHAR() and $ASCII() to set the variable nam to a
value that immediately precedes its previous value in the set of
strings of the same length as nam.
2 $Data()
$Data()
The $DATA function returns an integer code describing the value and
descendent status of a local or global variable.
The format for the $DATA function is:
$D[ATA](glvn)
o The subscripted or unsubscripted global or local variable name
specifies the target node.
o If the variable is undefined, $DATA() returns 0.
o If the variable has a value but no descendants, $DATA() returns 1.
o If the variable has descendants but no value, $DATA() returns 10.
o If the variable has a value and descendants, $DATA() returns 11.
3 Ex_of_$Data()
Examples of $DATA()
Example:
GTM> KILL WRITE $DATA(a)
0
GTM> SET a(1)=1 WRITE $DATA(a(1))
1
GTM> WRITE $DATA(a)
10
GTM> SET a=0 WRITE $DATA(a)
11
GTM>
This uses $DATA to display all possible $DATA() results.
Example:
L ^ACCT(0)
I '$D(^ACCT(0)) S ^ACCT(0)=0
S (ACCT,^ACCT(0))=^ACCT(0)+1
L
This uses $DATA() to determine whether a global node requires
initialization.
Example:
FOR SET cus=$O(^cus(cus)) Q:cus="" I $D(^(cus))>1 D WORK
This uses $DATA() to determine whether a global node has descendants
and requires additional processing.
2 $Extract()
$EXTRACT()
The $EXTRACT function returns a substring of a given string.
The format for the $EXTRACT function is:
$E[XTRACT](expr[,intexpr1[,intexpr2]])
o The expression specifies a string from which $EXTRACT() derives a
substring.
o The first optional integer expression (second argument) specifies
the starting character position in the string expr of the substring
result. If the starting position is beyond the end of the
expression, $EXTRACT() returns the null string. If the starting
position is zero (0) or negative, $EXTRACT() starts at the first
position in the expression; if this argument is omitted, $EXTRACT()
returns the first character of the expression. $EXTRACT() numbers
character positions starting at one (1) (i.e., the first character
of a string is at position one (1)).
o The second optional integer expression (third argument) specifies
the ending character position for the result. If the ending
position is beyond the end of the expression, $EXTRACT() stops with
the last character of the expression. If the ending position
precedes the starting position, $EXTRACT() returns the null string.
If this argument is omitted, $EXTRACT() returns one character at
most.
$EXTRACT() provides a tool for manipulating strings based on character
positions.
A SET command argument can have something that has the format of a
$EXTRACT() on the left-hand side of its equal sign (=). This construct
permits easy maintenance of individual pieces within a string. It can
also be used to right justify a value padded with blank characters. For
more information on SET $EXTRACT(), refer to SET in the "Commands"
chapter.
3 Ex_of_$Extract()
Examples of $EXTRACT()
Example:
GTM> FOR i=0:1:3 WRITE !,$EXTRACT("HI",i),"<"
<
H<
I<
<
GTM>
This loop displays the result of $EXTRACT(), specifying no ending
character position and a beginning character position "before, " first
and second positions, and "after" the string.
Example:
GTM> FOR i=0:1:3 WRITE !,$E("HI",1,i),"<"
<
H<
HI<
HI<
GTM>
This loop displays the result of $EXTRACT() specifying a beginning
character position of 1 and an ending character position "before, "
first and second positions, and "after" the string.
Example:
TRIM(x)
NEW i,j
FOR j=$L(x):-1:0 S nx=$E(x,1,j) Q:$EXTRACT(x,j)'=" "
FOR i=1:1:j S fx=$E(nx,i,$L(x)) Q:$EXTRACT(x,i)'=" "
QUIT fx
GTM>SET str=" MUMPS "
GTM>WRITE $LENGTH(str)
7
GTM>WRITE $LENGTH($$TRIM^trim(str))
5
This extrinsic function uses $EXTRACT() to remove extra leading and
trailing spaces from its argument.
2 $Find()
$FIND()
The $FIND function returns an integer character position that locates
the occurrence of a substring within a string.
The format for the $FIND function is:
$F[IND](expr1,expr2[,intexpr])
o The first expression specifies the string in which $FIND() searches
for the substring.
o The second expression specifies the substring for which $FIND()
searches.
o The optional integer expression identifies the starting position
for the $FIND() search. If this argument is missing, zero (0), or
negative, $FIND() begins its search in the first position of the
string.
o If $FIND() locates the substring, it returns the position after the
last character of the substring. If the end of the substring
coincides with the end of the string (expr1), it returns an integer
equal to the length of the string plus one ($L(expr1)+1).
o If $FIND() does not locate the substring, it returns zero (0).
$FIND() provides a tool to locate characters. The ( [ ) operator and
the two-argument $LENGTH() are other tools that provide related
functionality.
3 Ex_of_$Find()
Examples of $FIND()
Example:
GTM> WRITE $FIND("HIFI","I")
3
GTM>
This example uses $FIND() to WRITE the position of the first occurrence
of the character "I." The return of 3 gives the position after the
"found" substring.
Example:
GTM> WRITE $FIND("HIFI","I",3)
5
GTM>
This example uses $FIND() to WRITE the position of the next occurrence
of the character "I" starting in character position three.
Example:
GTM> SET t=1 FOR SET t=$FIND("BANANA","AN",t) Q:'t W !,t
4
6
GTM>
This example uses a loop with $FIND() to locate all occurrences of "AN"
in "BANANA". The $FIND() returns 4 and 6 giving the positions after the
two occurrences of "AN".
Example:
GTM> SET str="MUMPS databases are hierarchical"
GTM>WRITE $FIND(str," ")
7
GTM>WRITE $FIND(str,"Z")
0
GTM>WRITE $FIND(str,"d",1)
8
GTM>WRITE $FIND(str,"d",10)
0
The above example searches a string for a sub string, and returns an
integer value which corresponds to the next character position after
locating the sub string.
2 $FNumber()
$FNumber()
The $FNUMBER function returns a string containing a formatted number.
The format for the $FNUMBER function is:
$FN[UMBER](numexpr,expr[,intexpr])
o The numeric expression specifies the number that $FNUMBER()
formats.
o The expression (second argument) specifies zero or more single
character format control codes; if the expression contains any
character other than the defined codes, $FNUMBER() generates a
run-time error.
o The optional integer expression (third argument) specifies the
number of digits after the decimal point. If the numeric expression
has more digits than specified by this argument, $FNUMBER() rounds
to obtain the result. If the numeric expression has fewer digits
than specified by this argument, $FNUMBER() zero-fills to obtain
the result.
o When the optional third argument is specified and the first
argument evaluates to a fraction between -1 and 1, $FNUMBER()
returns a number with a leading zero (0) before the decimal point
(.).
$FNUMBER() formats or edits numbers, usually for reporting. For more
information on rounding performed by $FNUMBER(), refer to the section
on $JUSTIFY().
The formatting codes are:
+ Forces a "+" on positive values.
- Suppresses the "-" on negative values.
, Inserts commas every third position to the left of the decimal
within the number.
T Represents the number with a trailing, rather than a leading
sign; positive numbers have a trailing space unless the expression
includes a plus sign (+).
P Represents negative values in parentheses, positive values with a
space on either side; combining with any other code except comma
(,) causes a run-time error.
M accepts both lower-case and upper-case alphabetic codes. The order of
the codes does not affect the result.
3 Ex_of_$FNumber()
Examples of $FNUMBER()
Example:
SET X=-100000,Y=2000
WRITE "SUPPRESS NEGATIVE SIGN:",?35,$FNUMBER(X,"-"),!
WRITE "TRAILING SIGN:",?35,$FNUMBER(X,"T"),!
WRITE "NEGATIVE NUMBERS IN ():",?35,$FNUMBER(X,"P"),!
WRITE "COMMAS IN NUMBER:",?35,$FNUMBER(X,","),!
WRITE "NUMBER WITH FRACTION:",?35,$FNUMBER(X,"",2),!
WRITE "FORCE + SIGN IF POSITIVE:",?35,$FNUMBER(Y,"+"),!
Produces the results:
SUPPRESS NEGATIVE SIGN: 100000
TRAILING SIGN: 100000-
NEGATIVE NUMBERS IN (): (100000)
COMMAS IN NUMBER: -100,000
NUMBER WITH FRACTION: -100000.00
FORCE + SIGN IF POSITIVE: +2000
Example:
SET x=$FNUMBER(x,"-")
This example uses $FNUMBER() to SET x equal to its absolute value.
2 $Get()
$Get()
The $GET function returns the value of a local or global variable if
the variable has a value. If the variable has no value, the function
returns a value specified by an optional second argument, and otherwise
returns a null string.
The format for the $GET function is:
$G[ET](glvn[,expr])
o The subscripted or unsubscripted global or local variable name
specifies the node for which $GET() returns a value.
o If the global or local variable has a data value, $GET() returns
the value of the variable.
o If the global or local variable has no data value, $GET() returns
the value of the optional expression (second argument), or a null
string if the expression is not specified.
M defines $GET(x,y) as equivalent to:
$SELECT($DATA(x)[0:y,1:x)
and $GET(x) as equivalent to:
$GET(x,"")
$GET() provides a tool to eliminate separate initialization of
variables. This technique may provide performance benefits when used to
increase the density of a sparse global array by eliminating nodes that
would otherwise hold absent optional information. On the other hand,
some uses of one argument $GET() can mask logic problems.
GT.M has a "NOUNDEF" mode of operation, which treats all variable
references as if they were arguments to a one argument $GET(). The VIEW
command controls "NOUNDEF" mode.
3 Ex_of_$Get()
Examples of $GET()
Example:
I '$D(^PNT(NAME,TSTR)) S STATUS="NEW TEST"
E I ^PNT(NAME,TSTR)="" S STATUS="WAITING FOR RESULT"
E S STATUS=^PNT(NAME ,TSTR)
This example can be reduced to two lines of code by using $GET(), shown
in the following example. However, by using $GET() in its one-argument
form, the distinction between an undefined variable and one with a null
value is lost:
S STATUS=$G(^PNT(NAME,TSTR))
I STATUS="" S STATUS="WAITING FOR RESULT"
This is solved by using the two-argument form of $GET():
S STATUS=$G(^PNT(NAME,TSTR),"NEW TEST")
I STATUS="" S STATUS="WAITING FOR RESULT"
2 $Justify()
$Justify()
The $JUSTIFY function returns a formatted string.
The format for the $JUSTIFY function is:
$J[USTIFY](expr,intexpr1[,intexpr2])
o The expression specifies the string formatted by $JUSTIFY().
o The first integer expression (second argument) specifies the
minimum size of the resulting string. If the first integer
expression is larger than the length of the expression, $JUSTIFY()
right justifies the expression to a string of the specified length
by adding leading spaces. Otherwise, $JUSTIFY() returns the
expression unmodified unless specified by the second integer
argument.
o The optional second integer expression (third argument) specifies
the number of digits to follow the decimal point in the result, and
forces $JUSTIFY() to evaluate the expression as numeric. If the
numeric expression has more digits than this argument specifies,
$JUSTIFY() rounds to obtain the result. If the expression had fewer
digits than this argument specifies, $JUSTIFY() zero-fills to
obtain the result.
o When the second argument is specified and the first argument
evaluates to a fraction between -1 and 1, $JUSTIFY() returns a
number with a leading zero (0) before the decimal point (.).
$JUSTIFY() fills expressions to create fixed length values. However, if
the length of the specified expression exceeds the specified field
size, $JUSTIFY() does not truncate the result (although it may still
round based on the third argument). When required, $EXTRACT() performs
truncation.
$JUSTIFY() optionally rounds the portion of the result after the
decimal point. In the absence of the third argument, $JUSTIFY() does
not restrict the evaluation of the expression. In the presence of the
third (rounding) argument, $JUSTIFY() evaluates the expression as a
numeric value. The rounding algorithm can be understood as follows:
o If necessary, the rounding algorithm extends the expression to the
right with 0s (zeros) to have at least one more digit than
specified by the rounding argument.
o Then, it adds 5 (five) to the digit position after the digit
specified by the rounding argument.
o Finally, it truncates the result to the specified number of digits.
The algorithm rounds up when excess digits specify a half or more
of the last retained digit and rounds down when they specify less
than a half.
3 Ex_of_$Justify()
Examples of $JUSTIFY()
Example:
GTM> WRITE $JUSTIFY("HELLO",10),!,$JUSTIFY("GOODBYE",5)
HELLO
GOODBYE
GTM>
This uses $JUSTIFY() to display "HELLO" in a field of 10 spaces and
"GOODBYE" in a field of 5 spaces. Because the length of "GOODBYE"
exceeds five spaces, the result overflows the specification.
Example:
GTM> WRITE "1234567890",!,$JUSTIFY(10.545,10,2)
1234567890
10.55
GTM>
This uses $JUSTIFY() to WRITE a rounded value right justified in a
field of 10 spaces. Notice that the result has been rounded up.
Example:
GTM> WRITE "1234567890",!,$JUSTIFY(10.544,10,2)
1234567890
10.54
GTM>
Again, this uses $JUSTIFY() to WRITE a rounded value right justified in
a field of 10 spaces. Notice that the result has been rounded down.
Example:
GTM> WRITE "1234567890",!,$JUSTIFY(10.5,10,2)
1234567890
10.50
GTM>
Once again, this uses $JUSTIFY() to WRITE a rounded value right
justified in a field of 10 spaces. Notice that the result has been
zero-filled to 2 places.
Example:
GTM> WRITE $JUSTIFY(.34,0,2)
0.34
GTM>
This example uses $JUSTIFY to ensure that the fraction has a leading
zero. Note the use of a second argument of zero in the case that
rounding is the only function that $JUSTIFY is to perform.
2 $Length()
$Length()
The $LENGTH function returns the length of a string measured in
characters, or in "pieces" separated by a delimiter specified by one of
its arguments.
The format for the $LENGTH function is:
$L[ENGTH](expr1[,expr2])
o The first expression specifies the string that $LENGTH()
"measures."
o The optional second expression specifies the delimiter that defines
the measure; if this argument is missing, $LENGTH() returns the
number of characters in the string.
o If the second argument is present and not a null string, $LENGTH
returns one more than the count of the number of occurrences of the
second string in the first string; if the second argument is a null
string, the M standard specifies that $LENGTH() returns a zero (0).
$LENGTH() provides a tool for determining the lengths of strings in two
ways, characters and pieces. The two argument $LENGTH() returns the
number of existing pieces, while the one argument returns the number of
characters.
3 Ex_of_$Length()
Examples of $LENGTH()
Example:
GTM> WRITE $LENGTH("KINGSTON")
8
GTM>
This uses $LENGTH() to WRITE the length in characters of the string
"KINGSTON".
Example:
GTM> SET x="Smith/John/M/124 Main Street/Ourtown/KA/USA"
GTM> WRITE $LENGTH(x,"/")
7
GTM>
This uses $LENGTH() to WRITE the number of pieces in a string, as
delimited by /.
Example:
GTM> WRITE $LENGTH("/2/3/","/")
4
GTM>
This also uses $LENGTH() to WRITE the number of pieces in a string, as
delimited by /. Notice that GT.M. adds one count to the final number of
pieces (in this case 3), in the string (displays 4).
2 $NAme()
$NAme()
The $NAME function returns an evaluated representation of some or all
of a local or global variable name.
The format for the $NAME function is:
$NA[ME](glvn[,intexpr])
o The subscripted or unsubscripted global or local variable name,
including naked references, specifies the name for which $NAME()
returns an evaluated representation.
o The optional integer expression (second argument) specifies the
maximum number of subscript levels in the representation. If the
integer expression is not provided or exceeds the actual number of
subscript levels, $NAME() returns a representation of the whole
name. If the integer expression is zero (0), $NAME() returns only
the name. A negative integer expression produces a run-time error.
3 Ex_of_$Name()
Examples of $NAME()
Example:
GTM> SET X="A""B",^Y(1,X,"B",4)=""
GTM> WRITE $NAME(^(3),3)
^Y(1,"A""B","B")
GTM>
This example sets up a naked reference and then uses $NAME() to display
the first three levels of that four-level reference.
Example:
GTM> WRITE $NAME(^(3),0)
^Y
GTM>
This example shows the name level for the same naked reference.
2 $Next()
$Next()
The $NEXT function returns the next subscripted local or global
variable name in collation sequence within the array level specified by
its argument.
$NEXT() has been replaced by $ORDER(). $NEXT has been retained in the
current standard only for compatibility with earlier versions of the
standard. $NEXT() is similar to $ORDER(). However, $NEXT() has the
deficiency that when it encounters negative one (-1) as a subscript, it
returns the same result as when it finds no other data at the level.
This deficiency is particularly disruptive because it occurs in the
middle of the M collating sequence.
As $NEXT() has been removed from the standard in the MDC, you
should use $ORDER.
The format for the $NEXT function is:
$N[EXT](glvn)
o The subscripted global or local variable name specifies the node
following which $NEXT() searches for the next node with data and/or
descendants; the number of subscripts contained in the argument
implicitly defines the array level.
o If $NEXT() finds no node at the specified level after the specified
global or local variable, it returns negative one (-1).
o If the last subscript in a subscripted global or local variable
name is null or negative one (-1), $NEXT() returns the first node
at the specified level.
2 $Order()
$Order()
The $ORDER function returns the subscript of the next or prior local or
global variable name in collation sequence within the array level
specified by its first argument. In doing so, it moves in the direction
specified by the second argument. In GT.M, when $ORDER() has an
unsubscripted argument, it returns the next or previous unsubscripted
local or global variable name in collating sequence.
The format for the $ORDER function is:
$O[RDER](glvn[,expr])
o The subscripted global or local variable name specifies the node
from which $ORDER() searches for the next or previous node that has
data and/or descendants. The number of subscripts contained in the
argument implicitly defines the array level.
o The optional expression (second argument) specifies the direction
for the $ORDER(); 1 specifies forward operation and -1 specifies
reverse operation. Any other values for the expression will cause
an error.
o GT.M extends the M standard to allow unsubscripted names. In this
case, $ORDER() returns the next or previous unsubscripted name.
o If $ORDER() finds no node (or name) at the specified level after
(or before) the specified global or local variable, it returns a
null string (" ").
o If the last subscript in the subscripted global or local variable
name is null, $ORDER() returns the first (or last) node at the
specified level.
$ORDER() provides a tool for retrieving data from M sparse arrays in an
ordered fashion, independent of the order in which it was entered. In
M, routines generally sort by SETting data into an array with
appropriate subscripts and then retrieving the information with
$ORDER().
$ORDER() returns subscripts, not data values, and does not discriminate
between nodes that have data values and nodes that have descendants.
Once $ORDER() provides the subscript, the routine must use the
subscript to access the data value, if appropriate. Using $ORDER()
maintains the naked reference indicator, even if $ORDER() returns a
null.
GT.M optionally permits the use of null subscripts. This feature is
enabled via the VIEW command for local variables and a REGION qualifier
in GDE for global variables. When an application uses null subscripts,
they are "invisible" in a $ORDER() loop so the application must test
for them as a special case, perhaps using $DATA().
3 Ex_of_$Order()
Examples of $ORDER()
Example:
GTM>K S (a(1),a(2000),a("CAT"),a("cat"),a("ALF"), a(12))=1
GTM>S x="" F S x=$O(a(x)) Q:x="" W !,x
1
12
2000
ALF
CAT
cat
GTM>K a("CAT") SET a(5,10)="woolworths",a("cat")="last"
GTM> S x="" F S x=$O(a(x),-1) Q:x="" W !,x
cat
ALF
2000
12
5
1
GTM>
This example uses a $ORDER() loop to display all the subscripts at the
first level of local variable a, make some changes in a, and then
display all the subscripts in reverse order. Notice that $ORDER()
returns only the existing subscripts in the sparse array and returns
them in M collation sequence, regardless of the order in which they
were entered. Also, $ORDER() does not differentiate between node A(5),
which has only descendants (no data value), and the other nodes, which
have data values.
Example:
GTM>k s (%(1),tiva(2),A(3),tiv(4),Q(5),%a(6))=""
GTM>s x="%"
GTM>w:$d(@x) !,x f s x=$order(@x) q:x="" w !,x
%
%a
A
Q
tiv
tiva
x
GTM>s x="zzzzzzzz"
GTM>w:$d(@x) !,x f s x=$order(@x,-1) q:x="" w !,x
x
tiva
tiv
Q
A
%a
%
GTM>
This loop uses $ORDER() to display the current local variable names in
both forward and reverse order. Notice that the first ([^]%) and last
([^]zzzzzzzz) names require handling as special cases and require a
$DATA() function.
Example:
SET acct="",cntt=""
FOR SET acct=$OREDER(^acct(acct)) QUIT:acct="" DO
. F SET cntt=$ORDER(^acct(acct,cntt)) DO WORK
QUIT
This uses two nested $ORDER() loops to cycle through the ^acct global
array and perform some action for each second level node.
2 $Piece()
$Piece()
The $PIECE function returns a substring delimited by a specified string
delimiter made up of one or more characters. In M, $PIECE() returns a
logical field from a logical record.
The format for the $PIECE function is:
$P[IECE](expr1,expr2[,intexpr1[,intexpr2]])
o The first expression specifies the string from which $PIECE() takes
its result.
o The second expression specifies the delimiting string that
determines the piece "boundaries"; if this argument is a null
string, $PIECE() returns a null string.
o If the second expression does not appear anywhere in the first
expression, $PIECE() returns the entire first expression (unless
forced to return a null string by the second integer expression).
o The optional first integer expression (third argument) specifies
the beginning piece to return; if this argument is missing,
$PIECE() returns the first piece.
o The optional second integer expression (fourth argument) specifies
the last piece to return. If this argument is missing, $PIECE()
returns only one piece unless the first integer expression is zero
(0) or negative, in which case it returns a null string. If this
argument is less than the first integer expression, $PIECE()
returns a null string.
o If the second integer expression exceeds the actual number of
pieces in the first expression, $PIECE() returns all of the
expression after the delimiter selected by the first integer
expression.
o The $PIECE() result never includes the "outside" delimiters;
however, when the second integer argument specifies multiple
pieces, the result contains the "inside" occurrences of the
delimiter.
$PIECE() provides a tool for efficiently using values that contain
multiple elements or fields, each of which may be variable in length.
Applications typically use a single character for a $PIECE() delimiter
(second argument) to minimize storage overhead, and increase efficiency
at run-time. The delimiter must be chosen so the data values never
contain the delimiter. Failure to enforce this convention with edit
checks may result in unanticipated changes in the position of pieces
within the data value. The caret symbol (^), backward slash (\), and
asterisk (*) characters are examples of popular visible delimiters.
Multiple character delimiters may reduce the likelihood of conflict
with field contents. However, they decrease storage efficiency, and are
processed with less efficiency than single character delimiters. Some
applications use control characters, which reduce the chances of the
delimiter appearing in the data but sacrifice the readability provided
by visible delimiters.
A SET command argument can have something that has the format of a
$PIECE() on the left-hand side of its equal sign (=). This construct
permits easy maintenance of individual pieces within a string. It also
can be used to generate a string of delimiters. For more information on
SET $PIECE(), refer to SET in the "Commands" chapter.
3 Ex_of_$Piece()
Examples of $PIECE()
Example:
GTM> FOR i=0:1:3 WRITE !,$PIECE("1 2"," ",i),"<"
<
1<
2<
<
GTM>
This loop displays the result of $PIECE(), specifying a space as a
delimiter, a piece position "before," first and second, and "after" the
string.
Example:
GTM> FOR i=-1:1:3 WRITE !,$PIECE("1 2"," ",i,i+1),"<"
<
1<
1 2<
2<
<
GTM>
This example is similar to the previous example except that it displays
two pieces on each iteration. Notice the delimiter (a space) in the
middle of the output for the third iteration, which displays both
pieces.
Example:
F p=1:1:$L(x,"/") W ?p-1*10,$piece(x,"/",p)
This loop uses $LENGTH() and $PIECE() to display all the pieces of x in
columnar format.
Example:
GTM> s $P(x,".",25)="" W x
........................
This SETs the 25th piece of the variable x to null, with a delimiter of
a period. This produces a string of 24 periods preceding the null.
2 $Qlength()
$Qlength()
The $QLENGTH function returns the number of subscripts in a variable
name. The format is:
$QL[ENGTH] (namevalue)
o The namevalue has the form of an evaluated subscripted or
unsubscripted global variable (which yields a length of zero, and
which may have an environment - not counted) or local variable
name.
o The form returns a value which is derived from namevalue. If
namevalue has the form NAME(s1, s2,..., sn), considering n to be
zero, if there are no subscripts, then the function returns n.
o This function only affects the naked indicator if the string in
question is stored in a global variable.
3 Ex_of_$Qlength()
Examples of $Qlength()
Example:
WRITE $DATA(^|"XXX"|ABC(1,2,3,4))
GTM>0
SET X=$NAME(^(5,6))
WRITE $QLENGTH(X)
GTM>5
Refer to $NAme() section earlier in this chapter for an understanding
of the $NAME function.
2 $Qsubscript()
$Qsubscript()
The $QSUBSCRIPT function returns a component of a variable name.
The format of the $QSUBSCRIPT function is:
$QS[UBSCRIPT](namevalue, intexpr)
o The namevalue has the form of an evaluated subscripted or
unsubscripted global or local variable name.
o The intexpr selects the component of the name as follows:
-2 is reserved but may be "error",
-1 for environment,
0 for the unsubscripted name,
1 for the first subscript,
2 for the second subscript, and so on.
If the second argument selects a component that is not part of the
specified name, $QSUBSCRIPT() returns an empty string ("").
3 Ex_of_$Qsubscript()
Examples of $Qsubscript()
Example:
Assume that X is defined as in the "Examples of $Qlength()" earlier in
this chapter;
$QLENGTH (X="^|""XXX""|ABC(1,2,3,5,6)")
WRITE $QSUBSCRIPT(X,-2)
GTM>error
WRITE $QSUBSCRIPT(X,-1)
GTM>XXX
WRITE $QSUBSCRIPT(X,0)
GTM>^ABC
WRITE $QSUBSCRIPT(X,1)
GTM>1
WRITE $QSUBSCRIPT(X,4)
GTM>5
WRITE $QSUBSCRIPT(X,7)
GTM>""
2 $Query()
$Query()
The $QUERY function returns the next subscripted local or global
variable node name, independent of level, which follows the node
specified by its argument in M collating sequence and has a data value.
The format for the $QUERY function is:
$Q[UERY](glvn)
o The subscripted or unsubscripted global or local variable name
specifies the starting node from which $QUERY() searches for a node
with a data value.
o If $QUERY() finds no node after the specified global or local
variable, it returns a null string.
$QUERY() provides a tool for scanning an entire array for nodes that
have data values. Because $QUERY() can return a result specifying a
different level than its argument, the result provides a full variable
name. This contrasts with $ORDER(), which returns a subscript value. To
access the data value at a node, a $ORDER() return can be used as a
subscript; however, a $QUERY() return must be used with indirection.
Because arrays tend to have homogeneous values within a level but not
between levels, $QUERY() is more useful as a tool in utility programs
than in application programs. The $QUERY() is useful in avoiding nested
$ORDER loops.
Note that the standard does not unambiguously define the state of the
naked reference indicator after a $QUERY(). While in GT.M after
$QUERY(), the naked reference indicator reflects the $QUERY() argument,
NOT its result.
3 Ex_of_$Query()
Examples of $QUERY()
Example:
SET ^X(1,2,3)="123"
SET ^X(1,2,3,7)="1237"
SET ^X(1,2,4)="124"
SET ^X(1,2,5,9)="1259"
SET ^X(1,6)="16"
SET ^X("B",1)="AB"
The following routine:
SET y="^X"
FOR SET y=$QUERY(@y) QUIT:y="" WRITE !,y,"=",@y
produces the results:
^X(1,2,3)=123
^X(1,2,3,7)=1237
^X(1,2,4)=124
^X(1,2,5,9)=1259
^X(1,6)=16
^X("B",1)=AB
2 $Random()
$Random()
The $RANDOM function returns a random integer from a range specified by
its argument.
The format for the $RANDOM function is:
$R[ANDOM](intexpr)
o The integer expression specifies the upper exclusive limit of a
range of integers from which $RANDOM() may pick a result; $RANDOM()
never returns a number less than zero (0).
o If $RANDOM() has an argument less than one (1), it generates a
run-time error.
o $RANDOM can generate numbers up to 2147483646 (that is 2GB - 2).
$RANDOM() provides a tool for generating pseudo-random patterns useful
in testing or statistical calculations. $RANDOM() results fall between
zero (0) and one less than the argument.
Random number generators use factors from the environment to create
sequences of numbers. True random number generation requires a source
of what is known as noise. Pseudo-random numbers appear to have no
pattern, but are developed using interactions between factors that vary
in ways not guaranteed to be entirely random. In accordance with the M
standard, the GT.M implementation of $RANDOM() produces pseudo-random
numbers.
3 Ex_of_$Random()
Examples of $RANDOM()
Example:
GTM> FOR i=1:1:10 WRITE $RANDOM(1)
0000000000
GTM>
This shows that when $RANDOM() has an argument of one (1), the result
is too confined to be random.
Example:
SET x=$RANDOM(100)+1*.01
This $RANDOM() example produces a number between 0 and 99. The example
then shifts with addition, and scales with multiplication to create a
value between .01 and 1.
2 $Reverse()
$Reverse()
The $REVERSE function returns a string with the characters in the
reverse order from that of its argument.
The format for the $REVERSE function is:
$RE[VERSE](expr)
o The expr in the syntax is the string to be reversed.
3 Ex_of_$Reverse()
Examples of $REVERSE()
Example:
WRITE $REVERSE(123)
GTM>321
WRITE $REVERSE("AbCDe")
GTM>"eDCbA"
2 $Select()
$Select()
The $SELECT function returns a value associated with the first true
truth-valued expression in a list of paired expression arguments.
The format for the $SELECT function is:
$S[ELECT](tvexpr:expr[,...])
o $SELECT() evaluates expressions from left to right.
o If a truth-valued expression is TRUE (1), $SELECT() returns the
corresponding expression after the colon (:) delimiter.
o Once $SELECT() finds a TRUE, the function does not process any
remaining arguments.
o If $SELECT() finds no TRUE truth-value in its list of arguments,
the function generates a run-time error.
$SELECT() is one of a limited set of functions that permit an
indefinite number of arguments. $SELECT() provides a means of selecting
from a list of alternatives.
Generally, the last $SELECT() argument has numeric literal one (1) for
a truth-value to prevent run-time errors, and to provide a "default"
value.
3 Ex_of_$Select()
Examples of $SELECT()
Example:
GTM> F i=3:-1:0 W !,$S(i=1:"here",i=2:"come",i=3: "Watson")
Watson
come
here
%GTM-E-SELECTFALSE, No argument to $SELECT was true
GTM>
This loop uses $SELECT() to WRITE a series of strings. Because there is
no true argument on the fourth iteration, when i=0, $SELECT() produces
an error.
Example:
SET name=$S(sex="M":"Mr. ",sex="F":"Ms. ",1:"")_name
This example uses $SELECT() to add a prefix to the name based on a sex
code held in the variable sex. Notice that the default handles the case
of a missing or incorrect code.
Example:
IF $S(x=+x:x,x="":0,"JANAPRJULOCT"[x:1,1:0) D THING
This uses $SELECT() to perform complex logic as the truth-valued
expression argument to an IF command.
2 $Stack()
$Stack()
The $STACK function returns strings describing aspects of the execution
environment.
The format for the $STACK function is:
$ST[ACK](intexpr[,expr])
o The intexpr identifies the M virtual machine stack level (as
described by the standard), on which the function is to provide
information.
o The optional second argument is evaluated as a keyword that
specifies a type of information to be returned as follows: "PLACE"
for position in the code (for which, GT.M. due to its compiled
nature, has no information), "MCODE" for the source code if
available, or "ECODE" for the $ECODE value associated with the
stack level.
o When $STACK has only one argument, values corresponding to
available stack levels specify a return value that indicates how
the level was created, as follows:
o If intexpr is zero (0), the function returns information on how
GT.M was invoked.
o If intexpr is minus one (-1), the function returns the highest
level for which $STACK can return information. Note that, if
$ECODE="", $STACK(-1) returns the same value as $STACK.
o If intexpr is greater than zero (0) and less than or equal to
$STACK (-1), indicates how this level of process stack was created
("DO", "XECUTE", or "$$". "$$" being for an extrinsic function).
o If intexpr is greater than $STACK (-1), the function returns an
empty string.
o For any integer value of "level" between 0 and max (inclusive), the
function $STACK(level, type) provides the following information:
Type Information
"MCODE" the line of code that was executed
"PLACE" the address of the above line of code or the symbol at
("@") to indicate code executed from a string value
"ECODE" either an empty string, or the error code(s) that was added
at this execution level.
3 Ex_of_$Stack()
Examples of $STACK()
Example:
WRITE !,$STACK
XECUTE "WRITE !,$STACK"
DO Label
WRITE !,$$ELabel
WRITE !,$STACK
QUIT
Label
WRITE !,$STACK
DO DLabel
QUIT
ELabel()
QUIT $STACK
DLabel
WRITE !,$STACK
QUIT
The above example when executed displays the current M stack level. The
result of the execution is:
GTM>0
1
1
2
1
0
Example for error processing:
For i=$STACK(-1):-1:1 DO
. WRITE !,$STACK(i,"PLACE"),":"
. WRITE $STACK(i,"MCODE")
. QUIT
The above example can be used to display a trace of the code path that
led to an error.
2 $Text()
$Text()
The $TEXT function returns source text for the line specified by its
argument.
The format for the $TEXT function is:
$T[EXT](entryref)
o The entryref specifies the label, offset, and routine of the source
line that $TEXT() returns.
o If the label+offset combination do not fall within the routine,
$TEXT returns a null string.
o If the entryref explicitly or implicitly specifies an offset of
zero (0) from the beginning of the routine, $TEXT() returns the
routine name.
o If the entryref does not specify a routine, GT.M assumes the
current routine, that is, the routine at the top of a ZSHOW "S."
o A GT.M extension to $TEXT() permits negative offsets; however,
every offset must still be preceded by a plus sign (+) delimiter,
(for example, LABEL+-3). If a negative offset points to a line
prior to the zero line, $TEXT() generates a run-time error.
$TEXT() provides a tool for examining routine source code and the name
of the current routine. $TEXT() assists, along with the ZPRINT command,
in debugging programs. $TEXT() also allows the insertion of small
tables of driver information into a routine. Because $TEXT() is not
very efficient and the table-driven technique is generally best suited
to minimal program changes, this approach is best used for prototyping
and the tables should reside in global variables for production.
If $TEXT() cannot access the source file for the current object, either
because it is not in the location from which it was compiled or because
the process does not have access to some piece of the path to the
source, or if the located source does not match the object currently in
use by the process, $TEXT() returns the empty string.
3 Ex_of_$Text()
Examples of $TEXT()
Example:
F i=1:1 S x=$T(+i) Q:x="" W !,x
This loop uses $TEXT() to write out the entire source for the current
routine.
Example:
GTM> WRITE $TEXT(+0)
GTM$DMOD
GTM> WRITE $TEXT(+1)
GTM>
This uses $TEXT() to WRITE the name of the current routine, then it
tries to access the source and returns an empty string. This occurs
because the default Direct Mode image is compiled by Sanchez and
delivered without source. The exact failure message may vary.
2 $TRanslate()
$TRanslate()
The $TRANSLATE function returns a string that results from replacing or
dropping characters in the first of its arguments as specified by the
patterns of its other arguments.
The format for the $TRANSLATE function is:
$TR[ANSLATE](expr1[,expr2[,expr3]])
o The first expression specifies the string on which $TRANSLATE()
operates. If the other arguments are omitted, $TRANSLATE() returns
this expression.
o The optional second expression specifies the characters for
$TRANSLATE() to replace. If a character occurs more than once in
the second expression, the first occurrence controls the
translation, and $TRANSLATE() ignores subsequent occurrences. If
this argument is omitted, $TRANSLATE() returns the first expression
without modification.
o The optional third expression specifies the replacement characters
for the second expression that corresponds by position. If this
argument is omitted or shorter than the second expression,
$TRANSLATE() drops all occurrences of characters in the second
expression that have no replacement in the corresponding position
of the third expression.
$TRANSLATE() provides a tool for tasks such as changing case and doing
encryption. For examples of case translation, refer to the ^%LCASE and
^%UCASE utility routines.
The $TRANSLATE() algorithm can be understood as follows:
o $TRANSLATE() evaluates each character in the first expression,
comparing it character by character to the second expression
looking for a match. If there is no match in the second expression,
the resulting expression contains the character without
modification.
o When it locates a character match, $TRANSLATE() uses the position
of the match in the second expression to identify the appropriate
replacement for the original expression. If the second expression
has more characters than the third expression, $TRANSLATE()
replaces the original character with a null, thereby deleting it
from the result. By extension of this principle, if the third
expression is missing, $TRANSLATE() deletes all characters from the
first expression that occur in the second expression.
3 Ex_of_$TRanslate()
Examples of $TRANSLATE()
Example:
GTM> WRITE $TR("ABC","CB","1")
A1
GTM>
o First, $TRANSLATE() searches for "A" (the first character in the
first expression, "ABC") within the second expression ("CB"). Since
"A" does not exist in the second expression, it appears unchanged
in the result.
o Next, $TRANSLATE() searches for "B" (the second character in the
first expression) within the second expression ("CB"). Because "B"
holds the second position in the second expression ("CB"),
$TRANSLATE() searches for the character holding the second position
in the third expression. Since there is no second character in the
third expression, $TRANSLATE() replaces "B" with a null,
effectively deleting it from the result.
o Finally, $TRANSLATE() searches for "C" (the third character in the
first expression) within the second expression ("CB"), finds it in
the first position, and replaces it with the number 1, which is in
the first position of the third expression. The translated result
is "A1."
Example:
GTM> WRITE $TR("A","AA","BC")
B
GTM>
This $TRANSLATE() example finds the first occurrence of "A" in the
second expression, which holds the first character position, and
substitutes the character in the first position of the third
expression.
Example:
GTM> WRITE $TR("BACKUP","AEIOU")
BCKP
GTM>
Because the $TRANSLATE() has only two parameters in this example, it
finds the characters in the first expression that also exist in the
second expression and deletes them from the result.
2 $View()
$View()
The $VIEW function returns information about an environmental factor
selected by the arguments. In GT.M, the first argument contains a
keyword identifying the environmental factor and, where appropriate,
subsequent arguments select among multiple possible occurrences of that
factor.
The format for the $VIEW() function is:
$V[IEW](expr1[,expr2])
o The first expression specifies a keyword identifying the target
factor for $VIEW() to examine.
o The second expression differentiates between multiple possible
targets for some keywords. $VIEW() requires the second expression
for some keywords and does not permit it for others.
The $VIEW function returns 1 (true) if the region is frozen by MUPIP or
DSE and returns 0 (false) otherwise.
3 Arg_Key_of_$View()
Argument Keywords of $VIEW()
$VIEW() provides a means of accessing GT.M environmental information.
$VIEW() is similar in purpose to Intrinsic Special Variables. When GT.M
permits modification of the factors accessible with $VIEW(), the VIEW
command generally provides the tool for performing the change.
3 Ex_of_$View()
Examples of $VIEW()
Example:
S len=$L(name)
S be4=$EXTRACT(name,1,len-1)_$CHAR($ASCII(name,len)-1)
I $V("RTNNEXT",be4_$E("ZZZZZZZ",1,8-len))=name D
. ZLINK name
Given a routine name this uses $VIEW() to determine whether the image
contains the routine. If the routine already exists the ZLINK replaces
it. Otherwise, auto-ZLINK will bring in a new copy.
2 $ZBIT_Func
$ZBIT Functions
A series of functions beginning with $ZBIT let you manipulate bits.
Each function is described in its own section, and an example at the
end of the last section illustrates the use of several of the functions
in context.
3 $ZBITAND()
$ZBITAND()
The $ZBITAND function performs an AND function on two bit strings and
returns a bit string equal in length to the shorter of the two
arguments (containing set bits in those positions where both of the
input strings have set bits). Positions corresponding to positions
where either of the input strings have a cleared bit, also have cleared
bits in the resulting string.
The format for the $ZBITAND() function is:
$ZBITAND(expr1,expr2)
o The first expression specifies one of the bit strings that is input
to the AND operation.
o The second expression specifies the other bit string that is input
to the AND operation.
3 $ZBITCOUNT()
$ZBITCOUNT()
The $ZBITCOUNT function returns the number of ON bits in a bit string.
The format for the $ZBITCOUNT function is:
$ZBITCOUNT(expr)
o The expression specifies the bit string to examine.
3 $ZBITFIND()
$ZBITFIND()
The $ZBITFIND function performs the analog of the $FIND function on a
bit string. It returns an integer that identifies the position after
the first position equal to a truth-valued expression that occurs at,
or after, the specified starting position.
The format for the $ZBITFIND function is:
$ZBITFIND(expr,tvexpr[,intexpr])
o The expression specifies the bit string to examine.
o The truth-valued expression specifies the bit value for which
$ZBITFIND() searches (1 or 0).
o The optional integer argument specifies the starting position at
which to begin the search. If this argument is missing, $ZBITFIND()
begins searching at the first position of the string. $ZBIT
functions count the first bit as position one (1).
If the optional integer argument exceeds the length of the string, or
if the function finds no further bits, $ZBITFIND() returns a zero
value.
3 $ZBITGET()
$ZBITGET()
The $ZBITGET function returns the value of a specified position in the
bit string.
The format for the $ZBITGET function is:
$ZBITGET(expr,intexpr)
o The expression specifies the bit string to examine.
o The integer argument specifies the position in the string for which
the value is requested. If the integer argument is negative, zero,
or exceeds the length of the bit string, it is rejected with a
run-time error. $ZBIT functions count the first bit as position one
(1).
3 $ZBITLEN()
$ZBITLEN()
The $ZBITLEN function returns the length of a bit string, in bits.
The format for the $ZBITLEN function is:
$ZBITLEN(expr)
o The expression specifies the bit string to examine.
3 $ZBITNOT()
$ZBITNOT()
The $ZBITNOT function returns a copy of the bit string with each input
bit position inverted.
The format for the $ZBITNOT function is:
$ZBITNOT(expr)
o The expression specifies the bit string whose inverted bit pattern
becomes the result of the function.
3 $ZBITOR()
$ZBITOR()
The $ZBITOR function performs a bitwise OR on two bit strings, and
returns a bit string equal in length to the longer of the two arguments
(containing set bits in those positions where either or both of the
input strings have set bits). Positions that correspond to positions
where neither input string has a set bit have cleared bits in the
resulting string.
The format for the $ZBITOR function is:
$ZBITOR(expr1,expr2)
o The first expression specifies one of the bit strings that is input
to the OR operation.
o The second expression specifies the other bit string that is input
to the OR operation.
3 $ZBITSET()
$ZBITSET()
The $ZBITSET function returns an edited copy of the input bit string
with a specified bit set to the value of the truth-valued expression.
The format for the $ZBITSET function is:
$ZBITSET(expr,intexpr,tvexpr)
o The expression specifies the input bit string.
o The integer expression specifies the position of the bit to
manipulate. Arguments that are negative, zero, or exceed the length
of the bit string produce a run-time error. $ZBIT functions count
the first bit as position one (1).
o The truth-valued expression specifies the value to which to set the
specified bit (0 or 1).
3 $ZBITSTR()
$ZBITSTR()
The $ZBITSTR function returns a bit string of a specified length with
all bit positions initially set to either zero or one.
The format for the $ZBITSTR function is:
$ZBITSTR(intexpr[,tvexpr])
o The integer expression specifies the length of the bit string to
return; arguments that exceed the maximum length of 253,952 produce
a run-time error.
o The optional truth-valued expression specifies the value to which
all bit positions should initially be set (0 or 1). If this
argument is missing, the bits are set to zero.
3 $ZBITXOR()
$ZBITXOR()
The $ZBITXOR performs a bitwise exclusive OR on two bit strings, and
returns a bit string equal in length to the shorter of the two
arguments (containing set bits in those position where either but not
both of the input strings have set bits). Positions that correspond to
positions where neither or both input string has a set bit have cleared
bits in the resulting string.
The format for the $ZBITXOR function is:
$ZBITXOR(expr1,expr2)
o The first expression specifies one of the bit strings that is input
to the XOR operation.
o The second expression specifies the other bit string that is input
to the XOR operation.
3 Ex_of_$ZBIT_Func
Examples of $ZBIT Functions
Example:
ZCRC(X)
NEW R,I,J,B,X1,K
SET R=$ZBITSTR(8,0)
FOR I=1:1:$L(X) S R=$ZBITXOR(R,$$BITIN($A(X,I)))
QUIT $$BITOUT(R)
;CONVERT A BYTE TO A BIT STRING
BITIN(X)
SET X1=$ZBITSTR(8,0)
FOR J=1:1:8 S B=X#2,X=X\2 i B s X1=$ZBITSET(X1,J,1)
QUIT X1
; CONVERT A BITSTRING TO A NUMBER
BITOUT(X)
SET X1=0
FOR K=1:1:8 I $ZBITGET(X,K) S X1=X1+(2**(K-1))
QUIT X1
This uses several $ZBIT functions to turn a character into a bit stream
and return a coded value.
While this example illustrates the use of several of the $ZBIT
functions, the following example produces identical results if you need
to code the function illustrated above for production.
ZCRC(X)
NEW R,I,J,B,X1,K
SET R=$ZBITSTR(8,0)
FOR I=1:1:$L(X) S R=$ZBITXOR(R,$C(0)_$E(X,I))
QUIT $A(R,2)
This example illustrates the use of $C to specify the number of invalid
bits that exist at the end of the character string. In this case there
are zero invalid bits.
2 $ZDate()
$ZDate()
The $ZDATE function returns a date and/or time formatted as text based
on an argument formatted in the manner of $HOROLOG. For information on
the format of $HOROLOG, refer to the "Intrinsic Special Variables"
chapter in this manual.
The format for the $ZDATE function is:
$ZD[ATE](expr1[,expr2[,expr3[,expr4]]]])
o The first expression specifies in $HOROLOG format the date and/or
time that $ZDATE() returns in text format. If the output requires
only the date or the time, the other piece of the argument that is
delimited by a comma (,) may be null.
o The optional second expression specifies a string providing
$ZDATE() with a "picture" of the desired output format. If this
argument is missing or null, $ZDATE() uses the default format
string "MM/DD/YY". If the optional second expression exceeds 64
characters, $ZDATE() generates a run-time error.
o The optional third expression specifies a list of 12 month codes,
separated by commas (,), that $ZDATE() uses in formatting text
months called for by the "MON" picture, (i.e., $ZDATE() outputs
$PIECE(expr3,",",month-number) when "MON" appears in the second
expression). If this argument is missing or null, $ZDATE() uses
three-character English abbreviations for months.
o The optional fourth expression specifies a list of seven day codes,
separated by commas (,), which $ZDATE() uses in formatting text
days of the week called for by the "DAY" picture, $ZDATE() outputs
$PIECE (expr4,",",day-of-week-number) when "DAY" appears in the
second expression; if this argument is missing or null, $ZDATE()
uses three-character English abbreviations for days of the week.
$ZDATE() provides an easy and flexible tool for putting M internal
date/time ($HOROLOG) formats into more user-friendly formats.
The Intrinsic Special Variable $ZDATEFORM determines the output format
for years. The default value is zero (0), in which case $ZDATE() with
one argument (no format specification) uses a "YY" (two digit) format
for all years. If $ZDATEFORM is one (1), a "YYYY" (four digit) format
is used for years later than 1999. For all other values of $ZDATEFORM,
"YYYY" (four digit) format is used for all years. $ZDATEFORM does not
affect $ZDATE() when the format argument is specified.
3 $ZDate_Form_Spec_Ele
$ZDATE Format Specification Elements
This section lists the $ZDATE() format specification elements. $ZDATE()
format specifications must appear in upper case. When any alphabetic
characters in format specifications are in lower case, $ZDATE()
generates a run-time error.
YY Outputs the rightmost two digits of the year.
YEAR Outputs the year as a four-digit number.
MM Outputs the month as a two-digit zero-filled number between 01
and 12.
MON Outputs the month as a three-letter abbreviation. (You can
modify the output further using expr3).
DD Outputs the day of the month as a two-digit zero-filled number
between 01 and 31.
DAY Outputs the day of the week as a three-letter abbreviation.
(You can modify the output further using expr4).
24 Outputs the hour of the day as a zero-filled number between 00
and 23.
12 Outputs the hour of the day as a zero-filled number between 01
and 12.
60 Outputs the minute of the hour as a zero-filled number between
00 and 59.
SS Outputs the second of the minute as a zero-filled number between
00 and 59.
AM Outputs the letters AM and PM depending on the time.
+ Inserts a plus sign (+) in the output string
- Inserts a minus sign (-) in the output string.
. Inserts a period (.) in the output string.
, Inserts a comma (,)in the output string.
/ Inserts a slash (/) in the output string.
: Inserts a colon (:) in the output string.
; Inserts a semi-colon (;) in the output string.
* Inserts an asterisk (*) in the output string.
A blank space inserts a blank space in the output string.
3 Ex_of_$ZDate()
Examples of $ZDATE()
Example:
GTM> WRITE $H,!,$ZDATE($H)
55243,43223
04/01/2002
GTM>
This displays $HOROLOG and then uses $ZDATE() to display today's date.
The output shown would appear if today were the first of April, 2002.
Example:
GTM> W $ZDATE($H,"DD-MON-YEAR")
01-APR-2002
GTM>
This uses the second argument to specify a text format different from
the default.
Example:
GTM> SET m="Januar,Februar,Marz,April,Mai,Juni,Juli,August,"
GTM> SET m=m_"September,October,November,Dezember"
GTM> WRITE $ZDATE($H,"DD-MON-YEAR",m)
01-April-2002
GTM>
This is similar to the prior example, however it uses the third
argument to specify the months in German.
Example:
GTM> SET d="Dimanche,Lundi,Mardi,Mercredi,Jeudi,Vendredi,Samedi"
GTM> WRITE $ZD($H,"DAY, DD/MM/YY","",d)
Mercredi, 01/04/2002
GTM>
This example displays the first of April, however it uses the fourth
argument to specify the days of the week in French.
Example:
GTM> WRITE !,$ZDATE($H,"12:60:55 AM")
10:35:51 PM
GTM>
This example shows hours, minutes, and seconds in a 12 hour clock with
an AM/PM indicator.
Example:
GTM> WRITE !,$ZDATE(",36524","24-60")
10-08
GTM>
This example shows hours and minutes on a 24 hour clock. Notice that
the first argument must provide the time in the second comma delimiter
piece to match $HOROLOG format.
Example:
GTM>WRITE $ZDATEFORM
0
GTM>WRITE $ZDATE($H)
11/15/02
GTM>SET $ZDATEFORM=1
GTM>WRITE $ZDATE($H)
11/15/2002
GTM>WRITE $ZDATE($H,"MM/DD/YY")
11/15/02
This example converts the output format for years from the default
("YY") format to the four digit format ("YYYY") using the Intrinsic
Special Variable $ZDATEFORM.
2 $ZJOBEXAM()
$ZJOBEXAM()
The $ZJOBEXAM function returns the full specification of the file into
which the function places a ZSHOW "*". The return value serves as a way
to save, to notify others of the exact location of the output, or to
open the file for further processing. GT.M reports each $ZJOBEXAM() to
the operator log facility with its file specification.
The optional expression argument is a template output device
specification. It can be a device, a file directory, or a file name.
The template is an expression that is pre-processed to create a file
specification as the target for the ZSHOW. The preprocessing is
equivalent to $ZPARSE(), as illustrated by the following M code:
Set deffn="GTM_JOBEXAMINE.ZSHOW_DMP_"_$JOB_"_"_<cntr>
Set filespec=$ZPARSE(expr1,"",deffn)
The $ZJOBEXAM()does not trigger error processing except when there is a
problem storing its return value, so no error is reported to the
process until after any dump is complete. In the event of any error
encountered during the $ZJOBEXAM(), GT.M sends an appropriate message
to operator log facility and returns control to the caller. Note that
this special error handling applies only to the $ZJOBEXAM(), and is not
a property of the $ZINTERRUPT interrupt handler, which uses $ZJOBEXAM()
by default.
$ZJOBEXAM() dump files contain the context of a process at the time the
function executes. Placement and management of these files should
consider their potential size and security implications.
3 Ex_of_$ZJOBEXAM()
Examples of $ZJOBEXAM()
Example:
GTM>Set x=$ZJOBEXAM()
GTM>Write x
/home/testarea/demo/GTM_JOBEXAM.ZSHOW_DMP_28760_1
GTM>Set x=$ZJOBEXAM("test.file")
GTM>write x
/home/testarea/demo/test.file
GTM>
Shows default file name and type of the files created containing the
zshow dump information and the difference when the name and type are
specified.
2 $ZMessage()
$ZMessage()
The $ZMESSAGE function returns a message string associated with a
specified status code.
The format for the $ZMESSAGE function is:
$ZM[ESSAGE](intexpr)
o The integer expression specifies the status code for which
$ZMESSAGE() returns error message text.
$ZMESSAGE() provides a tool for examining the message associated with a
particular message code as reported in $ZSTATUS.
The $ZSTATUS Intrinsic Special Variable holds the message code and the
message of the last non-Direct Mode GT.M error. For more information on
$ZSTATUS, refer to the "Intrinsic Special Variables" chapter in GT.M
Programmer's Guide.
3 Ex_of_$ZMessage()
Examples of $ZMESSAGE()
Example:
GTM> WRITE $ZMESSAGE(36)
Interrupted system call
GTM>
This uses $ZMESSAGE() to display the message string corresponding to
code 36.
2 $ZPARSE()
$ZPARSE()
The $ZPARSE function expands a file name to a full pathname and then
returns the full pathname or one of its fields (directory, name, or
extension).
The format for the $ZPARSE function is:
$ZPARSE(expr1[,expr2[,expr3[,expr4[,expr5]]]])
o The first expression specifies the file name; if the file name is
not valid, $ZPARSE() returns a null string; if the file name
contains a wildcard (* and/or ?), $ZPARSE() returns a file name
containing the wildcard(s).
o The optional second expression specifies the field of the pathname
that $ZPARSE() returns; if this argument is missing or null,
$ZPARSE() returns a full pathname constructed using default values
in place of any fields missing for directory, file and extension.
o The optional third and fourth expressions specify default values to
use during file name expansion for missing fields (directory, name,
or extension), if any, in the original file name. For any field
missing in the original file name specified in expr1, $ZPARSE()
will attempt to substitute the corresponding field from expr3; if
that field is not present in expr3, $ZPARSE() will attempt to use
the corresponding field from expr4.
o If the file extension is missing from all three of expr1, expr3,
and expr4, $ZPARSE() will return a null string for the
corresponding field. If the file, or directory is missing from all
three of expr1, expr3, and expr4, $ZPARSE() will substitute the
information from your current working directory.
o The optional fifth expression specifies the mode or type of parse
that $ZPARSE() performs.
$ZPARSE() provides a tool for verifying that a file name is
syntactically correct, for examining specific fields of a file name,
and for filling in missing pieces in a partial specification based on a
hierarchy of defaults. For information about determining whether a file
exists, refer to the description of $ZSEARCH().
$ZPARSE() arguments, after the first, are optional. If you use no other
arguments, a single argument is sufficient. However, if you use
selected arguments $ZPARSE() requires that null strings ("") be filled
in for the unspecified arguments.
The acceptable keywords for the second argument are:
"DIRECTORY" Directory name
"NAME" File name (excluding file extension)
"TYPE" File typeextension
The keywords may be entered in either upper or lower case. Variables
that evaluate to these strings and indirection are acceptable for
argument two. When the keywords themselves appear as string literals,
they must be enclosed in quotation marks (" ").
The following guidelines must be followed in constructing arguments
one, three and four:
o Directory specifications must end in a slash; anything after the
final slash in the directory specification is assumed to be part of
the name specification.
o A file name with an extension must include at least one character
to the left of the period (.). Thus, "/user/.login" refers to the
file named ".login", while "/usr/taxes.c" refers to a file named
"taxes" with the extension "c". If a file name includes more than
one period, the extension includes all letters to the right of the
rightmost period.
The keywords for the fifth argument $ZPARSE() are:
NULL ("") Returns a full file-specification or device
"SYNTAX_ONLY"
Disables checking for the existence of the directory or device.
3 Ex_of_$ZPARSE()
Examples of $ZPARSE()
Example:
GTM> WRITE $ZPARSE("test","","/usr/work/","dust.lis")
/usr/work/test.lis
GTM>
This uses $ZPARSE() to demonstrate defaulting using the third and
fourth arguments. The result gets the directory field from the third
expression, the name from the first expression, and the type from the
fourth expression.
Example:
GTM>r!,"file :",f w ?20,$zparse(f,"directory")
file: test.list /usr/work/
GTM>
This uses $ZPARSE() to display the directory for the file name entered
as input at the prompt file: , in this case, the current working
directory.
Example:
$ cd /usr/work/me
$ $gtm
GTM>W $ZPARSE("test","","x.list","y.c")/usr/work/me/test.lis
GTM>W $ZPARSE("test","","/usr/work/","/dev/y.c")/usr/work/test.c
GTM>W $ZPARSE("test","","/usr/work","/dev/y.c")/usr/test.c
GTM>
This example illustratest the use of the third and fourth arguments to
$ZPARSE(). In the first statement, the first argument has no directory
or extension field, so $ZPARSE() substitutes the extension field from
the third argument. Since neither the third nor fourth argument
specifies a directory, and because the fourth argument does not contain
any fields that are not present in the third argument, the fourth
argument is not used.
In the second statement, the first argument to $ZPARSE() is again
missing both the directory and extension. In this instance, $ZPARSE()
uses the directory specified in the third argument and, becuase neither
the first nor third argument specifies a file extension, $ZPARSE() uses
the file extension from the fourth argument.
In the third statement, because "/usr/work" does not end with a
backward slash (/), $ZPARSE() interprets the substring "work" as a file
name. Then, $ZPARSE() substitutes "/usr/" for the directory missing in
the first argument and substitutes ".c" from the fourth argument for
the extension missing from both the first and third arguments.
Example:
$ cd /usr/work/met
$ $gtm_dist/mumps -direct
GTM>f i="DIRECTORY","NAME","TYPE",""d
. W $zparse("test.m",i),!
/usr/work/me/
test
.m
/usr/work/me/test.m
GTM>
This example illustrates the output produced for each of the possible
values for the second argument.
2 $ZPrevious()
$ZPrevious()
The $ZPREVIOUS function returns the subscript of the previous local or
global variable name in collation sequence within the array level
specified by its argument. When $ZPREVIOUS() has an unsubscripted
argument, it returns the previous unsubscripted local or global
variable name in collating sequence.
The $ZPREVIOUS function provides compatibility with some other M
implementations. The M Development Committee chose to implement this
functionality with the optional second -1 argument of $ORDER().
Therefore, when a design requires this functionality $ORDER() has the
advantage over $ZPREVIOUS of being part of the M standard.
The format for the $ZPREVIOUS function is:
$ZP[REVIOUS](glvn)
o The subscripted or unsubscripted global or local variable name
specifies the node prior to which $ZPREVIOUS() searches backwards
for a defined node with data and/or descendants. The number of
subscripts contained in the argument implicitly defines the array
level.
o If $ZPREVIOUS() finds no node at the specified level before the
specified global or local variable, it returns a null string.
o If the last subscript in the subscripted global or local variable
name is null, $ZPREVIOUS() returns the last node at the specified
level.
$ZPREVIOUS() is equivalent to $ORDER() with a second argument of -1.
2 $ZQGBLMOD()
$ZQGBLMOD()
The $ZQGBLMOD function enables an application to determine whether it
can safely apply a lost transaction to the database. A lost transaction
is a transaction that must be rolled off a database to maintain
dual-site consistency.
The format for the $ZQGBLMOD function is:
$ZQGBLMOD(gvn)
o The subscripted or non-subscripted global variable name (gvn)
specifies the target node.
o A return value of zero (0) means the value of the global variable
has not changed since the last synchronization of the primary and
secondary.
o A return value of one (1) means the value of the global variable
may have changed since the last synchronization of the primary and
secondary.
$ZQGBLMOD function produces an error if you submit an argument that is
not a global variable name.
Internally, $ZQGBLMOD (gvn) compares the GT.M transaction number in the
database block in which the global variable name is stored with the
value in the resync_tn field stored in the database file header.
For example, if x is the transaction number of the level-0 database
block in which gvn resides, and y is the value of resync_tn of region
reg containing gvn, then the following is true:
o If x £ y, no transaction modified the level-0 database block z in
which gvn resides since the databases at primary and secondary
became synchronized with each other. $ZQGBLMOD() returns a zero
(0).
o If x > y, some transaction modified z, but not necessarily
❇❖■
, after the primary and secondary system databases synchronized with each
, after the primary and secondary system databases synchronized with each
, after the primary and secondary system databases synchronized with each
, after the primary and secondary system databases synchronized with each
, after the primary and secondary system databases synchronized with each
, after the primary and secondary system databases synchronized with each
, after the primary and secondary system databases synchronized with each
, after the primary and secondary system databases synchronized with each
If a transaction is a lost transaction that has been rolled back and it
is determined that for all the M globals set and killed in the
transaction $ZQGBLMOD() is zero (0), it is probably safe to apply the
updates automatically. However, this determination of safety can only
be made by the application designer and not by GT.M. If the $ZQGBLMOD()
is one (1) for any set or kill in the transaction, it is not safe to
apply the update.
The test of $ZQGBLMOD() and applying the updates must be
encapsulated inside a GT.M transaction.
Another approach to handling lost transactions would be to store in the
database the initial message sent by a client, as well as the outcome
and the response, and to reprocess the message with normal business
logic. If the outcome is the same, the transaction can be safely
applied.
If restartable batch operations are implemented, lost batch
transactions can be ignored since a subsequent batch restart will
process them correctly.
2 $ZSEARCH()
$ZSEARCH()
The $ZSEARCH function attempts to locate a file matching the specified
file name. If the file exists, it returns the file name; if the file
does not exist, it returns the null string.
The format for the $ZSEARCH function is:
$ZSEARCH(expr[,intexpr])
o The expression contains a file name, with or without wildcards, for
which $ZSEARCH() attempts to locate a matching file. Repeating
$ZSEARCH with the same filename uses the same context and return a
sequence of matching files when they exist; when the sequence is
exhausted, $ZSEARCH() returns an empty string (""). Any change to
the file name starts a new context.
o $ZSEARCH() uses the process current working directory, if the
expression does not specify a directory.
o The optional integer expression specifies a "stream" number from 0
to 255 for each search; streams provide a means of having up to 256
$ZSEARCH() contexts simultaneously in progress.
o If a $ZSEARCH() stream has never been used or if the expression
differs from the argument to the last $ZSEARCH() of the stream, the
function resets the context and returns the first pathname matching
the expression; otherwise, it returns the next matching file in
collating sequence; if the last prior pathname returned for the
same expression and same stream was the last one matching the
argument, $ZSEARCH() returns a null string.
$ZSEARCH() provides a tool for verifying that a file exists. For
information to help determine the validity of a file name, refer to the
section on $ZPARSE()
3 Ex_of_$ZSEARCH()
Examples of $ZSEARCH()
Example:
GTM> WRITE $ZSEARCH("data.dat")
/usr/staff/ccc/data.dat
GTM>
This uses $ZSEARCH() to display the full file path name of "data.dat"
in the process current default directory.
Example:
GTM>SET x=$ZSEARCH("*.M")
GTM>FOR S x=$ZSEARCH("*.M") Q:x="" W !,$ZPARSE(x,"NAME")
This FOR loop uses $ZSEARCH() and $ZPARSE() to display M source file
names in the process current working directory. To ensure that the
search starts at the beginning, the example resets the context by first
searching with a different argument.
2 $ZTRNLNM()
$ZTRNLNM()
The $ZTRNLNM function gives the value of an environment variable.
$ZTRNLNM() does iterative translation in cases where one environment
variable is set to the name of another environment variable.
The format for the $ZTRNLNM function is:
$ZTRNLNM(expr)
The expression specifies the target environment variable.
3 Ex_of_$ZTRNLNM()
Examples of ZTRNLNM()
Example:
GTM> write $ztrnlnm("gtm_dist")
/usr/dev/bin
GTM>
This uses $ZTRNLNM() to display the translation value for gtm_dist.
1 Intr_Spe_Vars
Intrinsic Special Variables
M Intrinsic Special Variables start with a single dollar sign ($). GT.M
provides such variables for program examination. In some cases, the
Intrinsic Special Variables may be set to modify the corresponding part
of the environment.
None of the Intrinsic Special Variables can be KILLed. SETting or
NEWing is generally not allowed, but is specifically noted in the
descriptions of those that do.
2 $Device
$Device
$D[EVICE] reflects the status of the current device. If the status of
the device does not reflect any error-condition, the value of $DEVICE,
when interpreted as a truth-value is 0 (FALSE). If the status of the
device reflect any error-condition, the value of $DEVICE, when
interpreted as a truth-value is 1 (TRUE).
The initial value of $DEVICE is implementation dependant. However,
if the initial value of $IO is the empty string, then the initial
value of $DEVICE is also empty string.
$DEVICE gives status code and meaning, in one access:
Example:
1,Connection reset by peer
The above message is displayed on the server side when the socket
device is closed on the client side.
2 $ECode
$ECode
$EC[ODE] contains a list of error codes for "active" errors -the error
conditions which are not yet resolved. If there are no active errors,
$ECODE contains the empty string. Whenever an error occurs, a code for
that error is appended to the value of $ECODE in such a way that the
value of $ECODE always starts and ends with a comma.
The value of $ECODE can be SET, and when it is set to a non-NULL value,
error processing starts.
List of codes for $ECODE start with comma seperated by commas. A code
starts with "M", "U", or "Z", with rest numeric. "M" codes are assigned
by MDC (MUMPS Development Committee), "U" by application (programmers),
and "Z" codes by MUMPS implementors (in this case GT.M).
An error always has a GT.M specified code and many errors also have an
ANSI Standard code. The complete list of standardized error codes can
be referenced from GT.M Message and Recovery Procedures Reference
Manual version 4.3 and onwards.
IF $ECODE[",M61," WRITE "Undefined local variable"
The leftmost character of the value of $ECODE is always a comma.
This means that every error code that is stored in $ECODE is
surrounded by commas. If $ECODE was to contains the error code
without the commas (that is, "M61"), the variable would check for
subset "M6" as well. Thus, it is recommended that you include the
commas in the value to check. For example; check whether $ECODE
contains ",M61,".
$ECODE can be SET but not NEW'd. When $ECODE is set to the empty string
(" "), error handling becomes "inactive" and therefore QUIT does not
trigger additional error handling.
When $ECODE is not set to the empty string, M error handling is active,
which also affects behaviour in some aspects of $STACK.
2 $EStack
$EStack
$ES[TACK] contains an integer count of the number of M virtual machine
stack levels that have been activated and not removed since the last
time $ESTACK was NEW'd.
A NEW $ESTACK saves the value of current $ESTACK and then sets its
value to zero (0). If $ESTACK has not been NEW'd in the current
execution path, $ESTACK=$STACK.
SET $ETRAP="QUIT:$ESTACK GOTO LABEL^ROUTINE"
$ESTACK maybe used as a flag to indicate error traps invoked in
particular stack levels needed to perform some different action(s).
$ESTACK can be most useful in setting up a layered error trapping
mechanism.
GT.M does not permit $ESTACK to be SET, however $ESTACK can be
NEWed.
2 $ETrap
$ETrap
$ET[RAP] contains a string value that GT.M invokes when an error occurs
during routine execution. When a process is initiated, but before any
commands are processed, the value of $ETRAP is empty string.
The value of this variable is the M[UMPS] code that gets executed when
an error occurs.
SET $ETRAP="QUIT:$ESTACK GOTO LABEL^ROUTINE"
The value of $ETRAP is changed with the SET command. Changing the value
of $ETRAP with the SET command initiates a new trap; it does not save
the old trap.
For more examples of the use of special variable $ETRAP, see the
function $STACK().
2 $Horolog
$Horolog
$H[OROLOG] contains a string value specifying the number of days since
"31 December, 1840," and the number of seconds since midnight of the
current day, separated by a comma (,).
At midnight, the piece of the string following the comma resets to zero
(0) and the piece preceding the comma increments by one (1). GT.M does
not permit the SET command to modify $HOROLOG.
Example:
GTM> WRITE $HOROLOG
Produces the result 58883,55555 at 3:25:55 pm on 20 March, 2002.
For further information on formatting $HOROLOG for external use, see
the section on $ZDATE().
2 $Io
$IO
$I[O] contains the name of the current device specified by the last USE
command. The M standard does not permit the SET command to modify $IO.
USE 0 produces the same $IO as USE $P[RINCIPAL], but $P is the
preferred construct.
2 $Job
$Job
$J[OB] contains the current process identifier.
$JOB is guaranteed to be unique for every concurrently operating
process on a system. However, operating systems reuse PIDs over time.
GT.M does not permit the SET command to modify $JOB.
Example:
LOOP0 FOR SET itm=$O(^tmp($J,itm)) Q:itm="" DO LOOP1
This uses $J as the first subscript in a temporary global to insure
that every process uses separate data space in the global ^tmp.
2 $Key
$Key
$K[EY] contains the string that terminated the most recent READ command
from the current device (including any introducing and terminating
characters). If no READ command s issued to the current device or if no
terminator is used, the value of $KEY is an empty string. However, when
input is terminated by typing a function key, the value of $KEY is
equal to the string of characters that is transmitted by that function
key.
The effect of a READ *glvn on $KEY is unspecified.
If a Character Set Profile input-transform is in effect, then this is
also applied to the value stored in $KEY.
2 $Principal
$Principal
$P[RINCIPAL] contains the absolute pathname of the principal (initial
$IO) device. $PRINCIPAL is an MDC Type A enhancement to standard M.
Input and output for a process may come from separate devices, namely,
the standard input and output. However, the M I/O model allows only one
device to be USEd (or active) at a time. When and image starts, GT.M
implicitly OPENs the standard input and standard output device(s) and
assigns the device(s) to $PRINCIPAL. For USE deviceparameters, it is
the standard input that determines the device type.
For an image invoked interactively, $PRINCIPAL is the user's terminal.
For an image invoked from a terminal by means of a shell script,
$PRINCIPAL is the shell script's standard input (usually the terminal)
and standard output (also usually the terminal) for output, unless the
shell redirects the input or output.
GT.M provides a mechanism for the user to create a name for $PRINCIPAL
in the shell before invoking GT.M. The environment variable
gtm_principal, if defined becomes a synonym for the actual device and
the value for $PRINCIPAL. $IO holds the same value as $PRINCIPAL. $ZIO
in this case, holds the fully expanded name of the actual device. Refer
to $ZIO section in this chapter for an example of its usage.
GT.M ignores a CLOSE specifying the principal device. GT.M does not
permit the SET command to modify $PRINCIPAL.
2 $Quit
$Quit
$Q[UIT] indicates whether the current block of code was called as an
extrinsic function or as a subroutine.
If $Q[UIT] contains 1 (when the current process-stack frame is invoked
by an extrinsic function), the QUIT would therefore require an
argument.
When a process is initiated, but before any commands are processed,
the value of $Q[UIT] is zero (0).
This special variable is mainly used in error-trapping conditions. Its
value tells whether the current DO level was reached by means of a
subroutine call (DO xxx) or by a function call (SET variable=$$xxx).
A typical way of exiting from an error trap is:
QUIT:$QUIT "" QUIT
GT.M does not permit $QUIT to be SET or NEWed.
2 $Reference
$Reference
$R[EFERENCE] contains the last global reference. Until the first global
reference is made by an M program, $REFERENCE contains the empty string
(""). This way it is useful in determining if the usage of a naked
reference is valid.
A typical way of using this is:
IF $REFERENCE="" QUIT "<undefined>"
$R[EFERENCE] being a read-only variable cannot be SET or NEW'd.
2 $STack
$STack
$ST[ACK] contains an integer value of zero (0) or greater indicating
the current level of M execution stack depth.
When a process is initiated but before any command is executed, the
value of $STACK is zero (0).
The difference between $STACK and $ESTACK is that $ESTACK may
appear as an argument of the NEW command. NEWing $ESTACK resets its
value to zero (0), and can be useful to set up a layered error
trapping mechanism.
The value of $STACK is "absolute" since the start of a GT.M. process,
whereas the value of $ESTACK is "relative" to the most recent
"anchoring point".
For examples on the use of special variable $STACK, refer to $STACK()
in the "Functions" chapter in this manual.
2 $Storage
$Storage
$S[TORAGE] contains an integer value specifying the number of free
bytes of address space remaining between the memory currently under
management by the process and the theoretical maximum available to the
process.
GT.M uses memory for code (instructions) and data. If the amount of
virtual memory available to the process exceeds 2,147,483,647 bytes, it
is reported as 2,147,483,647 bytes.
Instruction space starts out with the original executable image.
However, GT.M may expand instruction space by ZLINKing additional
routines.
Data space starts out with stack space that never expands, and pool
space which may expand. Operations such as opening a database or
creating a local variable may cause an expansion in pool space. GT.M
expands pool space in fairly large increments. Therefore, SETs of local
variables may not affect $STORAGE at all or may cause an apparently
disproportionate drop in its value.
Once a GT.M process adds either instruction or data space, it never
releases that space. However, GT.M does reuse process space made
available by actions such as KILLs of local variables. $STORAGE can
neither be SET or NEWed.
2 $SYstem
$SYstem
$SY[STEM] contains a string that identifies the executing M instance.
The value of $SYSTEM is a string that starts with a unique numeric code
that identifies the manufacturer. Codes are assigned by the MDC (MUMPS
Development Committee).
$SYSTEM in GT.M starts with "47" followed by a comma and the evaluation
of the environment variable gtm_sysid. If the name has no evaluation,
the value after the comma is gtm_sysid.
2 $Test
$Test
$T[EST] contains a truth value specifying the evaluation of the last IF
argument or the result of the last operation with timeout. If the last
timed operation timed out, $TEST contains FALSE (0); otherwise, it
contains TRUE (1).
$TEST serves as the implicit argument for ELSE commands and
argumentless IF commands.
M stacks $TEST when invoking an extrinsic and performing an
argumentless DO. After these operations complete with an implicit or
explicit QUIT, M restores the corresponding stacked value. Because,
with these two exceptions, $TEST reflects the last IF argument or
timeout result on a process wide basis. Use $TEST only in immediate
proximity to the operation that last updated it.
M routines cannot modify $TEST with the SET command.
Example:
IF x=+x DO ^WORK
ELSE SET x=0
The ELSE statement causes M to use the value of $TEST to determine
whether to execute the rest of the line. Because the code in routine
WORK may use IFs and timeouts, this use of $TEST is not recommended.
Example:
SET MYFLG=x=+x
IF MYFLG DO ^WORK
IF 'MYFLG SET x=0
This example introduces a local variable flag to address the problems
of the prior example. Note that its behavior results in the opposite
$TEST value from the prior example.
Example:
IF x=+x DO ^WORK IF 1
ELSE SET x=0
This example uses the IF 1 to ensure that the ELSE works counter to the
IF.
2 $TLevel
$TLevel
$TL[EVEL] contains a count of executed TSTARTs that are currently
unmatched by TCOMMITs. $TLEVEL is zero (0) when there is no TRANSACTION
in progress. When $TLEVEL is greater than one (>1), it indicates that
there are nested sub-transactions in progress. Sub-transactions are
always subject to the completion of the main TRANSACTION and cannot be
independently acted upon by COMMIT, ROLLBACK, or RESTART.
$TLEVEL can be used to determine whether there is a TRANSACTION in
progress and to determine the level of nesting of sub-transactions.
M routines cannot modify $TLEVEL with SET.
Example:
IF $TLEVEL TROLLBACK
This example performs a TROLLBACK if a transaction is in progress. A
statement like this should appear in any error handler used with
transaction processing. For more information on transaction processing
refer to the "General Language Features of M" chapter in GT.M
Programmer's Guide.
2 $TRestart
$TRestart
$TR[ESTART] contains a count of the number of times the current
TRANSACTION has been RESTARTed. A RESTART can be explicit (specified in
M as a TRESTART) or implicit (initiated by GT.M as part of its internal
concurrency control mechanism). When there is no TRANSACTION in
progress, $TRESTART is zero (0).
$TRESTART can be used by the application to limit the number of
RESTARTs, or to cause a routine to perform different actions during a
RESTART than during the initial execution.
GT.M does not permit the SET command to modify $TRESTART.
Example:
TRANS TSTART ():SERIAL
IF $TRESTART>2 WRITE !;"Access Conflict" QUIT
This example terminates the sub-routine with a message if the number of
RESTARTs exceeds 2.
For more information on transaction processing, refer to the section on
that topic in the "General Language Features of M" chapter in GT.M
Programmer's Guide.
2 $X
$X
$X contains an integer value ranging from 0 to 65,535, specifying the
horizontal position of a virtual cursor in the current output record.
$X=0 represents the left-most position of a record or row.
Every OPEN device has a $X. However, M only accesses $X of the current
device. Therefore, exercise care in sequencing USE commands and
references to $X.
Generally, GT.M increments $X for every character written to and read
from the current device. M format control characters, write filtering,
and the device WIDTH also have an effect on $X.
$X never equals or exceeds the value of the device WIDTH. Whenever it
reaches the value equal to the device WIDTH, it gets reset to zero (0).
GT.M follows the MDC Type A recommendation and permits an M routine to
SET $X. However, SET $X does not automatically issue device commands or
escape sequences to reposition the physical cursor.
For more information on $X, refer to the "Input/Output Processing"
chapter in GT.M Programmer's Guide.
2 $Y
$Y
$Y contains an integer value ranging from 0 to 65,535 specifying the
vertical position of a virtual cursor in the current output page. $Y=0
represents the top row or line.
Every OPEN device has a $Y. However, M only accesses $Y of the current
device. Therefore, exercise care in sequencing USE commands and
references to $Y.
When GT.M finishes the logical record in progress, it generally
increments $Y. GT.M recognizes the end of a logical record when it
processes certain M format control characters, or when the record
reaches its maximum size, as determined by the device WIDTH, and the
device is set to WRAP. The definition of "logical record" varies from
device to device. For an exact definition, see the sections on each
device type. Write filtering and the device LENGTH also have an effect
on $Y.
$Y never equals or exceeds the value of the device LENGTH. Whenever it
reaches the value equal to the device LENGTH, it gets reset to zero (0)
GT.M permits an M routine to SET $Y. However, SET $Y does not
automatically issue device commands or escape sequences to reposition
the physical cursor.
For more information on $Y, refer to the "Input/Output Processing"
chapter in GT.M Programmer's Guide.
2 $ZA
$ZA
$ZA contains a status determined by the last read on the device. The
value is a decimal integer with a meaning determined by the device as
follows:
For Terminal I/O:
0 Indicating normal termination of a read operation
1 Indicating a parity error
2 Indicating that the terminator sequence was too long
9 Indicating a default for all other errors
For Sequential Disk Files I/O:
0 Indicating normal termination of a read operation
9 Indicating a failure of a read operation
For Fifos I/O:
Decimal representing $JOB (identifier) of the process that wrote the
last message the current process read
$ZA refers to the status of the current device. Therefore, exercise
care in sequencing USE commands and references to $ZA.
GT.M does not permit the SET command to modify $ZA.
For more information on $ZA, refer to the "Input/Output Processing"
chapter in GT.M Programmer's Guide.
2 $ZB
$ZB
$ZB contains a string specifying the input terminator for the last
terminal READ. $ZB contains null and is not maintained for devices
other than terminals. $ZB may contain any legal input terminator, such
as <CR> (ASCII 13) or an escape sequence starting with <ESC> (ASCII
27), from zero (0) to 15 bytes in length. $ZB contains null for any
READ terminated by a timeout or any fixed-length READ terminated by
input reaching the maximum length.
$ZB contains the actual character string, not a sequence of numeric
ASCII codes.
Example:
SET zb=$ZB FOR i=1:1:$L(zb) WRITE !,i,?5,$A(zb,i)
This displays the series of ASCII codes for the characters in $ZB.
$ZB refers to the last READ terminator of the current device.
Therefore, exercise care in sequencing USE commands and references to
$ZB.
GT.M does not permit the SET command to modify $ZB.
For more information on $ZB, refer to the "Input/Output Processing"
chapter in GT.M Programmer's Guide.
2 $ZCMdline
$ZCMdline
$ZCM[DLINE] contains a string value specifying the "excess" portion of
the command line that invoked the GT.M process. By "excess" is meant
the portion of the command line that is left after GT.M has done all of
its command line processing. For example, a command line mumps -direct
extra1 extra2 causes GT.M to process the command line upto mumps
-direct and place the "excess" of the command line, that is "extra1
extra2" in $ZCMDLINE. $ZCMDLINE gives the M routine access to the shell
command line input.
Note that the actual user input command line might have been
transformed by the shell (for example, removing one level of quotes,
filename, and wildcard substituion, and so on.), and it is this
transformed command line that GT.M processes.
M routines cannot modify $ZCMDLINE.
Example:
$ cat > test.m
write " $ZCMDLINE=",$ZCMDLINE,!
quit
$ mumps -run test OTHER information
$ZCMDLINE=OTHER information
$
This creates the program test.m, which writes the value of $ZCMDLINE.
Note how the two spaces specified in OTHER information in the command
line gets transformed to just one space in OTHER information in
$ZCMDLINE due to the shell's pre-processing.
2 $ZCOmpile
$ZCOmpile
$ZCO[MPILE] contains a string value composed of one or more qualifiers
that control the GT.M compiler. Explicit ZLINKs and auto-ZLINKs use
these qualifiers as defaults for any compilations that they perform.
$ZCOMPILE is a read-write ISV, that is, it can appear on the left side
of the equal sign (=) in the argument to the SET command. A $ZCOMPILE
value has the form of a list of M command qualifiers each separated by
a space ( ).
When the environment variable gtmcompile is defined, GT.M initializes
$ZCOMPILE to the translation of gtmcompile. Otherwise GT.M initializes
$ZCOMPILE to null. Changes to the value of $ZCOMPILE during a GT.M
invocation only last for the current invocation and do not change the
value of the environment variable gtmcompile.
When $ZCOMPILE is null, GT.M uses the default M command qualifiers
-IGNORE, -LABEL=LOWER, -NOLIST, and -OBJECT. Refer to the "Program
Development Cycle" chapter in this manual for detailed descriptions of
the M command qualifiers.
Example:
$ setenv gtmcompile "-LIST -LENGTH=56 -SPACE=2"
$ gtm
GTM>WRITE $ZCOMPILE
-LIST -LENGTH=56 -SPACE=2
GTM>SET $ZCOMPILE="-LIST -NOIGNORE"
GTM>WRITE $ZCOMPILE
-LIST -NOIGNORE
GTM>ZLINK "A.m"
GTM>HALT
$ echo $gtmcompile
-LIST -LENGTH=56 -SPACE=2
This example uses the environment variable gtmcompile to set up
$ZCOMPILE. Then it modifies $ZCOMPILE with the SET command. The ZLINK
argument specifies a file with a .m extension (type), which forces a
compile. The compile produces a listing for routine A.m and does not
produce an object module if A.m contains compilation errors. After GT.M
terminates, the shell command echo $gtmcompile demonstrates that the
SET command did not change the environment variable.
2 $ZCstatus
$ZCstatus
$ZC[STATUS] holds the value of the status code for the last compilation
performed by a ZCOMPILE command.
GT.M does not permit the SET command to modify $ZSTATUS.
2 $ZDAteform
$ZDAteform
$ZDA[TEFORM] contains an integer value, specifying the output year
format of $ZDATE(). $ZDATEFORM can be modified using the SET command.
GT.M initializes $ZDATEFORM to the translation of the environment
variable gtm_zdate_form. If gtm_zdate_form is not defined, GT.M
initializes $ZDATEFORM to zero (0).
Refer to "Functions" and "M utility Routines" chapter in GT.M
Programmer's Guide for more details.
Example:
GTM>WRITE $ZDATEFROM
0
GTM>WRITE $ZDATE($H)
11/15/02
GTM>SET $ZDATEFORM=1
GTM>WRITE $ZDATE($H)
11/15/2002
2 $ZDirectory
$ZDirectory
$ZD[IRECTORY] contains the string value of the full path of the current
directory. Initially $ZDIRECTORY contains the default/current directory
from which the GT.M image/process was activated.
If the current directory does not exist at the time of GT.M process
activation, GT.M errors out.
Example:
GTM>WRITE $ZDIR
/usr/tmp
GTM>SET $ZDIR=".."
GTM>WRITE $ZDIR
/usr
This example displays the current working directory and changes $ZDIR
to the parent directory.
$ZDIRECTORY is a read-write Intrinsic Special Variable, that is, it can
appear on the left side of the equal sign (=) in the argument to a SET
command. If an attempt is made to set $ZDIRECTORY to a non-existent
directory specification, GT.M issues an error and keeps the value of
$ZDIRECTORY unchanged.
At image exit, GT.M restores the current directory to the directory
that was the current directory when GT.M was invoked even if that
directory does not exist.
2 $ZEDit
$ZEDit
$ZED[IT] holds the value of the status code for the last edit session
invoked by a ZEDIT command.
GT.M does not permit the SET or NEW command to modify $ZEDIT.
2 $ZEOf
$ZEOf
$ZEO[F] contains a truth-valued expression indicating whether the last
READ operation reached the end-of-file. $ZEOF equals TRUE (1) at EOF
and FALSE (0) at other positions.
GT.M does not maintain $ZEOF for terminal devices.
$ZEOF refers to the end-of-file status of the current device.
Therefore, exercise care in sequencing USE commands and references to
$ZEOF.
GT.M does not permit the SET or NEW command to modify $ZEOF.
For more information on $ZEOF, refer to the "Input/Output Processing"
chapter.
2 $ZError
$ZError
$ZE[RROR] is supposed to hold the application-specific error-code
corresponding to the GT.M error-code stored in $ECODE/$ZSTATUS (refer
to their description in this chapter).
$ZERROR contains a default value of "Unprocessed $ZERROR, see $ZSTATUS"
at process startup.
$ZERROR can be SET but not NEWed.
The mapping of a GT.M error-code to the application-specific error-code
is achieved as follows. Whenever GT.M encounters an error,
$ECODE/$ZSTATUS gets set first. It then invokes the code that $ZYERROR
(see description later in this chapter) points to if it is not null. It
is intended that the code invoked by $ZYERROR use the value of $ZSTATUS
to select or construct a value to which it SETs $ZERROR. If an error is
encountered by the attempt to execute the code specified in $ZYERROR,
GT.M sets $ZERROR to the error status encountered. If $ZYERROR is null,
GT.M does not change the value of $ZERROR. In all cases, GT.M proceeds
to return control to the code specified by $ZTRAP/$ETRAP or device
EXCEPTION whichever is applicable.
2 $ZGbldir
$ZGbldir
$ZG[BLDIR] contains the value of the current Global Directory filename.
When $ZGBLDIR specifies an invalid or inaccessible file, GT.M cannot
successfully perform database operations.
GT.M initializes $ZGBLDIR to the translation of the environment
variable gtmgbldir. If gtmgbldir is not defined, GT.M initializes
$ZGBLDIR to null. When $ZGBLDIR is null, GT.M constructs a file name
for the Global Directory using the name gtmgbldir and the extension
.gld in the current working directory. A $ZGBLDIR value may include an
environment variable.
$ZGBLDIR is a read-write Intrinsic Special Variable, (i.e., it can
appear on the left side of the equal sign (=) in the argument to the
SET command). SET $ZGBLDIR="" causes GT.M to assign $ZGBLDIR to the
translation of gtmgbldir if that environment variable is defined. If it
is not defined, then SET $ZGBLDIR="" causes GT.M to assign the string
gtmgbldir to $ZGBLDIR. This syntax specifies the file gtmgbldir.gld in
the current directory. GT.M permits $ZGBLDIR to be NEW'd.
SETting $ZGBLDIR also causes GT.M to attempt to open the specified
file. If the file name is invalid or the file is inaccessible, GT.M
triggers an error without changing the value of $ZGBLDIR.
To establish a value for $ZGBLDIR outside of M, use the appropriate
shell command to assign a translation to gtmgbldir. Defining gtmgbldir
provides a convenient way to use the same Global Directory during a
session where you repeatedly invoke and leave GT.M.
Changes to the value of $ZGBLDIR during a GT.M invocation only last for
the current invocation and do not change the value of gtmgbldir.
Example:
$ gtmgbldir=test.gld
$ export gtmgbldir
$ gtm
GTM> WRITE $zgbldir
/usr/dev/test.gld
GTM> SET $zgbldir="mumps.gld"
GTM> WRITE $zgbldir
mumps.gld
GTM> HALT
$ echo $gtmgbldir
test.gld
This example defines the environment variable gtmgbldir. Upon entering
GT.M Direct Mode, $ZGBLDIR has the value supplied by gtmgbldir. The SET
command changes the value. After the GT.M image terminates, the echo
command demonstrates that gtmgbldir was not modified by the M SET
command.
Example:
$ ls test.gld
test.gld not found
$ gtm
GTM> WRITE $zgbldir
/usr/dev/mumps.gld
GTM> set $zgbldir="test.gld"
%GTM-E-ZGBLDIRACC, Cannot access global directory
"/usr/dev/test.gld". Continuing with
/usr/dev/mumps.gld"
%SYSTEM-E-ENO2, No such file or directory
GTM> WRITE $zgbldir
/usr/dev/mumps.gld
GTM> halt
$
The SET command attempts to change the value of $ZGBLDIR to test.gld.
Because the file does not exist, GT.M reports an error and does not
change the value of $ZGBLDIR.
Attempting to restore an inaccessible initial Global Directory that
has been NEW'd, can cause an error.
2 $ZINTerrupt
$ZINTerrupt
$ZINT[ERRUPT] specifies the code to be XECUTE'd when an interrupt (for
example, through a MUPIP INTRPT) is processed. While a $ZINTERRUPT
action is in process, any additional interrupt signals are discarded.
When an interrupt handler is invoked, the current values of $REFERENCE
is saved and restored when the interrupt handler returns. The current
device ($IO) is neither saved nor restored.
GT.M permits the SET command to modify the value of $ZINTERRUPT.
If an interrupt handler changes the current IO device (via USE), it is
the responsibility of the interrupt handler to restore the current IO
device before returning. There are sufficient legitimate possibilities
why an interrupt routine would want to change the current IO device
(for example; daily log switching), that this part of the process
context is not saved and restored automatically.
The initial value for $ZINTERRUPT is taken from the UNIX environment
variable gtm_zinterrupt if it is specified, otherwise it defaults to
the following string:
IF $ZJOBEXAM()
The IF statement executes the $ZJOBEXAM function but effectively
discards the return value.
If the default value for $ZINTERRUPT is modified, no $ZJOBEXAM()
will occur unless the replacement value directly or indirectly
invokes that function. In other words, while $ZJOBEXAM() is part of
the interrupt handling by default, it is not an implicit part of
the interrupt handling.
3 Inter_Handl_GTM
Interrupt Handling in GT.M
The interrupt handler is executed by GT.M when on a statement boundary
or on an appropriate boundary in a potentially long running COMMAND (in
the same place as <CTRL>-C is recognized). If a GT.M process is in a
long running external call (for example; waiting in a message queue)
the interrupt handler cannot be driven immediately. The interrupt
request is recognized and the handler is driven after the external call
returns to GT.M and an appropriate execution boundary is reached.
Since sending an interrupt signal requires the sender to have
appropriate permissions from UNIX, the use of the interrupt facility
itself does not present any inherent security exposures. Nonetheless,
because the dump files created by the default action contain the values
of every local variable in the context at the time they are made,
inappropriate access to the dump files would constitute a security
exposure. Make sure the design and implementation of any interrupt
logic includes careful consideration to security issues.
If an error occurs while compiling the $ZINTERRUPT code, the action
taken depends on the process state at the time the interrupt was
received and the error handler is not invoked (the error handler is
invoked if an error occurs while executing the $ZINTERRUPT code). If
the GT.M process is at a direct mode prompt or is executing a direct
mode command (for example, a FOR loop), the error message is sent to
the user console along with the GTM-ERRWZINTR error (refer to the GT.M
Error and Message Recovery Manual). In addition, the GTM-ERRWZINTR
error is also sent to the operator log facility. IF the process is not
at a direct mode prompt or executing a direct mode command, the
GTM-ERRWZINTR message and the compiler error message are sent to the
operator log facility and nothing is displayed on the user's console.
In both cases, the interrupted process resumes execution.
If an error occurs during execution of the interrupt handler's stack
frame (before it calls anything), that error is prefixed with the
GTM-ERRWZINTR error. The error handler then executes normal error
processing associated with the module that was interrupted. Any other
errors that occur in code called by the interrupt handler are handled
by normal error handling.
The interrupt handler does not operate "outside" the current M
environment but rather within the environment of the process.
If a TP transaction is in progress (0<$TLEVEL), updates to globals are
not safe since a TP restart can be signaled at any time prior to the
transaction being committed - even after the interrupt handler returns.
A TP restart reverses all global updates and unwinds the M stack so it
is as if the interrupt never occurred. The interrupt handler is not
redriven as part of a transaction restart. Referencing (reading)
globals inside an interrupt handler can trigger a TP restart if a
transaction is active. When programming interrupt handling, either
discard interrupts when 0<$TLEVEL (forcing the interrupting party to
try again), or use local variables that are not restored by a TRESTART
to defer the interrupt action until after the final TCOMMIT.
Note that it is possible for the interrupt handler to be executed while
the process executing the M routine is holding the critical section for
one or more regions. Use of this feature may create temporary hangs or
pauses while the interrupt handler executes. For the default case where
the interrupt handler uses $ZJOBEXAM() to create a dump, the pause
duration depends on the number of local variables in the process at the
time of the dump and on the speed of the disk being written to. The
dumps are slower on a network-mounted disk than on a disk directly
connected to the local system. Any interrupt driven code should be
designed to account for this issue.
2 $ZINInterrupt
$ZINInterrupt
$ZINI[NTERRUPT] evaluates to 1 (TRUE) when a process is executing code
initiated by the interrupt mechanism, and otherwise 0 (FALSE).
GT.M does not permit the SET or NEW commands to modify $ZININTERRUPT.
2 $ZIO
$ZIO
$ZIO contains the translated name of the current device, in contrast to
$IO, which contains the name as specified by the USE command.
GT.M does not permit the SET or NEW command to modify $ZIO.
An example where $ZIO contains a value different from $IO is if the
environment variable gtm_principal is defined.
Example:
$ gtm_principal="foo"
$ export gtm_principal
GTM>WRITE $IO
foo
GTM>WRITE $ZIO
/dev/pts/8
Notice that $ZIO contains the actual terminal device name while $IO
contains the string pointed to by the environment variable
gtm_principal.
2 $ZJob
$ZJob
$ZJ[OB] holds the pid of the process created by the last JOB command
performed by the current process.
GT.M initializes $ZJOB to zero (0) at process startup. If the JOB
command fails to spawn a new job, GT.M sets $ZJOB to zero (0). Note
that because of the left to right evaluation order of M, using $ZJOB in
the jobparameter string results in using the value created by the last,
rather than the current JOB command, which is not likely to match
common coding practice.
GT.M does not permit the SET or NEW command to modify $ZJOB.
2 $ZLevel
$ZLevel
$ZL[EVEL] contains an integer value indicating the "level of nesting"
caused by DO commands, XECUTE commands, and extrinsic functions in the
M invocation stack.
$ZLEVEL has an initial value of one (1) and increments by one with each
DO, XECUTE or extrinsic function. Any QUIT that does not terminate a
FOR loop decrements $ZLEVEL. ZGOTO may also reduce $ZLEVEL. In
accordance with the M standard, a FOR command does not increase
$ZLEVEL. M routines cannot modify $ZLEVEL with the SET or NEW commands.
Use $ZLEVEL in debugging or in an error-handling mechanism to capture a
level for later use in a ZGOTO argument.
Example:
GTM>ZPRINT ^ZLEV
A DO B
WRITE X,!
QUIT
B GOTO C
QUIT
C DO D
QUIT
D SET X=$ZLEVEL
QUIT
GTM>DO ^ZLEV
4
This program, executed from Direct Mode, produces a value of 4 for
$ZLEVEL. If you run this program from the shell, the value of $ZLEVEL
is three (3).
2 $ZMAXTPTIme
$ZMAXTPTIme
$ZMAXTPTI[ME] contains an integer value indicating the time duration
GT.M should wait for the completion of all activities fenced by the
current transaction's outermost TSTART/TCOMMIT pair.
$ZMAXTPTIME can be SET but cannot be NEWed.
The initial value of $ZMAXTPTIME is zero (0) seconds, which indicates
"no timeout" (unlimited time). The value of $ZMAXTPTIME when a
transaction's outermost TSTART operation executes determines the
timeout setting for that transaction.
When a $ZMAXTPTIME expires, GT.M executes the $ETRAP/$ZTRAP exception
handler currently in effect.
Negative values of $ZMAXTPTIME are also treated as "no timeout".
Timeouts apply only to the outermost transaction, that is,
$ZMAXTPTIME has no effect when TSTART is nested within another
transaction.
Example:
Test ;testing TP timeouts
set $ZMAXTPTIME=6,^X=0,^Y=0,^Z=0
write "Start with $ZMAXTPTIME=",$ZMAXTPTIME,":",!
for sleep=3:2:9 do
. set retlvl=$zl
. do longtran ;ztrap on longtran
;continues execution
;on next line
. write "(^X,^Y)=(",^X,",",^Y,")",!
write !,"Done TP Timeout test.",!
quit
longtran ;I/O in TP doesn't get rolled back
set newzt="set $ZT="""" ";avoid recursive ZTRAP
set $ZT=newzt_" goto err"
tstart ():serial ;plain tstart works as well
set ^X=1+^X
write !,"^X=",^X,",will set ^Y to ",sleep
write " in ",sleep," seconds..."
hang sleep
set ^Y=sleep
write "^Y=",^Y
tcommit
write "...committed.",!
quit
err ;
set $ZT=""
write !,"In $ZTRAP handler. Error was: "
write !," ",$zstatus
if $TLEVEL do ;test allows handler use outside of TP
. trollback
. write "Rolled back transaction."
write !
zgoto retlvl
Results:
Start with $ZMAXTPTIME=6:
^X=1,will set ^Y to 3 in 3 seconds...^Y=3...committed.
^X=2,will set ^Y to 5 in 5 seconds...^Y=5...committed.
^X=3,will set ^Y to 7 in 7 seconds...
In $ZTRAP handler. Error was:
150377322,longtran+7^tptime,%GTM-E-TPTIMEOUT, Transaction timeoutRolled
back transaction.
^X=3,will set ^Y to 9 in 9 seconds...
In $ZTRAP handler. Error was:
150377322,longtran+7^tptime,%GTM-E-TPTIMEOUT, Transaction timeoutRolled
back transaction.
Done TP Timeout test.
2 $ZMOde
$ZMOde
$ZMO[DE] contains a string value indicating the process execution mode.
The mode can be:
o INTERACTIVE
o OTHER
M routines cannot modify $ZMODE.
Example:
GTM> WRITE $ZMODE
INTERACTIVE
This displays the process mode.
2 $ZPOSition
$ZPOSition
$ZPOS[ITION] contains a string value specifying the current entryref,
where entryref is [label][+offset]^routine, and the offset is evaluated
from the closest preceding label.
GT.M does not permit the SET or NEW commands to modify $ZPOSITION.
Example:
GTM>WRITE !,$ZPOS,! ZPRINT @$ZPOS
This example displays the current location followed by the source code
for that line.
2 $ZPROMpt
$ZPROMpt
$ZPROM[PT] contains a string value specifying the current Direct Mode
prompt. By default, GTM> is the Direct Mode prompt. M routines can
modify $ZPROMPT by means of a SET command. $ZPROMPT cannot exceed 16
characters. If an attempt is made to assign $ZPROMPT to a longer
string, only the first 16 characters will be taken.
Example:
GTM>SET $ZPROMPT="NEWZPROMPT>"
NEWZPROMPT>
This example changes the GT.M prompt to be NEWZPROMPT
2 $ZROutines
$ZROutines
$ZRO[UTINES] contains a string value specifying a directory or list of
directories containing object files. Each object directory may also
have an associated directory, or list of directories, containing the
corresponding source files. These directory lists are used by certain
GT.M functions, primarily auto-ZLINK, to locate object and source
files. The order in which directories appear in a given list determines
the order in which they are searched for the appropriate item.
Searches that use $ZROUTINES treat files as either object or source
files. GT.M treats files with an extension of .o as object files and
files with an extension of .m as source files.
Paths used in $ZROUTINES to locate routines must not include
embedded spaces, as $ZROUTINES uses spaces as delimiters.
3 Est_Val_frm_gtmroutines
Establishing the Value from gtmroutines
When the environment variable gtmroutines is defined, GT.M initializes
$ZROUTINES to the value of gtmroutines. Otherwise, GT.M initializes
$ZROUTINES to a null value. When $ZROUTINES is null, GT.M attempts to
locate all source and object files in the current working directory.
$ZROUTINES="" is equivalent to $ZROUTINES=".".
Commands or functions such as DO, GOTO, ZGOTO, ZBREAK, ZPRINT, and
$TEXT may auto-ZLINK and thereby indirectly use $ZROUTINES. If their
argument does not specify a directory, ZEDIT and explicit ZLINK use
$ZROUTINES. ZPRINT and $TEXT use $ZROUTINES to locate a source file if
GT.M cannot find the source file pointed to by the object file. For
more information on ZLINK and auto-ZLINK, refer to the "Program
Development Cycle" and "Commands" chapters in GT.M Programmer's Guide.
3 Set_Val_for_$ZRO
Setting a Value for $ZROUTINES
$ZRO[UTINES] is a read-write Intrinsic Special Variable, so M can also
SET the value.
By default, each directory entry in $ZROUTINES is assumed to contain
both object and source files. However, each object directory may have
an associated directory or list of directories to search for the
corresponding source files. This is done by specifying the source
directory list, in parentheses, following the object directory
specification.
If the command specifies more than one source directory for an object
directory, the source directories must be separated by spaces, and the
entire list must be enclosed in parentheses ( ) following the object
directory-specification. If the object directory should also be
searched for source, the name of that directory must be included in the
parentheses, (usually as the first element in the list).
Directory-specifications may also include empty parentheses, directing
GT.M to proceed as if no source files exist for objects located in the
qualified directory.
To set $ZROUTINES outside of M, use the appropriate shell command to
set gtmroutines. Because gtmroutines is a list, enclose the value in
quotation marks (" ").
Changes to the value of $ZROUTINES during a GT.M invocation only last
for the current invocation, and do not change the value of gtmroutines.
Directory specifications may include an environment variable. When GT.M
SETs $ZROUTINES, it translates all environment variables and verifies
the syntax and the existence of all specified directories. If
$ZROUTINES is set to an invalid value, GT.M generates a run-time error
and does not change the value of $ZROUTINES. Because the environment
variables are translated when $ZROUTINES is set, any changes to their
definition have no effect until $ZROUTINES is set again.
3 $ZRO_Examples
$ZROUTINES Examples
Example:
GTM> s $zroutines=".(../src) $gtm_dist"
This example directs GTM to look for object modules first in your
current directory, then in the distribution directory that contains the
percent routines. GT.M locates sources for objects in your current
directory in the sibling /src directory.
Example:
$ gtmroutines="/usr/jones /usr/smith"
$ export gtmroutines
$ gtm
GTM> write $zroutines
"/usr/jones /usr/smith"
GTM> set $zro="/usr/jones/utl /usr/smith/utl"
GTM> write $zroutines
"/usr/jones/utl /usr/smith/utl"
GTM> halt
$ echo $gtmroutines
/usr/jones /usr/smith
This example defines the environment variable gtmroutines. Upon
entering GT.M Direct Mode $zroutines has the value supplied by
gtmroutines. The SET command changes the value. When the GT.M image
terminates, the shell echo command demonstrates that gtmroutines has
not been modified by the M SET command.
Example:
GTM> SET $ZRO=". /usr/smith"
This example sets $zroutines to a list containing two directories.
Example:
GTM> set $zro="/usr/smith(/usr/smith/tax /usr/smith/fica)"
This example specifies that GT.M should search the directory /usr/smith
for object files, and the directories /usr/smith/tax and
/usr/smith/fica for source files. Note that in this example. GT.M does
not search /usr/smith for source files.
Example:
GTM> set $zro="/usr/smith(/usr/smith /usr/smith/tax /usr/smith/fica)"
This example specifies that GT.M should search the directory /usr/smith
for object files and the directories /usr/smith/tax and /usr/smith/fica
for source files. Note that the difference between this example and the
previous one is that GT.M searches /usr/smith for both object and
source files.
Example:
GTM> set $zro="/usr/smith /usr/smith/tax()
/usr/smith/fica"
This specifies that GT.M should search /usr/smith and /usr/smith/fica
for object and source files. However, because the empty parentheses
indicate directories searched only for object files, GT.M does not
search /usr/smith/tax for source files.
Omitting the parentheses indicates that GT.M can search the directory
for both source and object files. $ZROUTINES=/usr/smith is equivalent
to $ZROUTINES=/usr/smith(/usr/smith).
3 $ZRO_Search_Types
$ZROUTINES Search Types
GT.M uses $ZRO[UTINES] to perform three types of searches:
o Object-only when the command or function using $ZROUTINES requires
a .o file extension.
o Source-only when the command or function using $ZROUTINES requires
a file extension other than .o.
o Object-source match when the command or function using $ZROUTINES
does not specify a file extension.
An explicit ZLINK that specifies a non .o extension is considered as a
function that has not specified a file extension for the above
searching purposes.
All searches proceed from left to right through $ZROUTINES. By default,
GT.M searches directories for both source and object files. GT.M
searches directories followed by empty parentheses ( ) for object files
only. GT.M searches directories in parentheses only for source files.
Once an object-matching search locates an object file, the source
search becomes limited. If the directory containing the object file has
an attached parenthetical list of directories, GT.M only searches the
directories in the attached list for matching source files. If the
directory containing the object files does not have following
parentheses, GT.M restricts the search for matching source files to the
same directory. If the object module is in a directory qualified by
empty parentheses, GT.M cannot perform any operation that refers to the
source file.
3 $ZRO_Search_Ex
$ZROUTINES Search Examples
This section describes a model for understanding $ZROUTINES operations
and the illustrating examples, which may assist you if you wish to
examine the topic closely.
You may think of $ZROUTINES as supplying a two dimensional matrix of
places to look for files. The matrix has one or more rows. The first
row in the matrix contains places to look for object and the second and
following rows contain places to look for source. Each column
represents the set of places that contain information related to the
object modules in the first row of the column.
Example:
GTM> s $zro=". /usr/smi/utl() /usr/jon/utl
(/usr/jon/utl/so /usr/smi/utl)"
3 Sh_Lib_FileSpec_in_$ZRO
Shared Library File Specification in $ZROUTINES
The $ZROUTINES ISV allows individual UNIX shared library file names to
be specified in the search path. During a search for auto-ZLINK, when a
shared library is encountered, it is probed for a given routine and, if
found, that routine is linked/loaded into the image. During an explicit
ZLINK, all shared libraries in $ZROUTINES are ignored and are not
searched for a given routine.
Currently GT.M supports this feature on Tru64 operating system, and
plans to support other UNIX operating system in near future.
$ZROUTINES syntax contains a file-specification indicating shared
library file path. GT.M does not require any designated extension for
the shared library component of $ZROUTINES. Any file specification that
does not name a directory is treated as shared library. However, it is
recommended that the extension commonly used on a given platform for
shared library files be given to any GT.M shared libraries. (Refer to
the following section on "Linking GT.M Shared Images"). A shared
library component cannot specify source directories. GT.M reports an
error at an attempt to associate any source directory with a shared
library in $ZROUTINES.
The following traits of $ZROUTINES help support shared libraries:
o The $ZROUTINES search continues to find objects in the first place,
processing from left to right, that holds a copy; it ignores any
copies in subsequent locations. However, now for auto-ZLINK, shared
libraries are accepted as object repositories with the same ability
to supply objects as directories.
o Explicit ZLINK, never searches Shared Libraries. This is because
explicit ZLINK is used to link a newly created routine or re-link a
modified routine and there is no mechanism to load new objects into
an active shared library.
o ZPRINT and $TEXT() of the routines in a shared library, read source
file path from the header of the loaded routine. If the image does
not contain the routine, an auto-ZLINK is initiated. If the source
file path recorded in the routine header when the module was
compiled cannot be located, ZPRINT and $TEXT() initiate a search
from the beginning of $ZROUTINES, skipping over the shared library
file specifications. If the located source does not match the code
in image (checked via checksum), ZPRINT generates an object-source
mismatch status and $TEXT() returns a null string.
o ZEDIT, when searching $ZROUTINES, skips shared libraries like
explicit ZLINK for the same reasons. $ZSOURCE ISV is implicitly set
to the appropriate source file.
For example, if libshare.so is built with foo.o compiled from
./shrsrc/foo.m, the following commands specify that GT.M should search
the library ./libshare.so for symbol foo when do ^foo is encountered.
GTM>SET $ZROUTINES="./libshare.so ./obj(./shrsrc)"
GTM>DO ^foo ;auto-ZLINK foo - shared
GTM>ZEDIT "foo" ;edit ./shrsrc/foo.m
GTM>W $ZSOURCE,! ;prints foo
GTM>ZPRINT +0^foo ;issues a source-object mismatch status TXTSRCMAT
error message
GTM>ZLINK "foo" ;re-compile ./shrsrc/foo.m to generate ./obj/foo.o.
GTM>W $TEXT(+0^foo) ;prints foo
Note that ZPRINT reports an error, as foo.m does not match the routine
already linked into image. Also note that, to recompile and re-link the
ZEDITed foo.m, its source directory needs to be attached to the object
directory [./obj] in $ZROUTINES. The example assumes the shared library
(libshare.so) has been built using shell commands. The procedure to
build a shared library from a list of GT.M generated object (.o) files
is detailed in the following section on "Linking GT.M Shared Images".
4 Link_GTM_Sh_Image
Linking GT.M Shared Images
Following are the steps (UNIX system commands, and GT.M commands) that
need to be taken to use GT.M shared image linking with $ZROUTINES.
5 Comp_SrcFile_to_ObjFile
Compile Source (.m) Files to Object (.o) Files
In order to share M routines, GT.M generates objects (.o) with position
independent code, a primary requirement for shared libraries. All
objects must be generated by a release of GT.M that supports shared
binaries linking.
5 Creat_ShLib_from_ObjFile
Create a Shared Library from Object (.o) Files
On each UNIX platform, the native linker ld provides command line
options to create a shared library from a list of .o files. The
specific ld options vary depending on the platform.
Although GT.M does not require a specific file extension for shared
libraries, it is recommended that the conventional extension (.so on
Tru64) be used on a given platform. For example, the following Tru64
linker command
$ ld -shared -taso -o libabc.so a.o b.o c.o -lc
creates a shared library libabc.so from GT.M object files a.o, b.o and
c.o. The flag -taso directs the linker to generate 32-bit addressable
Shared Library. Without this option, Tru64 UNIX ld generates a 64-bit
addressable shared library by default. Even though GT.M can
successfully load 64-bit shared library, Sanchez recommends the use of
the -taso option for best compatibility with the GT.M memory model.
Notes on Tru64 UNIX linker:
o The linker (ld) may have a limit on the number of object files that
it can accept on the command line. If ld fails to read all objects
from the command line, users are recommended to use -input to
specify a text file <command-file> that contains all object files
as if they were specified on the command line.
o When creating a shared library, Sanchez suggests linking with the C
library (-lc at the end of link line) to prevent ld from reporting
various undefined-symbol warnings. These undefines are not relevant
to the use of the GT.M shared library routines but linking with the
C library eliminates the linker warning messages.
o See ld manual pages (UNIX shell command - man ld) for more details
of linker options.
5 Est_$ZRO_frm_gtmroutines
Establish $ZROUTINES from gtmroutines
When the UNIX environment variable gtmroutines is defined, GT.M
initializes $ZROUTINES to the value of gtmroutines. The $ZROUTINES ISV
can also be modified using SET command.
Example:
$ gtmroutines="./libabc.so ./obj(./src)"
$ export gtmroutines
$ mumps -direct
GTM>write $ZROUTINES,! ;writes "./libabc.so ./obj(./src)"
GTM> do ^a ;runs ^a from libabc.so
GTM> do ^b ;runs ^b from libabc.so
GTM> do ^c ;runs ^c from libabc.so
GTM> halt
$
2 $ZSOurce
$ZSOurce
$ZSO[URCE] contains a string value specifying the default pathname for
the ZEDIT and ZLINK commands. ZEDIT or ZLINK without an argument is
equivalent to ZEDIT/ZLINK $ZSOURCE.
$ZSOURCE initially contains the null string. When ZEDIT and ZLINK
commands have a pathname for an argument, they implicitly set $ZSOURCE
to that argument. This ZEDIT/ZLINK argument can include a full pathname
or a relative one. A relative path could include a file in the current
directory, or the path to the file from the current working directory.
In the latter instance, do not include the slash before the first
directory name. $ZSOURCE will prefix the path to the current working
directory including that slash.
The file name may contain a file extension. If the extension is .m or
.o, $ZSOURCE drops it. The ZEDIT command accepts arguments with
extensions other than .m or .o. $ZSOURCE retains the extension when
such arguments are passed.
If $ZSOURCE contains a file with an extension other than .m or .o,
ZEDIT processes it but ZLINK returns an error message
$ZSOURCE is a read-write Intrinsic Special Variable, (i.e., it can
appear on the left side of the equal sign (=) in the argument to the
SET command). A $ZSOURCE value may include an environment variable.
Example:
GTM> ZEDIT "subr.m"
.
.
GTM> WRITE $ZSOURCE
subr
Example:
GTM> ZEDIT "test"
.
.
.
GTM> WRITE $ZSOURCE
test
Example:
GTM> ZEDIT "/usr/smith/report.txt"
.
.
.
GTM> WRITE $ZSOURCE
/usr/smith/report.txt
Example:
GTM> ZLINK "BASE.O"
.
.
.
GTM> WRITE $ZSOURCE
BASE
2 $ZStatus
$ZStatus
$ZS[TATUS] contains a string value specifying the error condition code
and location of the last exception condition that occurred during
routine execution.
GT.M maintains $ZSTATUS as a string consisting of three or more
substrings. The string consists of the following:
o An error message number as the first substring.
o The entryref of the line in error as the second substring; a comma
(,) separates the first and second substrings.
o The message detail as the third substring. The format of this is a
percent sign (%) identifying the message facility, a hyphen (-)
identifying the error severity, another hyphen identifying the
message identification followed by a comma (,), which is followed
by the message text if any:
Format: %<FAC>-<SEV>-<ID>, <TEXT>
Example: %GTM-E-DIVZERO, Attempt to divide by zero
GT.M sets $ZSTATUS when it encounters errors during program execution,
but not when it encounters errors in a Direct Mode command.
$ZSTATUS is a read-write Intrinsic Special Variable, (i.e., it can
occur on the left side of the equal sign (=) in the argument to the SET
command). While it will accept any string, Sanchez Computer Associates
recommends setting it to null. M routines cannot modify $ZSTATUS with
the NEW command.
Example:
GTM> WRITE $ZSTATUS
150373110,+1^MYFILE,%GTM-E-DIVZERO,
Attempt to divide by zero
This example displays the status generated by a divide by zero (0).
2 $ZSTep
$ZSTep
$ZST[EP] contains a string value specifying the default action for the
ZSTEP command. $ZSTEP provides the ZSTEP action only when the ZSTEP
command does not specify an action.
$ZSTEP initially contains the string "B" to enter direct mode. $ZSTEP
is a read-write Intrinsic Special Variable, (i.e., it can appear on the
left side of the equal sign (=) in the argument to the SET command).
Example:
GTM> WRITE $ZSTEP
B
GTM>
This example displays the current value of $ZSTEP, which is the
default.
Example:
GTM> SET $ZSTEP="ZP @$ZPOS B"
This example sets $ZSTEP to code that displays the contents of the next
line to execute, and then enters Direct Mode.
2 $ZSYstem
$ZSYstem
$ZSY[STEM] holds the value of the status code for the last subprocess
invoked with the ZSYSTEM command.
2 $ZTExit
$ZTExit
$ZTE[XIT] contains a string value that controls the GT.M interrupt
facility at the transaction commit or rollback. At each outermost
TCOMMIT or TROLLBACK, If +$ZTEXIT evaluates to non-zero (TRUE), then
$ZINTERRUPT is XECUTEd after completing the commit or rollback.
$ZTEXIT is a read-write ISV, that is, it can appear on the left side of
the equal sign (=) in the argument to the SET command. M routines
cannot NEW $ZTEXIT. GT.M initializes $ZTEXIT to null at the process
startup. Note that the changes to the value of $ZTEXIT during a GT.M
invocation last for the entire duration of the process, so it is the
applications responsibility to reset $ZTEXIT after $ZINTERRUPT is
delivered in order to turn off redelivering the interrupt each every
subsequent transaction commit or rollback.
Example:
ztran.m
foo ;
set $ztexit=1
set $zinterrupt="d ^throwint"
tstart ()
for i=1:1:10 do
. set ^ACN(i,"bal")=i*100
tstart ()
do ^throwint
do ^proc
tcommit:$tlevel=2
for i=1:1:10 do
. set ^ACN(i,"int")=i*0.05
do ^srv
if $tlevel trollback
do ^exc
set $zte="",$zint=""
quit
bar ;
write "Begin Transaction",!
set $zte=1
tstart ()
i '$zsigproc($j,$ztrnlnm("sigusrval")) w "interrupt sent...",!!
for i=1:1:4 set ^B(i)=i*i
tcommit
write "End Transaction",!
do ^srv
quit
throwint.m
thrint
set $zint="write !,""interrupt occurred at :
"",$stack($stack-1,""PLACE""),! set $zte=1"
if '$zsigproc($j,$ztrnlnm("sigusrval")) write "interrupt sent to
process"
write "***************************************",!!
quit
Example:
GTM>d foo^ztran
interrupt sent to process
interrupt occurred at : thrint+3^throwint
***************************************
interrupt occurred at : foo+13^ztran
GTM>
In the above call to foo^ztran, the interrupt handler is a user-defined
routine, throwint. The process is sent a signal (SIGUSR1), and
$ZINTERRUPT is executed. At the outermost trollback, the interrupt is
rethrown, causing $ZINTERRUPT to be executed again.
Example:
GTM>w $zint
IF $ZJOBEXAM()
GTM>zsy "ls GTM*"
ls: No match.
GTM>d bar^ztran
Begin Transaction
interrupt sent...
End Transaction
GTM>zsy "ls GTM*"
GTM_JOBEXAM.ZSHOW_DMP_22551_1 GTM_JOBEXAM.ZSHOW_DMP_22551_2
GTM>
This uses the default value of $ZINTERRUPT to service interrupts issued
to the process. The $ZJOBEXAM function executes a ZSHOW "*", and stores
the output in each GTM_ZJOBEXAM_ZSHOW_DMP for the initial interrupt,
and at tcommit when the interrupt is rethrown.
2 $ZTrap
$ZTrap
$ZT[RAP] contains a string value that GT.M XECUTEs when an error occurs
during routine execution.
The following discussion assumes that $ETRAP error handling is
simultaneously not in effect (that is, $ETRAP="").
When the $ZTRAP variable is not null, GT.M executes $ZTRAP at the
current level. The $ZTRAP variable has the initial value of "B," and
puts the process in Direct Mode when an error condition occurs. If the
value of $ZTRAP is null (""), an exception causes the image to run-down
with the condition code associated with the exception. If $ZTRAP
contains invalid source code, GT.M displays an error message and puts
the process into Direct Mode.
$ZTRAP is a read-write Intrinsic Special Variable, (i.e., it can appear
on the left side of the equal sign (=) in the argument to the SET
command).
$ZTRAP may also appear as an argument to an inclusive NEW command. NEW
$ZTRAP causes GT.M to set $ZTRAP to null ($ZTRAP="") and to stack the
old value of $ZTRAP. When the program QUITs from the invocation level
where the NEW occurred, GT.M restores the value previously stacked by
the NEW. NEW $ZTRAP provides nesting of $ZTRAP. Because $ZTRAP=""
terminates the image when an error occurs, SET $ZTRAP= generally
follows immediately after NEW $ZTRAP. You may use this technique to
construct error handling strategies corresponding to the nesting of
your programs. If the environment variable gtm_ztrap_new evaluates to
boolean TRUE (case insensitive string "TRUE", or case insensitive
string "YES", or a non-zero number), $ZTRAP is NEWed when $ZTRAP is
SET; otherwise $ZTRAP is not stacked when it is SET.
QUIT from a $ZTRAP terminates the level at which the $ZTRAP was
activated.
Keep $ZTRAP simple and put complicated logic in another routine. If the
action specified by $ZTRAP results in another run-time error before
changing the value of $ZTRAP, GT.M invokes $ZTRAP until it exhausts the
process stack space, terminating the image. Carefully debug exception
handling.
Example:
GTM> S $ZTRAP="ZP @$ZPOS B"
This example modifies $ZTRAP to display source code for the line where
GT.M encounters an error before entering Direct Mode.
There are four accepted behavioural forms of $ZTRAP controlled by the
UNIX environment variable gtm_ztrap_form. If gtm_ztrap_form is defined
to "code" (or not defined to one of the subsequently described values),
then GT.M treats $ZTRAP as code and handles it as previously described
in the documentation.
The four different behavioural forms of gtm_ztrap_form are:
o entryref - If gtm_ztrap_form evaluates to "entryref" then GT.M
treats it as an entryref argument to an implicit GOTO command.
o adaptive - If gtm_ztrap_form evaluates to "adaptive" then if
$ZTRAP does not compile to valid M code, then $ZTRAP is treated as
just described for "entryref." Since there is little ambiguity,
code and entryref forms of $ZTRAP can be intermixed in the same
application.
Note that GT.M attempts to compile $ZTRAP before evaluating $ZTRAP as
an entryref. Since GT.M allows commands without arguments such as QUIT,
ZGOTO, or HANG as valid labels, be careful not to use such keywords as
labels for error handling code in "adaptive" mode.
o pope[ntryref] / popa[daptive] - If gtm_ztrap_form evaluates to
"POPE[NTRYREF]" or "POPA[DAPTIVE]" (case insensitive) and $ZTRAP
value is in the form of entryref, GT.M unwinds the M stack from the
level at which an error occurred to (but not including) the level
at which $ZTRAP was last SET. Then, GT.M transfers control to the
entryref in $ZTRAP at the level where the $ZTRAP value was SET. If
the UNIX environment variable gtm_zyerror is defined to a valid
entryref, GT.M transfers control to the entryref specified by
GTM_ZYERROR (with an implicit DO) after unwinding the stack and
before transferring control to the entyref specified in $ZTRAP.
2 $ZVersion
$ZVersion
$ZV[ERSION] contains a string value specifying the currently installed
GT.M. $ZV[ERSION] is a space-delimited string with four pieces
described below:
o The M product name, for example "GT.M".
o The M product version identifier; the format is: the capital letter
"V" followed by the major version number, then a period (.),
followed by the minor version number, then a patch number.
o The host operating system name and optional version identifier;
this identifier is only included if different versions of the OS
support different, compatible versions of the M product.
o The host hardware designation and optional chipset identifier; this
identifier is only included if different versions of the hardware
support different compatible versions of the M product.
M routines cannot modify $ZVERSION.
Example:
GTM> WRITE $ZVERSION
GT.M V4.3-001B AIX RS6000
This example displays the current version identifier for GT.M.
2 $ZYERror
$ZYERror
$ZYER[ROR] is a read/write ISV that contains a string value pointing to
an entryref. After GT.M encounters an error, if $ZYERROR is set a
non-null value, GT.M invokes the routine at the entryref specified by
$ZYERROR with an implicit DO. It is intended that the code invoked by
$ZYERROR use the value of $ZSTATUS to select or construct a value to
which it SETs $ZERROR. If $ZYERROR is not a valid entryref or if an
error occurs while executing the entryref specified by $ZYERROR, GT.M
SETs $ZERROR to the error status encountered. GT.M then returns control
to the M code specified by $ETRAP/$ZTRAP or device EXCEPTION.
$ZYERROR is implicitly NEWed on entry to the routine specified by
$ZYERROR. However, if GT.M fails to compile, GT.M does not transfer
control to the entryref specified by $ZYERROR.
GT.M permits $ZYERROR to be modified by the SET and NEW commands.
1 In_Out_Processing
Input Output Processing
OPEN, USE, and CLOSE commands accept deviceparameters, which are
keywords that permit an GT.M program to control the device state. Some
deviceparameters accept arguments, and some require them. The current
ANSI standard for GT.M does not define the deviceparameters for all
devices.
2 IO_ISV
I/O Intrinsic Special Variables
GT.M intrinsic special variables provide a means of communication
between a device and its device driver and GT.M routines. These
variables allow a GT.M routine to manage the I/O with a particular
device.
3 Device_Nam_Var
Device Name Variables
GT.M provides three intrinsic special variables that identify devices.
4 $IO
$IO
$I[O] contains the name of the current device specified by the last USE
command. The M standard does not permit a SET command to modify $IO.
USE produces the same $IO as USE $PRINCIPAL, but $P is the preferred
construct.
4 $Principal
$Principal
$P[RINCIPAL] contains the absolute pathname of the principal (initial
$IO) device.
Input and output for a process may come from separate devices, namely,
the standard input and output. However, the GT.M I/O model allows only
one device to be USEd (or active) at a time. When an image starts, GT.M
implicitly OPENs the standard input and standard output device(s) and
assigns the device(s) to $PRINCIPAL. For USE deviceparameters, it is
the standard input that determines the device type.
For an image invoked interactively, $PRINCIPAL is the user's terminal.
For an image invoked from a terminal by a shell script, $PRINCIPAL is
the shell script's standard input (usually the terminal) and standard
output (also usually the terminal), unless the shell redirects the
input or output.
GT.M ignores a CLOSE command specifying the principal device. GT.M does
not permit a SET command to modify $PRINCIPAL.
4 $ZIO
$ZIO
$ZIO contains the translated name of the current device, in contrast to
$IO, which contains the name as specified by the USE command.
3 Cur_Position_Var
Cursor Position Variables
GT.M provides two intrinsic special variables for determining the
virtual cursor position. $X refers to the current column, while $Y
refers to the current row.
4 $X
$X
$X contains an integer value ranging from 0 to 65,535, specifying the
horizontal position of a virtual cursor in the current output record.
$X=0 represents the left-most position of a record or row.
Every OPENed device has a $X. However, GT.M only has access to $X of
the current device. Therefore, be careful when sequencing USE commands
and references to $X.
Generally, GT.M increments $X for every character written to and read
from the current device. GT.M format control characters, FILTER, and
the device WIDTH and WRAP also have an effect on $X.
SET $X does not automatically issue device commands or escape sequences
to reposition the physical cursor.
4 $Y
$Y
$Y contains an integer value ranging from 0 to 65,535, specifying the
vertical position of a virtual cursor in the current output record.
$Y=0 represents the top row or line.
Every OPEN device has a $Y. However, GT.M only accesses $Y of the
current device. Therefore, be careful when sequencing USE commands and
references to $Y.
When GT.M finishes the logical record in progress, it generally
increments $Y. GT.M recognizes the end of a logical record when it
processes certain GT.M format control characters, or when the record
reaches its maximum size, as determined by the device WIDTH, and the
device is set to WRAP. The definition of "logical record" varies from
device to device. For an exact definition, see the sections on each
device type. FILTER and the device LENGTH also have an effect on $Y.
SET $Y does not automatically issue device commands or escape sequences
to reposition the physical cursor.
4 Maint_of_$X_and_&Y
Maintenance of $X and $Y
In GT.M, the following factors affect the maintenance of the virtual
cursor position ($X and $Y):
o The bounds of the virtual "page"
o GT.M format control characters
o GT.M character filtering
Each device has a WIDTH and a LENGTH that define the virtual "page."
The WIDTH determines the maximum size of a record for a device, while
the LENGTH determines how many records fit on a page. GT.M starts a new
record when the current record size ($X) reaches the maximum WIDTH and
the device has WRAP enabled. When the current line ($Y) reaches the
maximum LENGTH, GT.M starts a new page.
GT.M has several format control characters that allow the manipulation
of the virtual cursor. For all I/O devices, the GT.M format control
characters do the following:
! Sets $X to zero (0) and increments $Y, and terminates the logical
record in progress. The definition of "logical record" varies from
device to device, and is discussed in each device section.
# Sets $X and $Y to zero (0), and terminates the logical record in
progress.
?n If n is greater than $X, writes n-$X spaces to the device,
bringing $X to n. If n is less than or equal to $X, ?n has no
effect. When WRAP is enabled and n exceeds the WIDTH of the line,
WRITE ?n increments $Y and sets $X equal to n#WIDTH, where # is the
GT.M modulo operator.
GT.M provides two modes of character filtering. When filtering is
enabled, certain <CTRL> characters and/or escape sequences have special
effects on the cursor position (e.g., <BS> (ASCII 8) may decrement $X,
if $X is non-zero). For more information on write filtering, refer to
the section on the [NO]FILTER deviceparameter.
3 Status_Var
Status Variables
GT.M provides several I/O status variables that convey information
about the status of individual operations.
4 $ZA
$ZA
$ZA contains a status determined by the last read on the device. The
value is a decimal integer with a meaning determined by the device as
follows:
For Terminal I/O:
0 Indicating normal termination of a read operation
1 Indicating a parity error
2 Indicating the terminator sequence was too long
9 Indicating a default for all other errors
For Sequential Disk:
0 Indicating normal termination of a read operation
9 Indicating a failure of a read operation
For FIFO:
0 Indicating normal termination or time out
9 Indicating a failure of a read operation
For socket:
0 Indicating normal termination or time out
9 Indicating failure of a read operation
$ZA refers to the status of the current device. Therefore, exercise
care in sequencing USE commands and references to $ZA.
4 $ZB
$ZB
$ZB contains a string specifying the input terminator for the last
terminal READ. $ZB is null, and it is not maintained for devices other
than terminals. $ZB may contain any legal input terminator, such as
<CR> (ASCII 13) or an escape sequence starting with <ESC> (ASCII 27),
from zero (0) to 15 bytes in length. $ZB is null for any READ
terminated by a timeout or any fixed-length READ terminated by input
reaching the maximum length.
$ZB contains the actual character string, not a sequence of numeric
ASCII codes.
Example:
SET zb=$ZB FOR i=1:1:$LENGTH(zb) WRITE !,i,?5,$A(zb,i)
This example displays the series of ASCII codes for the characters in
$ZB.
$ZB refers to the last READ terminator of the current device.
Therefore, be careful when sequencing USE commands and references to
$ZB.
4 $ZEOF
$ZEOF
$ZEOF contains a truth-valued expression indicating whether the last
READ operation reached the end-of-file. $ZEOF is TRUE(1) at EOF and
FALSE (0) at other positions. GT.M does not maintain $ZEOF for terminal
devices.
$ZEOF refers to the end-of-file status of the current device.
Therefore, be careful when sequencing USE commands and references to
$ZEOF.
2 IO_Devices
I/O Devices
Each device type supported by GT.M responds to a particular subset of
deviceparameters, while ignoring others. Devices may be programmed in a
device-specific manner, or in a device-independent manner.
Device-specific I/O routines are intended for use with only one type of
device. Device-independent I/O routines contain appropriate
deviceparameters for all devices to be supported by the function, so
the user can redirect to a different device output while using the same
program.
GT.M supports the following I/O device types:
o Terminals and Printers
o Sequential Disk Files
o FIFOs
o Null Devices
o Socket Devices
3 IO_Devi_Recog
I/O Device Recognition
GT.M OPEN, USE, and CLOSE commands have an argument expression
specifying a device name. In the operating system environment, a device
may be referred to either by its physical name or by a name containing
one or more environment variables, each with a dollar-sign ($) prefix
that expand to its physical name. Because environment variables permit
program coding independent of hardware configuration, they tend to
isolate the code from hardware changes.
During an OPEN, GT.M attempts to resolve the specified device names to
physical names. When GT.M successfully resolves a device name to a
physical device, that device becomes the target of the OPEN. If the
device name contains a dollar sign ($), GT.M attempts an environment
variable translation; the result becomes the name of the device. If it
does not find such an environment variable, it assumes that the dollar
sign is a part of the filename, and opens a file by that name.
Once a device is OPEN, GT.M establishes an internal correspondence
between a name and the device or file. Therefore, while the device is
OPEN, changing the translation of an environment variable in the device
specification does not change the device.
The following names identify the original $IO for the process:
o $PRINCIPAL
0
Some versions of GT.M also treat the empty string as identifying $P.
However, Sanchez recommends using the empty string to identify a null
device, so it would be wise to avoid or eliminate this behavior.
3 Devi_Spec_Defaults
Device Specification Defaults
GT.M uses standard filenames for device specifiers.
The complete format for a filename is:
/directory/file
If the expression specifying a device does not contain a complete
filename, the expression may start with an environment variable that
translates to one or more leading components of the filename. GT.M
applies default values for the missing components.
The GT.M file-name defaults are the following:
Directory Current working directory
File No default (user-defined filename)
Filetype No default (user-defined filetype)
3 How_IO_DeviParam_Work
How I/O Deviceparameters Work
I/O deviceparameters either perform actions that cause the device to do
something (for example, CLEARSCREEN), or specify characteristics that
modify the way the device subsequently behaves (for example,
BLOCKSIZE). When an I/O command has multiple action deviceparameters,
GT.M performs the actions in the order of the deviceparameters within
the command argument. When a command has characteristic
deviceparameters, the last occurrence of a repeated or conflicting
deviceparameter determines the characteristic.
Deviceparameters often relate to a specific device type. GT.M ignores
any deviceparameters that do not apply to the type of the device
specified by the command argument. Specified device characteristics are
in force for the duration of the GT.M image, or until modified by an
OPEN, USE, or CLOSE command.
When reopening a device that it previously closed, a GT.M process
restores all characteristics not specified on the OPEN to the values
the device had when it was last CLOSEd. GT.M treats sequential disk
files differently and uses defaults for unspecified sequential disk
file characteristics on every OPEN (that is, GT.M does not retain
sequential disk file characteristics on a CLOSE).
The ZSHOW command with an argument of "D" displays the current
characteristics for all devices OPENed by the process. ZSHOW can direct
its output into a GT.M variable.
3 Abbv_DeviParam
Abbreviating Deviceparameters
GT.M deviceparameters do not have predefined abbreviations. GT.M
recognizes deviceparameters using a minimum recognizable prefix
technique. Most deviceparameters may be represented by four leading
characters, except ERASELINE, all deviceparameters starting with WRITE,
and Z* deviceparameters in a mnemonicspace (such as SOCKET). The four
leading characters recognized do not include a leading NO for negation.
For compatibility with previous versions, GT.M may recognize certain
deviceparameters by abbreviations shorter than the minimum. While it is
convenient in Direct Mode to use shorter abbreviations, Sanchez
Computer Associates may add additional deviceparameters, and therefore,
recommends all programs use at least four characters. Because GT.M
compiles the code, spelling out deviceparameters completely has no
performance penalty, except when used with indirection or XECUTEd
arguments.
3 Devi_Independent_Prog
Device-Independent Programming
When a user may choose a device for I/O, GT.M routines can take one of
two basic programming approaches.
o The user selection directs the program into different code
branches, each of which handles a different device type.
o The user selection identifies the device. There is a single code
path written with a full complement of deviceparameters to handle
all selectable device types.
The latter approach is called device-independent programming. To permit
device independent programming, GT.M uses the same deviceparameter for
all devices that have an equivalent facility, and ignores
deviceparameters applied to a device that does not support that
facility.
Example:
OPEN dev:(EXCE=exc:REWIND:VARIABLE:WRITEONLY)
This example OPENs a device with deviceparameters that affect different
devices. The EXCEPTION has an effect for all device types. When dev is
a terminal or a null device, GT.M ignores the other deviceparameters.
When dev is a sequential file on disk, GT.M uses REWIND and VARIABLE.
This command performs a valid OPEN for all the different device types.
A file that has been previously created and contains data that
should be retained can also be opened with the device parameter
APPEND.
2 Terminals
Using Terminals
A typical GT.M application is largely interactive and uses terminals
extensively. By default, a GT.M process directs its terminal I/O to
$PRINCIPAL. $PRINCIPAL identifies the terminal that the user signed
onto in UNIX.
While all terminals support the CTRAP deviceparameter, which optionally
allows terminal input to optionally redirect program flow, only
$PRINCIPAL supports CENABLE, which optionally allows the terminal user
to invoke the Direct Mode shell.
Directly connected printers often appear to GT.M as a terminal
(although printers generally do not provide input) regardless of
whether the printer is connected to the computer with a high speed
parallel interface, or an asynchronous terminal controller.
3 Set_Terminal_Char
Setting Terminal Characteristics
GT.M does not isolate its handling of terminal characteristics from the
operating system environment at large. GT.M inherits the operating
system terminal characteristics in effect at the time the GT.M image is
invoked. When GT.M exits, the invoking environment retains the device
characteristics established with GT.M.
However, if the process temporarily leaves the GT.M environment with a
ZSYSTEM command, GT.M does not recognize any changes to the terminal
characteristics left by the external environment. This may cause
disparities between the physical behavior of the terminal, and the
perceived behavior by GT.M.
UNIX enforces standard device security for explicit OPENs of terminals
other than the sign-in terminal ($PRINCIPAL). If you are unable to OPEN
a terminal, contact your system manager.
USE of a terminal causes the device driver to flush the output buffer.
This feature of the USE command provides routine control over the
timing of output, which is occasionally required. However, it also
means that redundant USE commands may induce an unnecessary performance
penalty. Therefore, Sanchez Computer Associates recommends restricting
USE commands to redirecting I/O, modifying deviceparameters, and
initiating specifically required flushes.
3 Logical_Rec_for_Term
Logical Records for Terminals
A logical record for a terminal equates to a line on the physical
screen. The WIDTH device characteristic specifies the width of the
screen, while the LENGTH device characteristic specifies the number of
lines on the screen.
3 READ_Comm_for_Term
READ* Command for Terminals
If the terminal has ESCAPE sequencing enabled, and the input contains a
valid escape sequence or a terminator character, the terminal device
driver stores the entire sequence in $ZB and returns the ASCII
representation of the first character.
Example:
GTM> KILL
GTM> USE $P:ESCAPE
GTM> READ *X SET ZB=$ZB ZWRITE
(Press the F11 key on the VT220 terminal keyboard)
x=27
zb=$C(27)_"[23~"
This enters an escape sequence in response to a READ *. The READ *
assigns the code for <ESC> to the variable X. The terminal handler
places the entire escape sequence in $ZB. Because some of the
characters are not graphic, that is, visible on a terminal, the example
transfers the contents of $ZB to the local variable ZB and uses a
ZWRITE so that the non-graphic characters appear in $CHAR() format.
The READ * command for terminals does not affect $ZB when escape
sequencing is not enabled. If the input contains a valid escape
sequence and escape sequencing is not enabled, the variable for the
READ * command returns the first character of the escape sequence, for
example, ASCII 27. The terminal device driver stores the remaining
characters of the escape sequence in the read buffer. A READ command
following a READ * command returns the remaining characters of the
escape sequence. An application that operates with NOESCAPE must
provide successive READ * commands to remove the remaining escape
characters from the buffer.
Example:
GTM> KILL
GTM> USE $P:(NOESCAPE:TERM=$C(13))
GTM> READ *X SET ZB=$ZB READ Y:0 ZWRITE
(Press the F11 key on the terminal keyboard)
[23~i=5
x=27
y="[23~"
zb=""
GTM> USE $P:NOECHO READ *X S ZB=$ZB READ Y:0 USE $P:ECHO ZW
i=5
x=27
y="[23~"
zb=""
GTM> READ *X SET ZB=$ZB USE $P:FLUSH READ Y:0 ZWRITE
i=5
x=27
y=""
zb=""
While the first READ Y:0 picks up the sequence after the first
character, notice how the graphic portion of the sequence appears on
the terminal - this is because the READ *X separated the escape
character from the rest of the sequence thus preventing the VMS
terminal driver logic from recognizing it as a sequence, and
suppressing its echo. The explicit suppression of echo removes this
visual artifact. In the case of the final READ *X, the FLUSH clears the
input buffer so that it is empty by the time of the READ Y:0.
3 READmaxlen_Comm_for_Term
READ X#maxlen Command for Terminals
Generally, GT.M performs the same maintenance on $ZB for a READ
X#maxlen as for a READ. However, if the READ X#maxlen terminates
because the input has reached the maximum length, GT.M sets $ZB to
null. When the terminal has ESCAPE sequencing enabled, and the input
contains an escape sequence that does not fit in the read buffer, GT.M
sets $ZB to contain the escape sequence.
3 Term_Examples
Terminal Examples
This section contains examples of GT.M terminal handling.
Example:
USE $PIECE:(exception="zg "_$zl_":C^MENU")
This example USEs the principal device, and sets up an EXCEPTION
handler. When an EXCEPTION occurs, it transfers control to label C in
the routine ^MENU at the process stack level where the EXCEPTION was
established.
Example:
USE $PIECE:(X=0:Y=0:CLEARSCREEN)
This example positions the cursor to the upper left-hand corner and
clears the entire screen.
Example:
USE $PIECE:(NOECHO:WIDTH=132:WRAP)
This example disables ECHOing, enables automatic WRAPping, and sets the
line width to 132 characters.
Example:
USE $PIECE:NOCENABLE
This example disables <CTRL-C>.
2 Sequential_Files
Using Sequential Files
GT.M provides access to sequential files both on disk. These files
allow linear access to records. Sequential files are used to create
programs, store reports, and to communicate with facilities outside of
GT.M.
3 Setting_Seq_File_Charc
Setting Sequential File Characteristics
The ANSI standard specifies that when a process CLOSEs and then reOPENs
a device, GT.M restores any characteristics not explicitly specified
with deviceparameters to the values they had prior to the last CLOSE.
However, because it is difficult for a large menu-driven application to
ensure the previous OPEN state, GT.M always sets unspecified sequential
file characteristics to their default value on OPEN. This approach also
reduces potential memory overhead imposed by OPENing and CLOSEing a
large number of sequential files during the life of a process.
GT.M does not restrict multiple OPEN commands. However, if a file is
already open, GT.M ignores attempts to modify sequential file OPEN
characteristics, except for RECORDSIZE and for deviceparameters that
also exist for USE.
Sequential files can be READONLY, or read/write (NOREADONLY).
Sequential files can be composed of either FIXED or VARIABLE (NOFIXED)
length records. By default, records have VARIABLE length.
UNIX enforces its standard security when GT.M OPENs a sequential file.
This includes any directory access required to locate or create the
file. If you are unable to OPEN a file, contact your system manager.
3 SeqFile_Pointers
Sequential File Pointers
Sequential file I/O operations use a construct called a file pointer.
The file pointer logically identifies the next record to read or write.
OPEN commands position the file pointer at the beginning of the file
(REWIND) or at the end-of-file (APPEND). APPEND cannot reposition a
file currently open. Because the position of each record depends on the
previous record, a WRITE destroys the ability to reliably position the
file pointer to subsequent records in a file. Therefore, by default
(NOTRUNCATE), GT.M permits WRITEs only when the file pointer is
positioned at the end of the file.
If a device has TRUNCATE enabled, a WRITE issued when the file pointer
is not at the end of the file causes all contents after the current
file pointer to be discarded. This effectively moves the end of the
file to the current position and permits the WRITE.
3 SeqFile_Examples
Sequential File Examples
This section contains a few brief examples of GT.M sequential file
handling.
Example:
FREAD READ "File > ",sd
OPEN sd:(readonly:exception="g BADOPEN")
USE sd:exception="G EOF"
FOR USE sd READ x USE $P WRITE x,!
EOF IF '
$ZEOF ZM +$ZS
CLOSE sd
QUIT
BADOPEN IF $P($ZS,",",1)=2 DO QUIT
. WRITE !,"The file ",sd," does not exist."
IF $P($ZS,",",1)=13 DO QUIT
. WRITE !,"The file ",sd," is not accessible."
ZM +$ZS
QUIT
This example OPENs a file READONLY and specifies an EXCEPTION. The
exception handler for the OPEN deals with file-not-found and
file-access errors, and reissues all other errors with the ZMESSAGE
command. The first USE sets the EXCEPTION to handle end-of-file. The
FOR loop reads the file one record at a time and transfers each record
to the principal device. The GOTO in the EXCEPTION terminates the FOR
loop. At label EOF, if $ZEOF is false, the code reissues the error that
triggered the exception. Otherwise, the CLOSE releases the file.
Example:
SET sd="temp.dat",acct=""
OPEN sd:newversion U sd:width=132
FOR SET acct=$O(^ACCT(acct)) QUIT:acct="" DO
. SET rec=$$FORMAT(acct)
. WRITE:$Y>55 #,hdr W !,rec
CLOSE sd
This OPENs a NEWVERSION of file temp.dat. The FOR loop cycles through
the ^ACCT global formatting (not shown in this code fragment) lines and
writing them to the file. The FOR loop uses the argumentless DO
construct to break a long line of code into more manageable blocks. The
program writes a header record (set up in initialization not, shown in
this code fragment) every 55 lines, because that is the application
page length, allowing for top and bottom margins.
2 FIFO_Charc
FIFO Characteristics
FIFOs have the same characteristics as other sequential files, except
that READs and WRITEs can occur in any order.
The following characteristics of FIFO behavior may be helpful in using
them effectively.
With
READ:
o If a READ is done while there is no data in the FIFO:
The process hangs until data is put into the FIFO by another process,
or the READ times out, when a timeout is specified.
With
WRITE:
o If a process tries into write to a full FIFO, the process hangs
until another process reads from the FIFO, emptying enough data to
make room for the new data.
While it is hung, the process will not respond to <CTRL-C>.
With
CLOSE:
o The FIFO is not deleted unless the DELETE qualifier is specified.
o If a process closes the FIFO with the DELETE qualifier, the FIFO
becomes unavailable to new users at that time.
o All processes currently USEing the FIFO may continue to use it,
until the last process attached to it CLOSES it, and is destroyed.
o Any process OPENing a FIFO with the same name as a deleted FIFO
creates a new one to which subsequent OPENs attach.
A process must have read and write privileges on a FIFO to access it.
File permissions have no affect on a process that already has the FIFO
open.
3 Consider_Impl_FIFOs
Considerations in Implementing FIFOs
As you establish FIFOs for interprocess communication, consider
whether, and how, the following issues will be addressed:
o Do READs occur immediately, or can the process wait?
o Are timed READs useful to avoid system hangs and provide a way to
remove the process?
o Does the WRITE process need to know whether the READ data was
received?
o Will there be multiple processes READing and WRITEing into a single
FIFO?
3 GTM_Recog_FIFOs
GT.M Recognition of FIFOs
Like other GT.M devices a FIFO can be specified as an argument
expression to the OPEN, USE, and CLOSE commands. A device OPENed with a
FIFO qualifier becomes a FIFO unless another device of that name is
already OPEN. In that case, OPENing a device that has previously been
OPENed by another process as a FIFO causes the process (the process
here is the process trying to open the FIFO) to attach to the existing
FIFO.
3 FIFO_Devi_Ex
FIFO Device Examples
The following two examples represent a master/slave arrangement where
the slave waits in a read state on the FIFO until the master sends it
some data that it then processes.
Example:
set x="named.pipe"
open x:fifo
do getres
use x write res,!
This routine opens the FIFO, performs its own processing which includes
starting the slave process (not shown in this code fragment).
Example:
set x="named.pipe"
open x:fifo
use x read res
do process(res)
This routine waits for information from the master process, then begins
processing.
2 NULL_Devices
Using NULL Devices
The null device is accessed through /dev/null. A null device fulfills
every input request by returning a null string and setting $ZEOF. A
null device discards all output. GT.M maintains a virtual cursor
position for null devices as it does for terminals. Use null devices
for program testing and debugging, or for jobs that permit I/O to be
discarded under certain circumstances. For example, JOB processes must
have input and output devices associated with them, even though they do
not use them. Null devices are low overhead never-fail alternatives.
3 Null_Dev_Ex
Null Device Examples
Example:
SET dev="/dev/null"
OPEN dev USE dev
SET x="" WRITE hdr,!,$ZDATE($h),?30,$J,!
FOR SET x=$O(^tmp($J,x)) q:x="" DO REPORT
CLOSE dev
This program produces a report derived from the information in the
global variable ^tmp. The unspecified routine REPORT may potentially
contain a large amount of code. To see that the basic program functions
without error, the programmer may discard the output involved in favor
of watching the function. To run the program normally, the programmer
simply has to change the variable dev to name another device.
Example:
JOB ^X:(IN="/dev/null":OUT="/dev/null":ERR= "error.log")
This example issues a GT.M JOB command to execute the routine ^X in
another process. This routine processes a large number of global
variables and produces no output. In the example, the JOBbed process
takes its input from a null device, and sends its output to a null
device. If the JOBbed process encounters an error, it directs the error
message to error.log.
2 Socket_Devices
Using Socket Devices
SOCKET devices are used to access and manipulate sockets. A SOCKET
device can have from zero (0) to 64 associated sockets. At any time,
only one socket from the collection can be the current socket. If there
is no current socket, an attempt to READ from, or WRITE to the device,
generates an error.
Sockets can be attached and detached from the collection of sockets
associated with a device. Detached sockets belong to a pseudo-device
called the "socketpool". A process can detach a socket from a device
and later attach it to the same device or another device.
The GT.M socket device interface does not have the ability to pass
sockets between related or unrelated processes. Currently error
trapping operates on a device, rather than on a socket.
3 Msg_Mgmt
Message Management
From an application perspective, the transport layers used by a socket
device are stream-oriented media, with no provisions for implicit
application messages. Therefore, the following are two common protocols
used to segment application messages.
o One method is to use a, typically small, fixed length message
containing the length of the next, variable length, message. In
GT.M a simplistic writer might be:
Write $Justify($Length(x),4),x
A corresponding simplistic reader might be:
Read len#4,x#len
The advantage of this approach is that the message content (the value
of x in the code fragments above) can contain any character. The
disadvantage is that detecting that the protocol has become
desynchronized is a problem.
o The other common method is to place a delimiter between each
application message. The protocol breaks if a message ever includes
a delimiter as part of its content.
The SOCKET device has the capability to handle delimiters because
parsing messages for delimiters is cumbersome.
3 Msg_Delimi
Message Delimiters
Each device can have from zero (0) to 64 delimiters associated with it.
Each delimiter can be from one (1) to 64 characters. All the delimiters
declared for a device are valid for any READ from any associated
socket, which means, any of the defined delimiters terminate the READ.
The actual terminating delimiter is available in $KEY. A WRITE to a
socket associated with a device with one or more delimiters inserts the
first of the delimiters for any WRITE ! format.
3 Read_Comm
READ Command
The READ command may be used to obtain data from a socket. A
non-fixed-length read, with no timeout and no delimiters requires a
complex implementation of sequence of READs to ensure a predictable
result. This is because the transport layer stream fragments delivered
to the reader has only accidental correspondence with the operations
performed by the writer. For example, the following
Write "Message 1","Message 2"
is presented to the reader as the stream "Message1Message2" but it can
take from one (1) to 18 READ commands to retrieve the entire stream.
3 Write_Comm
WRITE Command
The WRITE command sends data to a socket.
The WRITE command for SOCKET devices accepts following controlmnemonics
on a bound socket:
/L[ISTEN][(numexpr)]
Where numexpr is in the range 1-5 and specifies the listen queue depth.
/W[AIT][(timeout)]
Where timeout is a "numexpr" that specifies how long a server waits for
a connect before returning control to the GT.M routine.
"WRITE !" inserts the character(s) of the first I/O delimiter (if any)
to the sending buffer. If "ZFF=expr" has been used to define a
delimiter, "WRITE #" inserts the characters of that delimiter.
Otherwise WRITE # has no effect on the stream content. WRITE ! and
WRITE # always maintain $X and $Y in a fashion that emulates a terminal
cursor position.
3 Socket_Devi_Ops
Socket Device Operation
Each socket may be in one of the following states:
o Created - indicates that the socket exists.
o Bound - indicates that the socket exists and is bound to a port; a
"Bound socket" needs a listen queue which currently requires a
WRITE /LISTEN [after a USE].
o Connected - indicates that the socket exists and has a connection.
A server socket used for accepting new connections goes through the
first two states in one step with a single OPEN or in two steps with an
OPEN and a USE. When a server does a WRITE /WAIT on a Bound socket, a
client can establish a connection which Creates another server socket
that is Connected. In server operation, $KEY supplies the port value
when a socket is bound (important when port 0 is specified to get the
system to choose the port), and a socket id when a Connected socket is
created. A client socket goes through the first and third states with a
single OPEN or in two steps with an OPEN and a USE.
3 Socket_Devi_Ex
Socket Device Examples
This section contains examples on Socket Device usage.
;server.m
Set portno=6321,delim=$c(13)
Set tcpdev="server$"_$j,timeout=30
Open tcpdev:(ZLISTEN=portno_":TCP":attach="server"):timeout:"SOCKET"
Use tcpdev
Write /listen(1)
Write /wait(timeout)
;
;dialogue with the client
;
;client.m
Set host="orlando"
Set portno=6321
Set delim=$c(13)
Set tcpdev="client$"_$j,timeout=30
O
tcpdev:(connect=host_":"_portno_":TCP":attach="client"):timeout:"SOCKET"
Use tcpdev
;
;dialogue with the server
;
2 IO_Comm
I/O Commands
This section describes the following GT.M I/O commands:
o OPEN establishes a connection from a GT.M process to a device.
o USE declares a device as the current source of input and
destination for output.
o READ accepts characters from the current device into a global or
local variable.
o WRITE sends characters to the current device.
o CLOSE breaks the connection between a GT.M process and a device.
2 Open
Open
The OPEN command establishes a connection from a GT.M process to a
device.
The format of the OPEN command is:
O[PEN][:tvexpr] expr[:[(keyword[=expr][:...])][:numexpr][:expr]][,...]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o The required expression specifies the device to OPEN.
o The optional keywords specify deviceparameters that control device
behavior; some deviceparameters take arguments delimited by an
equal sign (=); if the argument only contains one deviceparameter,
the surrounding parentheses are optional.
o The optional numeric expression specifies a time in seconds after
which the command should timeout if unsuccessful; 0 provides a
single attempt to open the device.
o When an OPEN command specifying a timeout contains no
deviceparameters, double colons (::) separate the timeout numeric
expression from the device expression.
o The optional expression specifies a mnemonicspace that selects a
device binding. The only mnemonicspace that GT.M currently accepts
is SOCKET.
o When an OPEN command specifies a mnemonicspace with no timeout,
double colons separate the mnemonicspace string expression from the
deviceparameters; if there are neither a timeout nor
deviceparameters, triple colons separate the mnemonicspace from the
device expression.
o An indirection operator and an expression atom evaluating to a list
of one or more OPEN arguments form a legal argument for an OPEN.
With the exception of FIFOs, UNIX device access is exclusive. READONLY
sequential disk files may be shared among many readers, but no writers.
Spooled devices are devices, usually printers, which buffer output from
multiple sources, processing it after the writing process CLOSEs the
file. Spooled devices appear to GT.M as a terminal type device. For
more information on spooled devices, refer to the UNIX System Manager's
Manual. When one process successfully OPENs a device exclusively, no
other process can access that device until the first process CLOSEs
that device.
By default, when a device is unavailable, GT.M retries the OPEN
indefinitely at approximately one second intervals. A device is
unavailable when another process is using it exclusively, or when the
OPENing process does not have the resources left to open the device.
All other errors on OPEN raise an error condition and interrupt program
flow. A timeout is a tool that lets a GT.M routine regain program
control when a device remains unavailable. When the OPEN specifies a
timeout, GT.M keeps retrying until either the OPEN succeeds or the
timeout expires.
If OPEN establishes a connection with a device before the timeout
expires, GT.M sets $TEST to TRUE (1). If the timeout expires, GT.M sets
$TEST to FALSE (0). If an OPEN command does not specify a timeout, the
execution of the command does not affect $TEST.
If a process has not previously OPENed a device within the context of
an image, any deviceparameters not supplied on the OPEN take their
default values. When reOPENing a device that it previously closed, a
GT.M process restores all characteristics not specified on the OPEN to
the values the device had when it was last CLOSEd, except with
sequential disk files. If you have a menu-driven application that OPENs
and CLOSEs devices based on user selections, take care that every OPEN
explicitly includes all deviceparameters important to the application.
GT.M treats sequential disk files differently and uses defaults for
unspecified sequential disk file characteristics on every OPEN (i.e.,
GT.M does not retain sequential disk file characteristics on a CLOSE).
If a process OPENs an already OPEN device, GT.M modifies any
characteristics that accept changes when a device is OPEN to reflect
any new deviceparameter specifications.
3 Ex_of_Open
Examples of OPEN
Example:
SET sd="report.dat" OPEN sd:NEWVERSION
This OPENs a NEWVERSION of a sequential disk file named report.dat for
both read and write access.
3 Open_DeviParam
OPEN Deviceparameters
4 APPEND
APPEND Applies to: Sequential Files
Positions the file pointer at the end-of-file. This deviceparameter
only affects the device on the first OPEN command. Re-OPENing an
already OPEN device with this deviceparameter has no effect.
By default, OPEN sets the file pointer to the beginning-of-file.
4 ATTACH
Attach=expr Applies to: Socket Device
When ATTACH is used and one of ZLISTEN and CONNECT is specified at the
same time, the value of expr becomes the identifier of the newly
created socket. If neither ZLISTEN nor CONNECT is specified, ATTACH is
ignored.
4 BLOCKSIZE
BLOCKSIZE=intexpr Applies to: Terminals and Printers
Specifies the size in bytes of the maximum single read or write for the
specified device.
4 CANONICAL
[NO]CANONICAL Applies to: Terminals and Printers
Enables or disables canonical input as controlled by the ICANON
terminal attribute. See the documentation on your platform for details,
but in general this would be erase and kill edit functions, and lines
delimited by NL (usually <LF>), EOF (usually ^D), and EOL (usually not
defined).
By default, canonical input is enabled.
4 CONNECT
CONNECT=expr Applies to: Socket Device
Enables a client connection with a server, which is located by the
information provided by expr. A new socket is allocated for the client
connection and is made the current socket for the device, if the
operation is successful.
expr specifies the protocol and protocol specific information.
Currently, TCP/IP is the only protocol GT.M supports. expr should be of
the format "<host>:<port>:TCP", where host is either an IP address or a
hostname like server.sanchez.com.
CONNECT is not compatible with ZLISTEN.
4 DELIMITER
[NO]DELIMITER=expr Applies to: Socket Device
DELIMITER establishes or replaces the list of delimiters used by the
sockets associated with the device. The default for on a command that
first OPENs a device is NODELIMITER. The delimiter list on a
preexisting device remains the same until it is explicitly replaced or
deleted.
expr must be a string of the following format:
':' is used to separate delimiters (it is the delimiter for
delimiters).
'/' serves as an escape character.
expr "ab:/:://:bc" is interpreted as four delimiters, which are "ab",
":", "/", and "bc". One socket can have 0-64 delimiters and each
delimiter can contain 1-64 characters.
4 EXCEPTION
EXCEPTION=expr Applies to: All devices
Defines an error handler for an I/O device. The expression must contain
a fragment of GT.M code (for example, GOTO ERRFILE) that GT.M XECUTEs
when the driver for the device detects an error, or an entryref to
which GT.M transfers control, as appropriate for the current
gtm_ztrap_form.
For more information on error handling, refer to the "Error Processing"
chapter in GT.M Programmer's Guide.
4 FIFO
FIFO Applies to: FIFO
Specifies that the device for the OPEN is a FIFO name. GT.M creates the
FIFO if it does not already exist and if the process has adequate
privileges. However, in the event that the process does not have
adequate privileges, the process generates a run-time error. A process
does not require any privileges to OPEN an existing FIFO.
4 FIXED
[NO]FIXED Applies to: Sequential Files and FIFO
Selects a fixed record length format for sequential disk files. FIXED
does not specify the actual length of a record. Use RECORDSIZE to
specify the record length.
NOFIXED specifies a variable length record format for sequential disk
files. NOFIXED is a synonym for VARIABLE. FIXED is incompatible with
STREAM and VARIABLE.
By default, records have VARIABLE length.
4 GROUP
GROUP=expr Applies to: Sequential Files and FIFO
Specifies access permission on a UNIX file for other users in the file
owner's group. The expression is a character string evaluating to null
or to any combination of the letters RWX, indicating respectively Read,
Write, and eXecute access. When any of the permissions controlling
deviceparameters appears on an OPEN of a new file, any user category
(OWNER, SYSTEM, WORLD), that is not explicitly specified is given the
default access permissions. When any one of these deviceparameters
appears on an OPEN of an existing device, any user category that is not
explicitly specified remains unchanged.
In order to modify file security, the user who issues the OPEN must
have ownership.
By default, OPEN does not modify the permissions on an existing file.
Unless otherwise specified, when OPEN creates a new file, it
establishes security using standard defaulting rules.
4 IOERROR
IOERROR=expr Applies to: Socket Device
Enables exception handling in socket devices. expr specifies the I/O
error trapping mode. A value equal to "TRAP" specifies that I/O errors
on a device raise error conditions. A value equal to "NOTRAP", or when
IOERROR is not specified, indicates that I/O error on a device does not
raise error conditions.
GT.M currently handles exception handling at device level instead
of socket level.
4 NEWVERSION
NEWVERSION Applies to: Sequential Files and FIFO
The NEWVERSION deviceparameter assures that when an existing file is
used, it is empty upon the OPEN.
By default, if any version of the file exists, OPEN accesses the
current version. If no version of the file exists, OPEN without
READONLY creates a new file.
4 OWNER
OWNER=expr Applies to: Sequential Files and FIFO
Specifies access permission on a UNIX file for the owner of the file.
The expression is a character string evaluating to null or to any
combination of the letters RWX, indicating Read, Write, and eXecute
access. When any one of these deviceparameters appears on an OPEN of a
new file, any user category that is not explicitly specified is given
the default mask. When any one of these deviceparameters appears on an
OPEN of an existing file, any user category (GROUP, SYSTEM, WORLD) that
is not explicitly specified remains unchanged.
To modify file security, the user who issues the OPEN must have
ownership.
By default, OPEN does not modify the permissions on an existing file.
Unless otherwise specified, OPEN establishes security using standard
defaulting rules when it creates a new file.
4 READONLY
[NO]READONLY Applies to: Sequential Files and FIFO
OPENs a device for reading only (READONLY) or reading and writing
(NOREADONLY).
To open a sequential file using the READONLY parameter, the file must
exist on the disk. If it does not, GT.M issues a run-time error.
When GT.M encounters a WRITE directed to a file OPENed READONLY, GT.M
issues a run-time error.
By default, OPEN accesses the device or file NOREADONLY (read-write).
4 RECORDSIZE
RECORDSIZE=intexpr Applies to: Sequential Files and FIFO
Overrides the default record size for a disk and specifies the new
maximum record size in bytes.
4 REWIND
REWIND Applies to: Sequential Files
REWIND positions the file pointer of a sequential disk to the first
record.
By default, OPEN does not REWIND.
5 [NO]STREAM Applies to: SD
4 STREAM
[NO]STREAM Applies to: Sequential Files
STREAM and VARIABLE are essentially the same; VARIABLE is preferred.
The combination of the STREAM and NOWRAP options on disk files allows
you to write a record of arbitrary length. While each WRITE argument is
truncated if it exceeds the WIDTH, the total record can be of arbitrary
length. Note that, for efficiency, the compiler combines sequential
literal arguments of a single WRITE into a single string so that the
run-time system considers the combined length of the sequence.
Automatic record termination does not occur when record length exceeds
the device width.
By default, records are VARIABLE, NOSTREAM.
4 SYSTEM
SYSTEM=expr Applies to: Sequential Files
This deviceparameter is a synonym for OWNER that is maintained in UNIX
for compatibility with VMS applications.
4 TRUNCATE
[NO]TRUNCATE Applies to: Sequential Files and FIFO
Enables or disables overwriting of existing data in sequential disk
files. Because the position of each record depends on the prior record,
a WRITE destroys the ability to reliably position to subsequent records
in a file. Therefore, by default (NOTRUNCATE), GT.M permits WRITEs only
when the file pointer is positioned at the end-of-file. When a device
has TRUNCATE enabled, a WRITE issued when the file pointer is not at
end-of-file truncates the file by destroying all data from the file
pointer to the end-of-file.
By default, OPEN accesses the file NOTRUNCATE.
4 UIC
UIC=expr Applies to: Sequential Files and FIFO
Specifies the group that has access to the file. The format of the
string is "g,i" where g is a decimal number representing the group
portion of the UIC and i is a decimal number representing the
individual portion. A process with the VMS privilege CMKRNL may set the
file UIC to a UIC other than the UIC under which it is running, thereby
giving ownership of the file to another user.
Specifies the owner and affects access to the file. The expression
evaluates to the numeric identifier of the new owner.
4 VARIABLE
VARIABLE Applies to: Sequential Files and FIFO
Specifies the VARIABLE record length format for sequential disk files.
By default, records have VARIABLE length.
4 WORLD
WORLD=expr Applies to: Sequential Files and FIFO
Specifies access permissions for users not in the owner's group on a
UNIX file. The expression is a character string evaluating to null or
to any combination of the letters RWX, indicating respectively Read,
Write, and eXecute access. When any one of these deviceparameters
appears on an OPEN of a new file, any user category that is not
explicitly specified is given the default character string. When any
one of these deviceparameters appears on an OPEN of an existing file,
any user category (OWNER, GROUP, SYSTEM), that is not explicitly
specified remains unchanged.
To modify file security, the user who issues the OPEN must have
ownership.
By default, OPEN and CLOSE do not modify the permissions on an existing
file. Unless otherwise specified, when OPEN creates a new file, it
establishes security using standard defaulting rules.
4 WRAP
[Z][NO]WRAP Applies to: FIFO, Sequential Devices, and Socket Device
Enables or disables automatic record termination. When the current
record size ($X) reaches the maximum WIDTH and the device has WRAP
enabled, GT.M starts a new record, as if the routine had issued a WRITE
! command.
NOWRAP causes GT.M to require a WRITE ! to terminate the record. NOWRAP
allows $X to become greater than the device WIDTH for terminals and
null devices.
The combination of STREAM and NOWRAP options on disk files allows you
to write a record of arbitrary length. Without the STREAM option, the
WRAP option determines the action taken when the record length exceeds
the device WIDTH. NOWRAP causes GT.M to truncate the record, while WRAP
causes GT.M to insert a format control character.
By default, records WRAP.
4 ZBFSIZE
ZBFSIZE Applies to: Socket Devices
Allocates a buffer used by GT.M when reading from a socket. The ZBFSIZE
deviceparameter should be at least as big as the largest message
expected.
By default, the size of ZBFSIZE is 1024 and the maximum it can be is
1048576.
4 ZDELAY
Z[NO]DELAY Applies to: Socket Devices
Controls buffering of data packets by the system TCP stack using the
TCP_NODELAY option to the SETSOCKOPT system call. This behavior is
sometimes known as the Nagle algorithm. The default is ZDELAY. This
delays sending additional packets until either an acknowledgement of
previous packets is received or an interval passes. If several packets
are sent from one end of a connection before the other end responds,
setting ZNODELAY may be desirable though at the cost of additional
packets being transmitted over the network. ZNODELAY must be fully
spelled out.
4 ZFF
Z[NO]FF=expr Applies to: Socket Device
expr specifies a string of characters, typically in $CHAR() format to
send to socket device, whenever a routine issues a WRITE #. When no
string is specified or when ZFF="", then no characters are sent. The
default in GT.M is ZNOFF.
4 ZIBFSIZE
ZIBFSIZE Applies to: Socket Device
Sets the buffer size used by the network software (setsockopt
SO_RCVBUF).
The default and the maximum values depend on the platform and/or system
parameters.
4 ZLISTEN
ZLISTEN=expr Applies to: Socket Device
A new socket is allocated to listen for a connection. It is made the
current socket for the device, if the operation is successful. Upon
successful completion, $KEY is set to the format of
"BOUND|<socket handle>|<port number>"
otherwise, $KEY is assigned the empty string.
expr specifies the protocol and protocol specific information.
Currently, TCP/IP is the only protocol GT.M supports. expr must be of
the format "<port>:TCP", where port specifies the port number at which
the socket is waiting for a connection.
ZLISTEN is not compatible with ATTACH in the USE command and
CONNECT in both USE and OPEN commands.
2 Use
Use Command
The USE command selects the current device for READs (input) and WRITEs
(output).
The format of the USE command is:
U[SE][:tvexpr] expr[:(keyword[=expr][:...])][,...]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o The required expression specifies the device to make the current
device.
o A USE that selects a device not currently OPENed by the process
causes a run-time error.
o The optional keywords specify deviceparameters that control device
behavior; some deviceparameters take arguments delimited by an
equal sign (=). If there is only one deviceparameter, the
surrounding parentheses are optional.
o An indirection operator and an expression atom evaluating to a list
of one or more USE arguments form a legal argument for a USE.
The intrinsic special variable $IO identifies the current device, so
GT.M directs all READs and WRITEs to $IO. When a GT.M image starts,
$PRINCIPAL is implicitly OPENed and USEd. Once the GT.M image USEs a
device, $IO holds the name of that device until the next USE command.
A USE command modifies the device in accordance with the
deviceparameters that apply to the device type and ignores those that
do not apply. Characteristics set with USE deviceparameters persist
until another USE for the same device with the corresponding
deviceparameter. Characteristics persist through USEs of other devices
and, except for sequential files, through a subsequent CLOSE and
re-OPEN.
Example:
USE $P:(X=0:Y=$Y-1:NOECHO)
This example USEs the principal device. If that device is a terminal,
the deviceparameters turn off echo and position the cursor to the
beginning of the previous line.
3 Use_DeviParam
Use Deviceparameters
4 ATTACH
ATTACH=expr Applies to: Socket Device
When ATTACH is used and one of ZLISTEN and CONNECT is specified at the
same time, the value of expr becomes the identifier of the newly
created socket. If neither ZLISTEN nor CONNECT is specified, expr
specifies the socket to be moved from the socketpool to the socket
device argument of USE.
4 CANONICAL
[NO]CANONICAL Applies to: Terminals and Printers
Enables or disables canonical input as controlled by the ICANON
terminal attribute. See the documentation on your platform for details,
but in general this would be erase and kill edit functions, and lines
delimited by NL (usually <LF>), EOF (usually ^D), and EOL (usually not
defined).
By default, canonical input is enabled (that is [NO]CANONICAL is the
default).
4 CENABLE
[NO]CENABLE Applies to: Terminals and Printers
Enables or disables the ability to force GT.M into Direct Mode by
entering <CTRL-C> at $PRINCIPAL.
[NO]CENABLE is subordinate to a CTRAP that includes <CTRL-C> ($C(3)).
By default, images have CENABLEd.
4 CLEARSCREEN
CLEARSCREEN Applies to: Terminals and Printers
Clears the terminal screen from the present cursor position to the
bottom of the screen. The CLEARSCREEN deviceparameter does not change
the cursor position or the $X and $Y variables.
Example:
U $P:(X=0:Y=0:CLEAR)
This example positions the cursor to "home" in the upper left corner of
a VDT and clears the entire current screen "page."
4 CONNECT
CONNECT=expr Applies to: Socket Device
Enables a client connection with a server, which is located by the
information provided by expr. A new socket is allocated for the client
connection and is made the current socket for the device, if the
operation is successful.
expr specifies the protocol and protocol specific information.
Currently, TCP/IP is the only protocol GT.M supports. expr should be of
the format "<host>:<port>:TCP", where host is either an IP address or a
hostname like server.sanchez.com.
CONNECT is not compatible with ZLISTEN.
4 CONVERT
[NO]CONVERT Applies to: Terminals and Printers
Enables or disables the terminal device driver from converting
lowercase input to uppercase during READs.
By default, the terminal device driver operates NOCONVERT.
4 CTRAP
CTRAP=expr Applies to: Terminals and Printers
Establishes the <CTRL> characters in the expression as trap characters
for the current device. When the terminal device driver receives a trap
character in the input from a device, GT.M issues a run-time exception.
The device does not have to be the current device, that is $IO.
The <CTRL> characters are ASCII 0 though 31.
For example, the command U $P:CTRAP=$C(26,30,7,19) sets a trap for the
ASCII characters <SUB>, <RS>, <BEL> and <DC3>.
Specifying CTRAP completely replaces the previous CTRAP list. Setting
CTRAP to the null string ("") disables character trapping.
A trap character enabled by CTRAP produces one of the following
actions:
o If an EXCEPTION deviceparameter has been issued for the device, the
process executes the EXCEPTION argument.
o Otherwise, if $ETRAP is not the empty string, execute $ETRAP.
o Otherwise, if $ZTRAP is not the empty string, the process executes
$ZTRAP.
o Otherwise, the GT.M image terminates.
For more information on error handling, refer to the "Error Processing"
chapter in GT.M Programmer's Guide.
When CTRAP includes <CTRL-C>, [NO]CENABLE has no effect. CTRAPping
<CTRL-C> also takes precedence over CENABLE.
4 DELIMITER
[NO]DELIMITER Applies to: Socket Device
DELIMITER establishes or replaces the list of delimiters used by the
sockets associated with the device. The default when the socket device
is first OPENed is NODELIMITER. The delimiter list on a preexisting
device remains the same until it is explicitly replaced or deleted.
expr must be a string of the following format:
':' is used to separate delimiters (it is the delimiter for
delimiters).
'/' serves as an escape character.
expr "ab:/:://:bc" is interpreted as four delimiters, which are "ab",
":", "/", and "bc". One socket can have 0-64 delimiters and each
delimiter can contain 1-64 characters.
4 DETACH
DETACH=expr Applies to: Socket Device
Removes the socket identified by expr from the current socket device,
without affecting any existing connection of that socket. The removed
socket is placed in the socketpool and may be attached to another
socket device. If the socket being removed is the current socket, then
GT.M does the following:
o The socket ATTACHed prior to the removed socket, is made current,
if one such exists.
o The socket ATTACHed after the removed socket, is made current, if
the removed one was the first socket.
o $PRINCIPAL is made the current device ($IO), if the removed socket
was the only one in the current socket device.
4 DOWNSCROLL
DOWNSCROLL Applies to: Terminals and Printers
If $Y=0, DOWNSCROLL does nothing. Otherwise, DOWNSCROLL moves the
cursor up one line on the terminal screen and decrements $Y by one.
DOWNSCROLL does not change the column position or $X. Some terminal
hardware may not support DOWNSCROLL.
4 ECHO
[NO]ECHO Applies to: Terminals and Printers
Enables or disables terminal device driver echo of input.
By default, terminal device drivers ECHO.
4 ERASELINE
ERASELINE Applies to: Terminals and Printers
Clears the current line from the physical cursor position to the end of
the line. ERASELINE does not affect the physical cursor position, or $X
and $Y.
4 ESCAPE
[NO]ESCAPE Applies to: Terminals and Printers
Enables or disables terminal device driver processing of escape
sequences.
The following events result when a terminal has ESCAPE sequencing
enabled. When an <ESC> or <CSI> arrives in the terminal input, the
device driver verifies the sequence that follows as a valid ANSI escape
sequence, terminates the READ, and sets $ZB to contain the entire
escape sequence. In this case, if the sequence starts with an <ESC>,
READ * returns the decimal ASCII representation for the character of
the escape introducer.
When escape processing is disabled, READ *x returns 27 in x for an
<ESC>. If the escape introducer is also a TERMINATOR, $ZB has a string
of length one (1), and a value of the $ASCII() representation of the
escape introducer; otherwise, $ZB holds the empty string. For single
character and short fixed reads with NOESCAPE, the terminal device
driver places the remaining characters of the escape sequence in the
input buffer for subsequent READs, regardless of [NO]TYPEAHEAD."
4 EXCEPTION
EXCEPTION=expr Applies to: All devices
Defines an error handler for an I/O device. The expression must contain
a fragment of GT.M code (e.g., GOTO ERRFILE) that GT.M XECUTEs when the
driver for the device detects an error, or an entryref to which GT.M
transfers control, as appropriate for the current gtm_ztrap_form.
For more information on error handling, refer to the "Error Processing"
chapter in GT.M Programmer's Guide.
4 FILTER
[NO]FILTER[=expr] Applies to: Terminals and Printers, Socket Device,
and NULL Device
Specifies character filtering for valid filtering expressions.
Filtering requires character by character examination of all output and
reduces I/O performance.
Each FILTER deviceparameter can have only one argument. However,
multiple FILTER deviceparameters can appear in a single USE command,
each with different arguments.
The valid values for expr:
[NO]CHARACTERS enables or disables maintenance of $X and $Y according
to the M ANSI standard for the characters <BS>, <LF>, <CR> and <FF>.
CHARACTERS causes the device driver to examine all output for the above
characters, and to adjust $X and $Y accordingly. By default, GT.M
performs special maintenance on $X and $Y only for M format control
characters, WRAPped records, and certain action deviceparameters.
[NO]ESCAPE alters the effect of ANSI escape sequences on $X and $Y.
ESCAPE causes GT.M to filter the output, searching for ANSI escape
sequences and preventing them from updating $X and $Y. By default, GT.M
does not screen output for escape sequences.
By default, GT.M does not perform output filtering. For GT.M to
maintain $X for non-graphic characters as described by the standard,
FILTER="CHARACTERS" must be enabled. Output filtering adds additional
overhead to I/O processing.
4 HOSTSYNC
[NO]HOSTSYNC Applies to: Terminals and Printers
Enables or disables the use of XON/XOFF by the host to throttle input
and prevent impending buffer overruns for a terminal. This
deviceparameter provides a control mechanism for the host over
asynchronous communication lines to help prevent data loss when
hardware is slow and/or processing load is high.
By default, the device driver operates HOSTSYNC.
4 IOERROR
IOERROR=expr Applies to: Socket Device
Enables exception handling in socket devices. expr specifies the I/O
error trapping mode. A value equal to "TRAP" specifies that I/O errors
on a device raise error conditions. A value equal to "NOTRAP", or when
IOERROR is not specified, indicates that I/O error on a device does not
raise error conditions.
GT.M currently handles exception handling at device level instead
of socket level.
4 LENGTH
[Z]LENGTH=intexpr Applies to: Terminals and Printers, Socket Device,
and NULL Device.
Sets the virtual page length for an I/O device to the integer
expression. The page length controls the point at which the device
driver automatically resets $Y to 0.
By default, GT.M uses the LENGTH specified by the device
characteristics at image activation. The terminal default depends on
the type of terminal. The default length for null device and socket
device is 66.
4 PASTHRU
[NO]PASTHRU Applies to: Terminals and Printers
Enables or disables interpretation of the ERASE character for a
terminal. PASTHRU shifts management of handling and response to ERASE
characters in the input stream from the driver to the GT.M application
code.
Exercise caution with PASTHRU in debugging, because using a PASTHRU
terminal in Direct Mode is somewhat awkward.
[NO]TTSYNC must be used with [NO]PASTHRU to control XON/XOFF handling.
By default, the device driver operates NOPASTHRU.
4 READSYNC
[NO]READSYNC Applies to: Terminals and Printers
Enables or disables automatic output of <XON> before a READ and <XOFF>
after a READ.
By default, the terminal drivers operate NOREADSYNC.
4 REWIND
REWIND Applies to: Sequential Files
REWIND for a disk file is a logical rather than a physical operation.
By default, USE does not REWIND.
4 SOCKET
SOCKET=expr Applies to: Socket Device
The socket specified in expr is made the current socket. Specifying a
socket that has not been previously OPENed generates an error.
SOCKET is compatible with DELIMITER only.
4 TERMINATOR
[NO]TERMINATOR[=expr] Applies to: Terminals and Printers
Specifies which of the 256 ASCII characters terminate a READ. For
example, TERMINATOR=$C(0) makes <NUL> the terminator.
When [NO]ESCAPE is in effect, TERMINATOR controls whether or not <ESC>
or <CSI> are treated as terminators, however, when ESCAPE processing is
enabled, the entire escape sequence is treated as a terminator
regardless of the TERMINATOR specification.
NOTERMINATOR eliminates all terminators. When a terminal has all
terminators disabled, fixed length READ and READ * terminate on receipt
of some number of characters, and a timed READ terminates on timeout,
but any other READ only terminates when the input fills the terminal
read buffer.
By default, terminals recognize <CR> and <ESC> as terminators, (i.e.,
TERMINATOR=$C(13,27)). TERMINATOR="" restores the default. However,
unless the terminal has PASTHRU, the operating system interprets some
escape sequences rather than passing them to the READ.
Example:
GTM> USE $P:TERM=$C(26,13,11,7)
This example enables the ASCII characters <SUB>, <CR>, <VT> and <BEL>
as READ terminators.
4 TRUNCATE
[NO]TRUNCATE Applies to: Sequential Files
Enables or disables overwriting of existing data in sequential files.
Because the position of each record depends on the prior record, a
WRITE destroys the ability to reliably position to subsequent records
in a file. Therefore, by default (NOTRUNCATE), GT.M permits WRITEs only
when the file pointer is positioned at the end-of-file. When a device
has TRUNCATE enabled, a WRITE issued when the file pointer is not at
end-of-file truncates the file by destroying all data from the file
pointer to the end-of-file.
By default, OPEN accesses files NOTRUNCATE, which does not allow
overwriting of sequential files.
This deviceparameter may not be supported by your platform.
4 TTSYNC
[NO]TTSYNC Applies to: Terminals and Printers
Enables or disables recognition of XON/XOFF for terminal output. A
terminal may have its own handling of XON/XOFF, controlled by a
set-up mode or by switches. If an application requires program
recognition of <CTRL-S> and <CTRL-Q>, the terminals may require
reconfiguration.
4 TYPEAHEAD
[NO]TYPEAHEAD Applies to: Terminals and Printers
Enables or disables type-ahead buffering for a terminal. With
NOTYPEAHEAD and no outstanding READ, the terminal device driver
discards input entered at the terminal. With TYPEAHEAD and no
outstanding READ, the device driver stores input entered at the
terminal in a type-ahead buffer. The device driver uses data from the
type-ahead buffer for subsequent READs.
The size of the type-ahead buffer limits the amount of data entered at
the terminal that the device driver can store in anticipation of future
READs.
By default, the terminal device driver accepts TYPEAHEAD.
4 UPSCROLL
UPSCROLL Applies to: Terminals and Printers
Moves the cursor down one line on the terminal screen. If $Y=LENGTH-1,
UPSCROLL sets $Y=0. Otherwise UPSCROLL increments $Y by one. If the
cursor is physically at the bottom of the page, the screen scrolls up
one line. UPSCROLL does not change the column position or $X.
4 WIDTH
[Z]WIDTH=intexpr Applies to: Terminals and Printers, Socket Device,
NULL Device, and Sequential Files
Sets the device's logical record size and enables WRAP.
NOWRAP and WIDTH supersede each other. When WIDTH and NOWRAP appear
together on the same USE command, the final one controls the device
behavior. For a terminal, WIDTH=0 is equivalent to WIDTH=n:NOWRAP,
where n is the default length of a logical record on that terminal.
Terminals inherit their default WIDTH in GT.M from the invoking shell
environment. The default WIDTH for null and socket device is 255.
4 WRAP
[Z][NO]WRAP Applies to: Terminals and Printers, FIFO, Socket Device,
NULL Device, and Sequential Files
Enables or disables automatic record termination. When the current
record size ($X) reaches the maximum WIDTH and the device has WRAP
enabled, GT.M starts a new record, as if the routine had issued a WRITE
! command.
NOWRAP causes GT.M to require a WRITE ! to terminate the record. NOWRAP
allows $X to become greater than the device WIDTH for terminals.
By default, WIDTH sets WRAP. When WIDTH and NOWRAP appear together on
the same USE command, the last one controls the device behavior.
By default, records WRAP.
4 X
X=intexpr Applies to: Terminals and Printers
$X positions the cursor to a vertical column on the terminal. If NOWRAP
is enabled or intexpr<WIDTH, the terminal device driver sets
$X=intexpr. If WRAP is enabled and intexpr>WIDTH, GT.M sets
$X=intexpr#WIDTH, where # is the GT.M modulo operator. The resulting $X
determines the actual physical position.
To ensure that $Y and $X match what is occurring visually on the
terminal, the GT.M deviceparameters and the device characteristics must
match at all times. For example, if a process initiates a subprocess
that changes the terminal wrap setting from NOWRAP, to WRAP, GT.M
returns to the NOWRAP condition when the subprocess completes, and
wraps on the terminal do not reflect in the values of $X and $Y.
The terminal hardware may affect physical cursor positioning. The X
deviceparameter does not change the cursor row or update $Y.
4 Y
Y=intexpr Applies to: Terminals and Printers
Positions the cursor to a horizontal row on the terminal.
The terminal device driver sets $Y=intexpr#LENGTH, where # is the GT.M
modulo operator. If intexpr<LENGTH, the resulting $Y determines the
physical position. If intexpr>LENGTH, the cursor is positioned so that
$Y=intexpr#LENGTH, where # is the GT.M module operator. The terminal
hardware may affect physical cursor positioning.
To ensure that $Y and $X match what is occurring visually on the
terminal, the GT.M deviceparameters and the device characteristics must
match at all times. For example, if a process initiates a subprocess
that changes the terminal wrap setting from NOWRAP, previously set with
the GT.M USE command to WRAP, GT.M does not reflect the change when the
subprocess completes. Therefore, wraps on the terminal do not reflect
in the values of $X and $Y.
The Y deviceparameter does not change the cursor column or update $X.
4 ZBFSIZE
ZBFSIZE Applies to: Socket Device
Allocates a buffer used by GT.M when reading from a socket. The ZBFSIZE
deviceparameter should be at least as big as the largest message
expected.
By default, the size of ZBFSIZE is 1024 and the maximum it can be is
1048576.
4 ZDELAY
Z[NO]DELAY Applies to: Socket Device
Controls buffering of data packets by the system TCP stack using the
TCP_NODELAY option to the SETSOCKOPT system call. This behavior is
sometimes known as the Nagle algorithm. The default is ZDELAY. This
delays sending additional packets until either an acknowledgement of
previous packets is received or an interval passes. If several packets
are sent from one end of a connection before the other end responds,
setting ZNODELAY may be desirable though at the cost of additional
packets being transmitted over the network. ZNODELAY must be fully
spelled out.
4 ZFF
Z[NO]FF=expr Applies to: Socket Device
expr specifies a string of characters, typically in $CHAR() format to
send to socket device, whenever a routine issues a WRITE #. When no
string is specified or when ZFF="", then no characters are sent. The
default in GT.M is ZNOFF.
4 ZIBFSIZE
ZIBFSIZE Applies to: Socket Device
Sets the buffer size used by the network software (setsockopt
SO_RCVBUF).
The default and the maximum values depend on the platform and/or system
parameters.
4 ZLISTEN
ZLISTEN=expr Applies to: Socket Device
A new socket is allocated to listen for a connection. It is made the
current socket for the device, if the operation is successful. Upon
successful completion, $KEY is set to the format of
"BOUND|<socket handle>|<port number>"
otherwise, $KEY is assigned the empty string.
expr specifies the protocol and protocol specific information.
Currently, TCP/IP is the only protocol GT.M supports. expr must be of
the format "<port>:TCP", where port specifies the port number at which
the socket is waiting for a connection.
2 Read
Read
The READ command transfers input from the current device to a global or
local variable specified as a READ argument. For convenience, READ also
accepts arguments that perform limited output to the current device.
The format of the READ command is:
R[EAD][:tvexpr] glvn|*glvn|glvn#intexpr|strlit|fcc[,...]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o A subscripted or unsubscripted global or local variable name
specifies a variable into which to store the input; the variable
does not have to exist prior to the READ; if the variable does
exist prior to the READ, the READ replaces its old value.
o When an asterisk (*) immediately precedes the variable name, READ
accepts one character of input and places the ASCII code for that
character in the variable.
o When a number sign (#) and a non-zero integer expression
immediately follow the variable name, the integer expression
determines the maximum number of characters accepted as input to
the read; such reads terminate when GT.M reads the number of
characters specified by the integer expression or a terminator in
the input stream, whichever occurs first.
o To provide a concise means of issuing prompts, GT.M sends string
literal and format control character (!,?intexpr,#) arguments of a
READ to the current device as if they were arguments of a WRITE.
o An indirection operator and an expression atom evaluating to a list
of one or more READ arguments form a legal argument for a READ.
The maximum length of the input string is the smaller of the device
buffer size limitation or the GT.M maximum string length (32,767
characters). If a record is longer than the maximum record length, GT.M
returns the record piece by piece during sequential reads, for devices
that allow it.
When a string literal appears as an argument to a READ, M writes the
literal to the current device. String literals appear as READ arguments
to serve as prompts for input. GT.M does not permit expression
arguments on a READ to act as prompts. Variable prompts must appear as
arguments to a WRITE. If a variable appears as an argument to a READ,
GT.M always interprets it as input, never as output. This facility is
used mostly with terminal I/O.
The READ commands adjust $X and $Y, based on the length of the input
read.
3 Read_Comm
READ * Command
The READ * command reads one character from the current device and
returns the decimal ASCII representation of that character into the
variable specified for the READ * command. READ * appears most
frequently in communication protocols, or in interactive programs where
single character answers are appropriate.
The following example reads the value "A", and returns the decimal
ASCII representation of "A" in the variable X.
Example:
GTM> READ *X
A
GTM> WRITE X
65
If a timeout occurs before GT.M reads a character, the READ * returns a
negative one (-1) in the variable.
3 Read_maxlen_Comm
READ X#maxlen Command
The READ X#maxlen command limits the maximum size of the input to a
maximum of "maxlen" characters, where maxlen is an integer expression.
If a READ follows a READ X#maxlen command, the READ returns the
remainder of the current record.
If a terminator arrives before maxlen characters are received the READ
X#maxlen terminates.
2 Write
Write
The WRITE command transfers a character stream specified by its
arguments to the current device.
The format of the WRITE command is:
W[RITE][:tvexpr] expr|*intexpr|fcc[,...]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o An expression argument supplies the text of a WRITE.
o When a WRITE argument consists of a leading asterisk (*) followed
by an integer expression, WRITE outputs one character associated
with the ASCII code specified by the integer evaluation of the
expression.
o WRITE also accepts format control characters as arguments; format
control characters modify the position of a virtual cursor: an
exclamation point (!) produces the device specific record
terminator (for example, new line for a terminal), a number sign
(#) produces device specific page terminator (for example, form
feed for a terminal) and a question mark (?) followed by an
expression moves the virtual cursor to the column specified by the
integer evaluation of the expression if the virtual cursor is to
the "left" of the specified column.
o When directed to a device bound to a mnemonicspace, WRITE also
accepts controlmnemonics, which are keywords specific to the
binding - they are delimited by a slash (/) prefix and optionally
followed by a parenthetical list of arguments. The parentheses "(
)" are optional when there are no arguments, but must appear even
if there is a single argument
o An indirection operator and an expression atom evaluating to a list
of one or more WRITE arguments form a legal argument for a WRITE.
GT.M can write up to 32,767 bytes (the GT.M maximum string length) as a
result of a single WRITE argument. GT.M buffers output into a "logical
record" for all devices except sockets without DELIMITERs and
sequential devices with STREAM enabled. The WRITE command appends a
string to the current record of the current device. GT.M does not write
to the output device until the buffer is full, a GT.M format control
character forces a write, a USE command, a CLOSE command, or, for
terminals, the buffer becomes stale.
Each device has a WIDTH and a LENGTH that define the virtual "page".
The WIDTH determines the maximum size of a record for a device, while
the LENGTH determines how many records fit on a page. When the current
record size ($X) reaches the maximum WIDTH and the device has WRAP
enabled, GT.M starts a new record. When the current line ($Y) reaches
the maximum LENGTH, GT.M starts a new page.
A WRITE with an asterisk preceding the argument, which it would expect
to be a decimal ASCII representation, writes the character
corresponding to the ASCII representation. The WRITE command also has
several format control characters that allow the manipulation of the
virtual cursor. For all I/O devices, the GT.M format control characters
do the following:
WRITE ! Clears $X and increments $Y and terminates the logical
record in progress. The definition of "logical record" varies from
device to device, and is discussed in each device section.
WRITE # Clears $X and $Y and terminates the logical record in
progress.
WRITE ?n If n is greater than $X, writes n-$X spaces to the device,
bringing $X to n. If n is less than or equal to $X, WRITE ?n has no
effect. When WRAP is enabled and n exceeds the LENGTH of the line,
WRITE ?n increments $Y.
For more information, refer to the sections on specific I/O devices.
2 Close
Close
The CLOSE command breaks the connection between a process and a device.
The format of the CLOSE command is:
C[LOSE][:tvexpr] expr[:(keyword[=expr][:...])][,...]
o The optional truth-valued expression immediately following the
command is a command postconditional that controls whether or not
GT.M executes the command.
o The required expression specifies the device to CLOSE.
o The optional keywords specify deviceparameters that control device
behavior; some deviceparameters take arguments delimited by an
equal sign (=); if there is only one keyword, the surrounding
parentheses are optional.
o An indirection operator and an expression atom evaluating to a list
of one or more CLOSE arguments form a legal argument for a CLOSE.
When a CLOSE is issued, GT.M flushes all pending output to the device,
and processes any deviceparameters. CLOSEing a device not currently
OPEN has no effect.
GT.M retains the characteristics of all device types, except a
sequential file, for use in case of subsequent re-OPENs. If the device
is a sequential file, characteristics controlled by deviceparameters
are lost after the CLOSE.
If the device being CLOSEd is $IO, GT.M implicitly USEs $PRINCIPAL.
GT.M ignores CLOSE $PRINCIPAL.
Example:
CLOSE SD:RENAME=SD_".SAV"
This closes the device and, if it is a disk file, renames it to have
the type .SAV.
3 Close_DeviParam
CLOSE Deviceparamenter
4 DELETE
DELETE Applies to: Sequential Files, and FIFO
Instructs GT.M to delete the current version of the disk file after
GT.M closes it.
4 EXCEPTION
EXCEPTION=expr Applies to: All devices
Defines an error handler for an I/O device. The expression must contain
a fragment of GT.M code (for example, GOTO ERRFILE) that GT.M XECUTEs
when the driver for the device detects an error, or an entryref to
which GT.M transfers control, as appropriate for the current
gtm_ztrap_form.
For more information on error handling, refer to the "Error Processing"
chapter in GT.M Programmer's Guide.
4 GROUP
GROUP=expr Applies to: Sequential Disk Files, and FIFO
Specifies access permission on a UNIX file for other users in the file
owner's group. The expression is a character string evaluating to null
or to any combination of the letters RWX, indicating respectively Read,
Write, and eXecute access. When any one of these deviceparameters
appears on a CLOSE of a new file, any user category that is not
explicitly specified is given the default character string. When any
one of these deviceparameters appears on a CLOSE of an existing file,
any user category (OWNER, SYSTEM, WORLD), that is not explicitly
specified remains unchanged.
In order to modify file security, the user who issues the CLOSE must
have ownership.
By default, CLOSE does not modify the permissions on an existing file.
4 OWNER
OWNER=expr Applies to: Sequential Disk Files, and FIFO
Specifies access permission on a UNIX file for the owner of the file.
The expression is a character string evaluating to null or to any
combination of the letters RWX, indicating respectively Read, Write,
and eXecute access. When any one of these deviceparameters appears on a
CLOSE of a new file, any user category that is not explicitly specified
is given the default mask. When any one of these deviceparameters
appears on a CLOSE of an existing file, any user category (GROUP,
SYSTEM, WORLD), that is not explicitly specified remains unchanged.
In order to modify file security, the user who issues the CLOSE must
have ownership.
By default, CLOSE does not modify the permissions on an existing file.
4 RENAME
RENAME=expr Applies to: Sequential Disk Files
Changes the file name to the name contained in the argument string.
When the expression omits part of the pathname, GT.M constructs the
full pathname by applying the defaults discussed in the section on
device specifications.
If the process has sufficient access permissions, it may use RENAME to
specify a different directory as well as file name. RENAME cannot move
a file to a different device.
4 SOCKET
SOCKET=expr Applies to: Socket Device
The socket specified in expr is closed. Specifying a socket that has
not been previously OPENed generates an error. If no SOCKET
deviceparameter is specified on a CLOSE for a socket device, the socket
device and all sockets associated with it are closed.
4 SYSTEM
SYSTEM=expr Applies to: Sequential Disk Files, and FIFO
This deviceparameter is a synonym for OWNER that is maintained in UNIX
for compatibility with VMS applications.
By default, CLOSE does not modify the permissions on an existing file.
4 UIC
UIC=exprgroup number Applies to: Sequential Disk Files, and FIFO
Specifies the group that has access to the file. The format of the
string is "g,i" where g is a decimal number representing the group
portion of the UIC and i is a decimal number representing the
individual portion. A process with the VMS privilege CMKRNL may set the
file UIC to a UIC other than the UIC under which it is running, thereby
giving ownership of the file to another user.
Specifies the owner and affects access to the file. The expression
evaluates to the numeric identifier of the new owner.
4 WORLD
WORLD=expr Applies to: Sequential Disk Files, and FIFO
Specifies access permissions for users not in the owner's group on a
UNIX file. The expression is a character string evaluating to null or
to any combination of the letters RWX, indicating respectively Read,
Write, and eXecute access. When any one of these deviceparameters
appears on a CLOSE of a new file, any user category that is not
explicitly specified is given the default character string. When any
one of these deviceparameters appears on a CLOSE of an existing file,
any user category (OWNER, GROUP, SYSTEM), that is not explicitly
specified remains unchanged.
In order to modify file security, the user who issues the CLOSE must
have ownership.
By default, CLOSE and CLOSE do not modify the permissions on an
existing file. Unless otherwise specified, when CLOSE creates a new
file, it establishes security using standard defaulting rules.
In order to modify file security, the user who issues the CLOSE must
have ownership.
By default, CLOSE does not modify the permissions on an existing file.
1 M_Utility_Rtns
M Utility Routines
GT.M provides library utilities to perform frequently used tasks, and
to access frequently used information. Most of the utilities are for
GT.M programmers, but some provide tools for system administration and
operation.
The GT.M utilities fall into the following general categories:
o Date and time utilities
o Conversion utilities
o Mathematic utilities
o Global utilities
o Routine utilities
o Internationalization utilities
o System Management utilities
The GT.M distribution includes the source files for these utilities.
The default installation compiles them to produce object modules in the
$gtm_dist distribution library.
You may wish to examine the utilities and include some of them in your
programs if the programs access the function frequently or you may want
to modify the utilities to better fit your particular needs. If you
modify a utility, store your copy in a directory that precedes gtm_dist
in the search list $ZROUTINES to prevent a new release of GT.M from
overlaying your copy.
2 Using_Util
Using the Utilities
You can either use a utility in Direct Mode or include it in a source
application program with one or more of the following formats.
Italicized items are to be supplied by the user:
o DO ^%UTILITYNAME
o DO LABEL^%UTILITYNAME
o $$FUNC^%UTILITYNAME[(para1,...)]
Many utilities contain labels that invoke variations of the basic
utility functionality. Some also provide the label FUNC to invoke an
extrinsic function with optional or required parameters.
GT.M passes input to non-extrinsic forms of the utilities interactively
or by using "input" variables. GT.M passes output from non-extrinsic
forms of the utilities using "output" variables. For extrinsic entry
points, the utilities receive input as parameters and pass output as
the returned result. For other entry points, GT.M uses predefined
"input" and "output" variables to pass information. Some utilities
interactively request user inputs and display their results. Each
utility is described individually in this chapter where appropriate
labels, input, and output variables are identified.
By convention, the utilities use upper-case variables for external
input and output. Since M is case-sensitive, when an invocation uses a
lower-case or misspelled variable name, the routine does not output the
expected information. Instead it supplies a default value, if one
exists, or produces an error message.
Example:
GTM>SET %ds="11/22/2002"
GTM>DO INT^%DATE
GTM>ZWRITE
%DN=59123
%ds="11/22/2002"
This example sets the lowercase variable %ds to the date 11/22/2002.
Since the %DATE routine expects the input to be provided in the
uppercase %DS variable, it returns a default value in the output
variable $DN. The default is the $HOROLOG format of the current date,
which is 11/15/2002 in the example.
2 Date_Time_Util
Date and Time Utilities
The date and time utilities are:
%D Displays the current date using the [d]d-mmm-[yy]yy format.
%DATE Converts input date to the $HOROLOG format.
%H Converts date and time to and from $HOROLOG format.
%T Displays the current time in [h]h:mm AM/PM format.
%TI Converts time to $HOROLOG format.
%TO Converts the current time from $HOROLOG format to [h]h:mm AM/PM
format.
For details and examples, refer to the GT.M Programmer's Guide.
The "%" sign has been removed from the topic headings below,
intentionally.
3 D_
%D
The %D utility displays the current date using the [d]d-mmm-[yy]yy
format. If a routine uses this function repetitively, put the utility
code directly into the M program.
4 Util_Labels
Utility Labels
INT Sets variable %DAT to current date.
FUNC[()] Invokes an extrinsic function returning today's date.
4 Output_Vars
Output Variables
%DAT Contains the current date.
4 Ex_of_D
Examples of %D
For the following examples, $ZDATEFORM is assumed to be one (1).
Example:
GTM>DO ^%D
22-NOV-2002
This example invokes %D in Direct Mode. Then %D displays the current
date.
Example:
GTM>DO INT^%D
GTM>ZWRITE
%DAT="22-NOV-2002"
This example invokes %D with the label INT (INT^%D). The variable %DAT
contains the current date. ZWRITE displays the contents of the output
variable.
Example:
GTM>WRITE $$FUNC^%D
22-NOV-2002
This example invokes %D as an extrinsic function with the label FUNC.
$$FUNC^%D returns today's date.
3 DATE
%DATE
The %DATE utility converts an input date to the $HOROLOG format. The
$HOROLOG format represents time as the number of days since December
31, 1840. The routine has entry points for interactive or
non-interactive use.
4 Util_Labels
Utility Labels
INT Converts %DS input non-interactively, if defined, otherwise the
current date.
FUNC(t) Invokes an extrinsic function returning $HOROLOG format of
the argument.
4 Prompts
Prompts
Date: Interactively requests a date for conversion to $HOROLOG
format.
4 Input_Vars
Input Variables
%DS Contains input date; refer to %DATE Input Formats table.
4 Output_Vars
Output Variables
%DN Contains output date in $HOROLOG format
4 Ex_of_DATE
Examples of %DATE
Example:
GTM>DO ^%DATE
Date:
GTM>ZWRITE
%DN=59105
This example invokes %DATE at the GTM> prompt. After pressing <RETURN>
at the Date: prompt, %DATE converts today's date (for example,
10/28/2002) to the $HOROLOG format. ZWRITE displays the contents of the
output variable.
Example:
GTM>DO INT^%DATE
GTM>ZWRITE
%DN=59105
This example invokes INT^%DATE, which converts the current date
non-interactively into $HOROLOG format. ZWRITE displays the contents of
the output variable.
Example:
GTM>SET %DS="10/20/2002"
GTM>DO INT^%DATE
GTM>ZWRITE
%DN=59097
%DS="10/20/2002"
This example sets the input variable %DS prior to invoking INT^%DATE,
which converts that date non-interactively to $HOROLOG format.
Example:
GTM>WRITE $$FUNC^%DATE("10/20/2002")
59097
This example invokes %DATE with the label FUNC as an extrinsic function
to convert an input date to $HOROLOG. If the invocation does not supply
a date for $$FUNC^%DATE, FUNC converts the current date.
Example:
GTM>WRITE $ZDATEFORM
1975
GTM>WRITE $$FUNC^%DATE("10/20/80")
51062
GTM>WRITE $ZDATE(51062)
10/20/1980
GTM>WRITE $$FUNC^%DATE("10/20/10")
62019
GTM>WRITE $ZDATE(62019)
10/20/2010
This example shows the use of a year limit in $ZDATEFORM. Two digit
years are interpreted to be in the interval (1975, 2074) since
$ZDATEFORM is 1975; the input year "80" is interpreted as the year
"1980" and "10" is interpreted as the year "2010". The example invokes
FUNC^%DATE to convert the input date to $HOROLOG format. $ZDATE() is
used to convert the $HOROLOG format date to mm/dd/yyyy format.
3 H
%H
The %H utility converts date and time to and from $HOROLOG format.
4 Util_Labels
Utility Labels
%CDS Converts %DT $HOROLOG input date to mm/dd/yyyy format.
%CTS Converts %TM $HOROLOG input time to external format.
%CDN Converts %DT input date to $HOROLOG format.
%CTN Converts %TM input time to $HOROLOG format.
CDS(dt) Extrinsic entry that converts the $HOROLOG argument to
external date format.
CTS(tm) Extrinsic entry that converts the $HOROLOG argument to
external time format.
CDN(dt) Extrinsic entry that converts the argument to $HOROLOG
format.
CTN(tm) Extrinsic entry that converts the argument to $HOROLOG
format.
4 Input_Vars
Input Variables
%DT Contains input date in either $HOROLOG or mm/dd/[yy]yy format,
depending on the format expected by the utility entry point.
%TM Contains input time in either $HOROLOG or [h]h:mm:ss format,
depending on the format expected by the utility entry point.
4 Output_Vars
Output Variables
%DAT Contains converted output date,
%TIM Contains converted output time,
4 Ex_of_H
Examples of %H
Example:
GTM>SET %DT=+$H DO %CDS^%H
GTM>ZWRITE
%DAT="10/20/2002"
%DT=59097
This example sets %DT to the current date in $HOROLOG format and
converts it to mm/dd/yyyy format by invoking %H at the label %CDS. %H
returns the converted date in the variable %DAT. ZWRITE displays the
contents of the variables.
Example:
GTM>SET %DT="10/20/2002" DO %CDN^%H
GTM>ZWRITE
%DAT=59097
%DT="10/20/2002"
This example sets the variable %DT to a date in mm/dd/yyyy format and
invokes %H at the label %CDN. %H returns the converted date in the
variable %DAT. ZWRITE displays the contents of the variables.
Example:
GTM>SET %TM=$P($H,",",2) DO %CTS^%H
GTM>ZWRITE
%TIM="17:41:18"
%TM=63678
This example sets the variable %TM to the current time in $HOROLOG
format using a $PIECE() function to return only those digits of the
$HOROLOG string that represent the time. The example then invokes %H at
the label %CTS. %H returns the converted time in the variable %TIM.
ZWRITE displays the contents of the variables.
Example:
GTM>SET %TM="17:41:18" DO %CTN^%H
GTM>ZWRITE
%TIM=63678
%TM="17:41:18"
This example sets the variable %TM to a time in hh:mm:ss format, and
invokes %H at the label %CTN. %H returns the converted time in the
variable %TIM. ZWRITE displays the contents of the variables.
Example:
GTM>WRITE $$CDS^%H(59130)
11/22/2002
This invokes CDS^%H as an extrinsic function to convert the external
argument to external date format.
Example:
GTM>WRITE $ZDATEFORM
1980
GTM>WRITE $$CDN^%H("10/20/02")
59097
GTM>WRITE $ZDATE(59097)
10/20/2002
GTM>WRITE $$CDN^%H("10/20/92")
55445
GTM>WRITE $ZDATE(55445)
10/20/1992
This example shows the use of a year limit in $ZDATEFORM. Two digit
years are interpreted to be in the interval of 1980 - 2079; since
$ZDATEFORM is 1980, the input year "02" is interpreted as "2002" and
"92" is interpreted as "1992". This example invokes CDN^%H to convert
the argument in mm/dd/yy format to $HOROLOG format. $ZDATE() is used to
conver the $HOROLOG format date to mm/dd/yyyy format.
3 T_
%T
The %T utility displays the current time in [h]h:mm AM/PM. If a routine
uses this function repetitively, put the utility code directly into the
M program.
4 Util_Labels
Utility Labels
INT Sets %TIM to current time in [h]h:mm AM/PM format.
FUNC[()] Invokes an extrinsic function returning the current time.
4 Output_Vars
Output Variables
%TIM Contains current time in [h]h:mm AM/PM format.
4 Ex_of_T
Examples of %T
Example:
GTM>DO ^%T
8:30 AM
This example invokes %T, which prints the current time and does not set
%TIM.
Example:
GTM>DO INT^%T
GTM>ZWRITE
%TIM="8:30 AM"
This example invokes INT^%T, which sets the variable %TIM to the
current time. ZWRITE displays the contents of the variable.
Example:
GTM>WRITE $$FUNC^%T
8:30 AM
This example invokes FUNC as an extrinsic function, which returns the
current time.
3 TI
%TI
The %TI utility converts time to $HOROLOG format. The $HOROLOG format
represents time as the number of seconds since midnight. %TI returns
the converted time in the variable %TN. The routine has entry points
for interactive or non-interactive use.
4 Util_Labels
Utility Labels
INT Non-interactively converts %TS to $HOROLOG format; if %TS is
not defined, then current time is converted.
FUNC[(ts)] Invokes an extrinsic function returning $HOROLOG format
of the argument, or if no argument, the $HOROLOG format of the
current time.
4 Prompts
Prompts
Time: Requests time in [h]h:mm:ss format to convert to $HOROLOG
format.
4 Input_Vars
Input Variables
%TS Contains input time.
4 Output_Vars
Output Variables
%TN Contains output time in $HOROLOG format
4 Ex_of_TI
Examples of %TI
Example:
GTM>DO ^%TI
Time: 4:02 PM
GTM>ZWRITE
%TN=57720
This example invokes %TI, which prompts for an input time. Press
<RETURN> to convert the current time. ZWRITE displays the contents of
the output variable.
Example:
GTM>ZWRITE
GTM>DO INT^%TI
GTM>ZWRITE
%TN=40954
This example invokes INT^%TI to convert the current time
non-interactively. ZWRITE displays the contents of the output variable
%TN.
Example:
GTM>SET %TS="8:30AM"
GTM>DO INT^%TI
GTM>ZWRITE
%TN=30600
%TS="8:30AM"
This example sets the variable %TS prior to invoking INT^%TI. %TI uses
%TS as the input time. ZWRITE displays the contents of the variables.
Example:
GTM>WRITE $$FUNC^%TI("8:30AM")
30600
This example invokes %TI as an extrinsic function to convert the
supplied time to $HOROLOG format. If there is no argument (i.e.,
$$FUNC^%TI), %TI converts the current time.
3 TO
%TO
The %TO utility converts the input time from $HOROLOG format to [h]h:mm
AM/PM format. Put the utility code directly into the M program if the
routine uses this function repetitively.
4 Util_Labels
Utility Labels
INT Converts non-interactively %TS, or if %TS is not defined the
current time to [h]h:mm AM/PM format.
4 Input_Vars
Input Variables
%TN Contains input time in $HOROLOG format.
4 Output_Vars
Output Variables
%TS Contains output time in [h]h:mm AM/PM format.
4 Ex_of_TO
Examples of %TO
Example:
GTM>DO INT^%TI,^%TO
GTM>ZWRITE
%TN=62074
%TS="5:14 PM"
This example invokes INT^%TI to set %TN to the current time and invokes
%TO to convert the time contained in %TN to the [h]h:mm AM/PM format.
%TO returns the converted time in the variable %TS. ZWRITE displays the
contents of the variables.
2 Conversion_Util
Conversion Utilities
The conversion utilities are:
%DH Decimal to hexadecimal conversion.
%DO Decimal to octal conversion.
%HD Hexadecimal to decimal conversion.
%HO Hexadecimal to octal conversion.
%LCASE Converts a string to all lower case.
%OD Octal to decimal conversion.
%OH Octal to hexadecimal conversion.
%UCASE Converts a string to all upper case.
The conversion utilities can be invoked as extrinsic functions.
The "%" sign has been removed from the topic headings below,
intentionally.
3 DH
%DH
The %DH utility converts numeric values from decimal to hexadecimal.
%DH defaults the length of its output to eight digits. However the
input variable %DL overrides the default and controls the length of the
output. The routine has entry points for interactive or non-interactive
use.
4 Util_Labels
Utility Labels
INT Converts interactively entered decimal number to hexadecimal
number with the number of digits specified.
FUNC(d[,l]) Invokes %DH as an extrinsic function returning the
hexadecimal equivalent of the argument.
4 Input_Vars
Input Variables
%DH As input, contains input decimal number.
%DL Specifies how many digits appear in the output, defaults to
eight.
4 Prompts
Prompts
Decimal: Requests a decimal number for conversion to hexadecimal.
Digits: Requests the length of the output in digits; eight by
default.
4 Output_Vars
Output Variables
%DH As output, contains the converted number in hexadecimal.
4 Ex_of_DH
Examples of %DH
Example:
GTM>DO INT^%DH
Decimal: 12
Digits: 1
GTM>ZWRITE
%DH="C"
This example invokes %DH interactively with INT^%DH. %DH prompts for a
decimal number and output length, then returns the result in the
variable %DH. ZWRITE displays the contents of the variables.
Example:
GTM>SET %DH=12
GTM>DO ^%DH
GTM>ZWRITE
%DH="0000000C"
%DL=8
This example sets the read-write variable %DH to 12 and invokes %DH to
convert the number to a hexadecimal number. Because the number of
digits was not specified, %DH used the default of 8 digits. Set %DL to
specify the number of output digits.
Example:
GTM>WRITE $$FUNC^%DH(12,4)
000C
This example invokes %DH as an extrinsic function using the FUNC label.
The first argument specifies the input decimal number and the optional,
second argument specifies the number of output digits. If the extrinsic
does not have a second argument, the length of the output defaults to
eight characters.
3 DO
%DO
The %DO utility converts numeric values from decimal to octal. The
default length of its output is 12 digits. The value assigned to the
input variable %DL overrides the default and controls the length of the
output. The routine has entry points for interactive or non-interactive
use.
4 Util_Labels
Utility Labels
INT Converts the specified decimal number to an octal number with
the specified number of digits, interactively.
FUNC(d[,ln]) Invokes %DO as an extrinsic function, returning the
octal equivalent of the argument.
4 Prompts
Prompts
Decimal: Requests a decimal number for conversion to octal.
Digits: Requests the length of the output in digits; 12 by default.
4 Input_Vars
Input Variables
%DO As input, contains input decimal number.
%DL Specifies the number of digits in the output, defaults to 12.
4 Output_Vars
Output Variables
%DO As output, contains the converted number in octal.
4 Ex_of_DO
Examples of %DO
Example:
GTM>DO INT^%DO
Decimal: 12
Digits: 4
GTM>ZWRITE
%DO="0014"
This example invokes %DO interactively with INT^%DO. %DO prompts for a
decimal number and an output length. If the output value of %DO has
leading zeros, the value is a string. ZWRITE displays the contents of
the variables.
Example:
GTM>SET %DO=12
GTM>DO ^%DO
GTM>ZWRITE
%DO="000000000014"
This example sets the read-write variable %DO to 12 and invokes %DO to
convert the number non-interactively. Because the number of digits was
not specified, %DO used the default of 12 digits. Set %DL to specify
the number of output digits. ZWRITE displays the contents of the
variables.
Example:
GTM>WRITE $$FUNC^%DO(12,7)
0000014
This example invokes %DO as an extrinsic function with the label FUNC.
The first argument specifies the number to be converted and the
optional, second argument specifies the number of output digits. If the
second argument is not specified, %DO uses the default of 12 digits.
3 HD
%HD
The %HD utility converts numeric values from hexadecimal to decimal.
%HD returns the decimal number in the read-write variable %HD. %HD
rejects input numbers beginning with a minus (-) sign and returns null
(""). The routine has entry points for interactive or non-interactive
use.
4 Util_Labels
Utility Labels
INT Converts hexadecimal number entered interactively to decimal
number.
FUNC(h) Invokes %HD as an extrinsic function returning the decimal
equivalent of the argument.
4 Prompts
Prompts
Hexadecimal: Requests a hexadecimal number for conversion to
decimal.
4 Input_Vars
Input Variables
%HD As input, contains input hexadecimal number.
4 Output_Vars
Output Variables
%HD As output, contains the converted number in decimal.
4 Ex_of_HD
Examples of %HD
Example:
GTM>DO INT^%HD
Hexadecimal:E
GTM>ZWRITE
%HD=14
This example invokes %HD in interactive mode with INT^%HD. %HD prompts
for a hexadecimal number, then returns the converted number in the
variable %HD. ZWRITE displays the contents of the variable.
Example:
GTM>SET %HD="E"
GTM>DO ^%HD
GTM>ZWRITE
%HD=14
This example sets the read-write variable %HD to "E" and invokes %HD to
convert non-interactively the value of %HD to a decimal number. %HD
places the converted value into the read-write variable %HD.
Example:
GTM>WRITE $$FUNC^%HD("E")
14
This example invokes %HD as an extrinsic function with the label FUNC
and writes the results.
3 HO
%HO
The %HO utility converts numeric values from hexadecimal to octal. %HO
returns the octal number in the read-write variable %HO. %HO rejects
input numbers beginning with a minus (-) sign and returns null ("").
The routine has entry points for interactive or non-interactive use.
4 Util_Labels
Utility Labels
INT Converts hexadecimal number entered interactively to octal
number.
FUNC(h) Invokes %HO as an extrinsic function returning the octal
equivalent of the argument.
4 Prompts
Prompts
Hexadecimal: Requests a hexadecimal number for conversion to octal.
4 Input_Vars
Input Variables
%HO As input, contains input hexadecimal number.
4 Output_Vars
Output Variables
%HO As output, contains the converted number in octal.
4 Ex_of_HO
Examples pf %HO
Example:
GTM>DO INT^%HO
Hexadecimal:C3
GTM>ZWRITE
%HO=303
This example invokes %HO in interactive mode using INT^%HO. %HO prompts
for a hexadecimal number that it converts to an octal number. ZWRITE
displays the contents of the variable.
Example:
GTM>SET %HO="C3"
GTM>DO ^%HO
GTM>ZWRITE
%HO=303
This example sets the read-write variable %HO to "C3" and invokes %HO
to convert the value of %HO non-interactively. ZWRITE displays the
contents of the variable.
Example:
GTM>WRITE $$FUNC^%HO("C3")
303
This example invokes %HO as an extrinsic function with the FUNC label.
3 LCASE
%LCASE
The %LCASE utility converts a string to all lower-case letters. If a
routine uses this function repetitively, put the utility code directly
into the M program.
4 Util_Labels
Utility Labels
INT Converts interactively a string to lower-case.
FUNC(s) Invokes %LCASE as an extrinsic function returning the
lower-case form of the argument.
4 Prompts
Prompts
String: Requests a string for conversion to lower case.
4 Input_Vars
Input Variables
%S As input, contains string to be converted to lower case.
4 Output_Vars
Output Variables
%S As output, contains the converted string in lower case.
4 Ex_of_LCASE
Examples of %LCASE
Example:
GTM>DO INT^%LCASE
String: LABEL
Lower: label
This example invokes %LCASE in interactive mode using INT^%LCASE.
%LCASE prompts for a string that it converts to all lower case.
Example:
GTM>SET %S="Hello"
GTM>do ^%LCASE
GTM>zwrite
%S="hello"
This example sets the variable %S to the string "Hello" and invokes
%LCASE non-interactively to convert the string.
Example:
GTM>SET ^X="Hello"
GTM>WRITE $$FUNC^%LCASE(^X)
hello
This example sets the variable ^X to the string "Hello" and invokes
%LCASE as an extrinsic function that returns "hello" in lower case.
3 OD
%OD
The %OD utility converts numeric values from octal to decimal. %OD
returns the decimal number in the read-write variable %OD. %OD rejects
input numbers beginning with a minus (-) sign and returns null ("").
The routine has entry points for interactive or non-interactive use.
4 Util_Labels
Utility Labels
INT Converts octal number entered interactively to decimal number.
FUNC(oct) Invokes %OD as an extrinsic function returning the
decimal equivalent of the argument.
4 Prompts
Prompts
Octal: Requests an octal number for conversion to decimal.
4 Input_Vars
Input Variables
%OD As input, contains input octal number.
4 Output_Vars
Output Variables
%OD As output, contains the converted number in decimal.
4 Ex_of_OD
Examples of %OD
Example:
GTM>DO INT^%OD
Octal:14
GTM>ZWRITE
%OD=12
This example invokes INT^%OD to interactively convert the octal number
entered. %OD prompts for an octal number that it converts to a decimal.
%OD returns the converted value in the variable %OD.
Example:
GTM>SET %OD=14
GTM>DO ^%OD
GTM>ZWRITE
%OD=12
This example sets the read-write variable %OD to 14 and invokes %OD to
convert the number non-interactively. ZWRITE displays the contents of
the variables.
Example:
GTM>WRITE $$FUNC^%OD(14)
12
This example invokes %OD as an extrinsic function with the FUNC label.
The argument specifies the number to be converted.
3 OH
%OH
The %OH utility converts numeric values from octal to hexadecimal. %OH
returns the hexadecimal number in the read-write variable %OH. %OH
rejects input numbers beginning with a minus (-) sign. The routine has
entry points for interactive or non-interactive use. In interactive
mode, %OH rejects non-octal numbers with the following message, "Input
must be an octal number". In non-interactive mode, %OH returns a null
string ("") upon encountering a non-octal number.
4 Util_Labels
Utility Labels
INT Converts interactively octal number entered to hexadecimal
number.
FUNC(oct) Invokes %OH as an extrinsic function returning the
hexadecimal equivalent of the argument.
4 Prompts
Prompts
Octal: Requests an octal number for conversion to hexadecimal.
4 Input_Vars
Input Variables
%OH As input, contains input octal number.
4 Output_Vars
Output Variables
%OH As output, contains the converted number in hexadecimal.
4 Ex_of_OH
Examples of %OH
Example:
GTM>DO INT^%OH
Octal:16
GTM>ZWRITE
%OH="E"
This example invokes %OH in interactive mode using INT^%OH. %OH prompts
for an octal number that it converts to a hexadecimal number. ZWRITE
displays the contents of the variable.
Example:
GTM>SET %OH=16
GTM>DO ^%OH
GTM>ZWRITE
%OH="E"
This example sets the read-write variable %OH to 16 and invokes %OH to
convert the value of %OH non-interactively. ZWRITE displays the
contents of the variable.
Example:
GTM>WRITE $$FUNC^%OH(16)
E
This example invokes %OH as an extrinsic function with the FUNC label.
3 UCASE
%UCASE
The %UCASE utility converts a string to all upper-case letters. If a
routine uses this function repetitively, put the utility code directly
into the M program.
4 Util_Labels
Utility Labels
INT Converts a string to upper case interactively.
FUNC(s) Invokes %UCASE as an extrinsic function, returning the
upper-case form of the argument.
4 Prompts
Prompts
String: Requests a string for conversion to upper case.
4 Input_Vars
Input Variables
%S As input, contains string to be converted to upper case.
4 Output_Vars
Output Variables
%S As output, contains the converted string in upper case.
4 Ex_of_UCASE
Examples of %UCASE
Example:
GTM>DO INT^%UCASE
String: test
Upper: TEST
This example invokes %UCASE in interactive mode using INT^%UCASE.
%UCASE prompts for a string that it converts to all upper case.
Example:
GTM>SET ^X="hello"
GTM>WRITE $$FUNC^%UCASE(^X)
HELLO
This example sets the variable X to the string "hello" and invokes
%UCASE as an extrinsic function that returns "HELLO" in upper case.
2 Math_Util
Mathematic Utilities
The mathematic utilities are:
%EXP Raises one number to the power of another number.
%SQROOT Calculates the square root of a number.
The mathematic utilities can be invoked as extrinsic functions.
The "%" sign has been removed from the topic headings below,
intentionally.
3 EXP
%EXP
The %EXP utility raises one number provided to the power of another
number provided. While this utility provides an interactive interface
for exponential calculations, most production code would perform inline
calculation with the "**" operator. The routine has entry points for
interactive or non-interactive use.
4 Util_Labels
Utility Labels
INT Calculates a number to the power of another number
interactively.
FUNC(i,j) Invokes %EXP as an extrinsic function returning the first
argument raised to the power of the second argument.
4 Prompts
Prompts
Power: Requests an exponent or power.
Number: Requests a base number to raise by the power.
4 Input_Vars
Input Variables
%I As input, contains number to be raised to a power.
%J Contains exponential power by which to raise %I.
4 Output_Vars
Output Variables
%I As output, contains the result of the exponential calculation.
4 Ex_of_EXP
Examples of %EXP
Example:
GTM>DO INT^%EXP
Power: 3
Number: 12
12 raised to 3 is 1728
This example invokes %EXP in interactive mode using INT^%EXP. %EXP
prompts for an exponent (power) and a base number.
Example:
GTM>SET %I=2,%J=9
GTM>DO ^%EXP
GTM>ZWRITE
%I=512
%J=9
This example sets the read-write variable %I to 2, variable %J to 9,
and invokes %EXP to calculate the result. ZWRITE displays the contents
of the variables. %I contains the result.
Example:
GTM>WRITE $$FUNC^%EXP(2,9)
512
This example invokes %EXP as an extrinsic function with the label FUNC.
3 SQROOT
%SQROOT
The %SQROOT utility calculates the square root of a number provided.
While this utility provides an interactive interface for taking square
roots, most production code would perform inline calculation by raising
a number to the .5 power (n**.5). The routine has entry points for
interactive or non-interactive use.
4 Util_Labels
Utility Labels
INT Calculates the square root of a number interactively.
FUNC(s) Invokes %SQROOT as an extrinsic function returning the
square root of the argument.
4 Prompts
Prompts
The square root of: Requests a number.
4 Input_Vars
Input Variables
%X Contains the number for which to calculate the square root.
4 Output_Vars
Output Variables
%Y Contains the square root of %X.
4 Ex_of_SQROOT
Examples of %SQROOT
Example:
GTM>SET %X=81
GTM>DO ^%SQROOT
GTM>ZWRITE
%X=81
%Y=9
This example sets the variable %X to 81 and invokes %SQROOT to
calculate the square root non-interactively. ZWRITE displays the
contents of the variables.
Example:
GTM>DO INT^%SQROOT
The square root of: 81 is: 9
The square root of: <RETURN>
GTM>
This example invokes INT^%SQROOT interactively that prompts for a
number. The square root of the number appears on the same line. %SQROOT
then prompts for another number. Press <RETURN> to exit.
Example:
GTM>WRITE $$FUNC^%SQROOT(81)
9
This example invokes %SQROOT as an extrinsic function with the label
FUNC.
2 Glob_Util
Global Utilities
The Global utilities are:
%G Displays global variables and their values.
%GC Copies a global or global sub-tree.
%GCE Replaces a specified value or part of a value in a set of
variables.
%GD Displays existing globals in the current global directory
without displaying their values or descendants.
%GED Provides full-screen editing capabilities for global variables
and values.
%GI Loads global data from a sequential file into a GT.M database.
%GO Extracts global data from a GT.M database into a sequential
file.
%GSE Displays global variables and their values when the values
contain a specified string or number.
%GSEL Selects globals.
The "%" sign has been removed from the topic headings below,
intentionally.
3 G_
%G
The %G utility displays names, descendants and values of globals
currently existing in the database. Use %G to examine global variables
and their values. Enter a question mark (?) at any prompt to display
help information.
4 Prompts
Prompts
Output Device: <terminal>:
Requests a destination device; defaults to the principal device.
List ^ Requests the name, in ZWRITE format, of a global to display.
4 Ex_of_G
Examples of %G
Example:
GTM>do ^%G
Output Device: <terminal>: <RETURN>
List ^C
^C="CLASS"
^C(1)="MARY"
^C(1,2)="MATH"
^C(1,2,1)=80
^C(1,3)="BIO"
^C(1,3,1)=90
^C(2)="JOHN"
^C(3)="PETER"
List ^ <RETURN>
GTM>
This example lists the nodes of global ^C. %G displays the global and
its descendants and values, if the node exists.
Example:
GTM>do ^%G
Output Device: <terminal>: <RETURN>
List ^C(1)
^C(1)="MARY"
This example lists only the node entered and its value.
Example:
GTM>do ^%G
Output Device: <terminal>: <RETURN>
List ^C(1,*)
^C(1)="MARY"
^C(1,2)="MATH"
^C(1,2,1)=80
^C(1,3)="BIO"
^C(1,3,1)=90
List ^ <RETURN>
GTM>
This example uses the asterisk (*) wildcard to list node ^C(1), its
descendants and values.
Example:
GTM>do ^%G
Output Device: <terminal>: <RETURN>
List ^?D
Global Directory
Global ^ <RETURN>
^C ^D ^S ^Y ^a
Total of 5 globals.
List ^
GTM>
This example specifies "?D" as the global that invokes the %GD utility.
%GD displays existing globals in the current global directory without
displaying their values or descendants.
3 GC_
%GC
The %GC utility copies values of globals from one global to another. It
is useful for testing and for moving misfiled data.
4 Prompts
Prompts
Show copied nodes <Yes>?
Asks whether to display the "source nodes" on the principal device.
From global ^ Requests a global variable name from which to copy
variable and descendants.
To global ^ Request a global variable name to receive the copy.
4 Ex_of_GC
Example:
GTM>do ^%GC
Global copy
Show copied nodes <Yes>? <RETURN>
From global ^b
To global ^g
^g(1)=1
^g(2)=2
^g(3)=3
Total 3 nodes copied.
From global ^<RETURN>
GTM>
This example makes a copy of the nodes and values of global ^b to
global ^g.
3 GCE
%GCE
The %GCE utility changes every occurrence of a string within the data
of selected global nodes to a replacement string. ^%GCE changes the
string in each place it occurs, even if it forms part of a longer
string. For example, changing the string 12 to 55 changes 312 to 355.
4 Prompts
Prompts
Global ^ Requests (using %GSEL) the name(s) of the globals to
change; <RETURN> ends selection.
Old string: Requests an existing string to find.
New string: Requests the replacement string.
Show changed nodes <Yes>?
Asks whether to display the before and after versions of modified
nodes on the current device.
Output Device: <terminal>:
Requests a destination device; defaults to the principal device.
4 Ex_of_GCE
Examples of %GCE
Example:
GTM>DO ^%GCE
Global Change Every occurrence
Global ^a:^b
^a ^b
Current total of 2 globals.
Global ^ <RETURN>
Old String: hello
New String: good-bye
Show changed nodes <Yes>?: <RETURN>
Output Device: <terminal>: <RETURN>
^a
No changes made in total 1 nodes.
^b
^b(10)
Was : hello Adam
Now : good-bye Adam
1 changes made in total 25 nodes.
Global ^ <RETURN>
GTM>
This example searches a range of globals and its nodes for the old
string value entered. GT.M searches each global and displays the
changes and number of nodes changed and checked.
Example:
GTM>set ^b(12)=12
GTM>set ^b(122)=122
GTM>set ^b(30)=656
GTM>set ^b(45)=344
GTM>set ^b(1212)=012212
GTM>DO ^%GCE
Global Change Every occurrence
Global ^b
Current total of 1 global.
Global ^ <RETURN>
Old String: 12
New String: 35
Show changed nodes <Yes>?: <RETURN>
Output Device: <terminal>: <RETURN>
^b(12)
Was : 12
Now : 35
^b(122)
Was : 122
Now : 352
^b(1212)
Was : 12212
Now : 35235
5 changes made in total 5 nodes
Global ^ <RETURN>
GTM>DO ^%G
Output device: <terminal>: <RETURN>
List ^b
^b(12)=35
^b(30)=656
^b(45)=344
^b(122)=352
^b(1212)=35235
This example shows that executing %GCE replaces all occurrences of "12"
in the data stored in the global ^b with "35" and displays the affected
nodes before and after the change. Then the %G demonstrates that "12"
as data was changed, while "12" in the subscripts remained untouched.
3 GD
%GD
The %GD utility displays existing globals in the current global
directory without displaying their values or descendants.
%GD prompts for a global name and redisplays the name if that global
exists.
%GD interprets a percent sign (%) in the first position of a global
name literally.
%GD allows the wildcard characters asterisk (*) and question mark (?).
The wildcards carry their usual meanings, an asterisk (*) denotes a
field or a portion of a field, and a question mark (?) denotes a single
character.
A colon (:) between two globals specifies a range. %GD displays
existing globals within that range.
After each selection %GD reports the number of globals selected by the
input.
A question mark (?) entered at a prompt displays help information.
Pressing <RETURN> exits %GD.
4 Prompts
Prompts
Global ^ Requests (using %GSEL) a global name with optional
wildcards or a range of names; <RETURN> terminates %GD.
4 Ex_of_GD
Exampels of %GD
Example:
GTM>DO ^%GD
Global directory
Global ^k
^k
Total of 1 global.
Global ^ <RETURN>
GTM>
This example verifies that ^k exists in the global directory.
Example:
GTM>DO ^%GD
Global directory
Global ^C:S
^C ^D ^S
Total of 3 globals
Global ^ <RETURN>
GTM>
This example displays a range of globals that exist from ^C to ^S.
Example:
GTM>DO ^%GD Global directory
Global ^*
^C ^D ^S ^Y ^a
Total of 5 globals
Global ^ <RETURN>
GTM>
The asterisk (*) wildcard at the Global ^ prompt displays all globals
in the global directory.
3 GED
%GED
The %GED utility enables you to edit the globals in a full-screen
editor environment. %GED invokes your default editor as specified by
the EDITOR environment variable. When you finish the edit, use the
[save and] exit command(s) of the editor you are using, to exit.
4 Prompts
Prompts
Edit ^ Requests the name, in ZWRITE format, of a global to edit.
Only one global can be edited at a time with %GED, refer to GT.M
Programmer's Guide for descriptions of valid input for subscripts.
4 Ex_of_GED
Examples of %GED
Example:
GTM>DO ^%GED
edit ^ b
Beginning screen:
^b(1)="melons"
^b(2)="oranges"
^b(3)="bananas"
Screen with a change to ^b(1), elimination of ^b(3), and two new
entries ^b(4) and ^b(5):
^b(1)="apples"
^b(2)="oranges"
^b(4)=pears
^b(5)="grapes"
%GED responds:
Invalid syntax: b(4)=pears
return to continue:
After screen:
^b(1)="apples"
^b(2)="oranges"
^b(4)="pears"
^b(5)="grapes"
%GED responds:
node : ^b
selected : 3
changed : 1
added : 2
killed : 1
Edit ^ <RETURN>
GTM>
This example shows the use of the full-screen editor to change, add,
and delete (kill) nodes. When you exit from the editor, %GED checks the
syntax and reports any problems. By pressing <RETURN>, return to the
full-screen editor to fix the error. At the end of the session, %GED
reports how many nodes were selected, changed, killed, and added.
3 GI
%GI
%GI loads global variable names and their corresponding data values
into a GT.M database from a sequential file. %GI uses the global
directory to determine which database files to use. %GI may operate
concurrently with normal GT.M database access. However, a %GI does not
use M LOCKs and may produce application-level integrity problems if run
concurrently with many applications.
The %GI utility corresponds to MUPIP LOAD. The format of the input file
(GO or ZWRITE) is automatically detected.
4 Prompts
Prompts
Enter input file:
Requests name of a file; file should be in standard Global Output
(GO) format or Zwrite (ZWR) format .
OK <Yes>?: Asks for confirmation.
4 Ex_of_GI
Examples of %GI
Example:
GTM>DO ^%GI
Global Input Utility
Input device <terminal>: DATA.GBL
Saved from user's development area
GT.M 07-MAY-2002 14:14:09
OK <Yes>? <RETURN>
^IB ^INFO
Restored 10 nodes in 2 globals
GTM>
3 GO
%GO
%GO copies specified globals from the current database to a sequential
output file in either GO or ZWR format. Use %GO to back up specific
globals or when extracting data from the database for use by another
system. %GO uses the global directory to determine which database files
to use. %GO may operate concurrently with normal GT.M database access.
To ensure that a %GO reflects a consistent application state, suspend
database updates to all regions involved in the extract.
The %GO utility corresponds to MUPIP EXTRACT (FORMAT=GO or FORMAT=ZWR).
4 Prompts
Prompts
Global ^ Requests (using %GSEL) the name(s) of the globals to
search; <RETURN> ends selection.
Header label: Requests text describing contents of extract file.
Output Format: GO or ZWR:
Requests the format to output the data. Defaults to ZWR.
Output Device: <terminal>:
Requests destination device, which may be any legal filename.
4 Ex_of_GO
Examples of %GO
Example:
GTM>DO ^%GO
Global Output Utility
Global ^A
^A
Current total of 1 global
Global ^<RETURN>
Header label: Revenues May, 2002
Output Format: GO or ZWR: ZWR
Output device: /usr/dev/out.go
^A
Total of 1 node in 1 global.
GTM>
3 GSE_
%GSE
The %GSE utility finds occurrences of a string within the data values
for selected global nodes and displays the variable name and data on a
specified output device.
4 Prompts
Prompts
Output Device: <terminal>:
Requests a destination device; defaults to the principal device.
Global ^ Requests (using %GSEL) the name(s) of the globals to
search; <RETURN> ends selection.
String: Requests a search string.
4 Ex_of_GSE
Examples of %GSE
Example:
GTM>do ^%GSE
Global Search For Every Occurence
Output device: <terminal>: Test.dat
Global ^a <RETURN>
^a
Current total of 1 global.
Global ^ <RETURN>
String: Hello
^a
^a(10) Hello Adam
Total 1 matches found in 25 nodes.
Global ^ <RETURN>
GTM>
This example searches global ^a for the string "Hello" and displays all
nodes that contain that string.
3 GSEL
%GSEL
The %GSEL utility selects globals. %GSEL creates a variable %ZG that is
a local array of the selected globals. After each selection %GSEL
displays the number of globals in %ZG.
%GSEL accepts the wildcard characters asterisk (*), percent sign (%)
and question mark (?). The wildcards carry their usual meanings,
asterisk (*) denoting a field or a portion of a field, and question
mark (?) or percent sign (%) denoting a single character. The wildcards
question mark (?) and percent sign (%) lose their meanings when in the
first position of a global name. %GSEL interprets a percent sign (%) in
the first position of a global name literally.
A colon (:) between two globals specifies a range.
A minus sign (-) or quotation mark (') preceding a global name removes
that global from the %ZG array. A question mark (?) provides online
help, and "?D" displays global names currently in the array.
4 Util_Labels
Utility Labels
CALL Runs %GSEL without reinitializing %ZG.
4 Output_Vars
Output Variables
%ZG Contains array of all globals selected.
4 Prompts
Prompts
Global ^ Requests a global name with optional wildcards or a range
of names.
4 Ex_of_GSEL
Examples of %GSEL
Example:
GTM>DO ^%GSEL
Global ^C
^C
Current total of 1 global
Global ^*
^S ^Y ^c ^class
Current total of 5 globals
Global ^-S
^S
Current total of 4 globals
Global ^'Y
^Y
Current total of 3 globals
Global ^?D
^C ^c ^class
Current total of 3 globals
Global ^ <RETURN>
GTM>ZWRITE
%ZG=3
%ZG("^C")=""
%ZG("^c")=""
%ZG("^class")=""
GTM>
This example adds and subtracts globals from the list of selected
globals. "?D" displays all globals selected. ZWRITE displays the
contents of the %ZG array.
Example:
GTM>DO ^%GSEL
Global ^a
^a
Current total of 1 global.
Global ^<RETURN>
GTM>ZWRITE
%ZG=1
%ZG("^a")=""
GTM>DO CALL^%GSEL
Global ^?d
^a
Global ^iv
^iv
Current total of 2 globals.
Global ^<RETURN>
GTM>ZWRITE
%ZG=2
%ZG("^a")=""
%ZG("^iv")=""
GTM>
This example uses CALL^%GSEL to add to an existing %ZG array of
selected globals.
2 Rtn_Util
Routine Utilities
The routine utilities are:
%FL Lists the comment lines at the beginning of source programs.
%RCE Replaces every occurrence of a text string with another text
string in a routine or a list of routines.
%RD Lists routine names available through $ZROUTINES.
%RI Loads routines from RO file to *.m files in GT.M format.
%RO Writes M source code for one or more routines to a sequential
device such as a terminal, or a disk file.
%RSE Searches for every occurrence of a text string in a routine or
a list of routines.
%RSEL Selects M routines and places their directories and names in
a local array.
The "%" sign has been removed from the topic headings below,
intentionally.
3 FL
%FL
The %FL utility lists the comment lines at the beginning of source
programs. %FL writes the routines in alphabetical order to the
specified device. If the output device is not the principal device, %FL
displays the name of each routine on the principal device as it writes
the routine to the output device.
%FL uses %RSEL to select routines. For more information, refer to the
section on %RSEL in this chapter.
4 Prompts
Prompts
Routine: Requests the name(s) of the routines (using %RSEL);
<RETURN> ends the selection.
Output Device: <terminal>:
Requests a destination device; defaults to the principal device.
4 Ex_of_FL
Examples of %FL
Example:
GTM>DO ^%FL
First Line Lister
Routine: %D
%D
Current total of 1 routine.
Routine: %GS*
%GSE %GSEL
Current total of 3 routines.
Routine: - %D
%D
Current total of 2 routines.
Routine: ?D
%GSE %GSEL
Routine: <RETURN>
Output Device: <RETURN>
Routine First Line Lister Utility
GT.M 21-MAR-2002 16:44:09
%GSE
%GSE ;GT.M %GSE utility - global search
;
%GSEL ;
%GSEL ;GT.M %GSEL utility - global select into a local array
;
;invoke ^%GSEL to create %ZG - a local array of existing globals,
interactively
;
Total 5 lines in of 2 routines.
GTM>
This example selects %D, then selects %GSE and %GSEL and deselects %D.
Because the example enters <RETURN> at the Output Device: <terminal>:
prompt, the output goes to the principal device.
3 RCE
%RCE
The %RCE utility replaces every occurrence of a text string with
another text string in a routine or a list of routines.
%RCE uses %RSEL to select routines. For more information, refer to the
section on %RSEL in this chapter.
%RCE prompts for a text string to replace and its replacement. %RCE
searches for text strings in a case-sensitive manner. %RCE issues a
warning message if you specify a control character such as a <TAB> in
the text string or its replacement. %RCE confirms your selection by
displaying the text string and its replacement between a left and right
arrow. The arrows highlight any blank spaces that you might have
included in the text string or its replacement.
Regardless of whether you select a display of every change, %RCE
displays the name of each routine as it is processed and completes
processing with a count of replacements and routines changed.
4 Prompts
Prompts
Routine: Requests (using %RSEL) the name(s) of the routines to
change; <RETURN> ends the selection.
Old string: Requests string to be replaced.
New string: Requests replacement string.
Show changed lines <Yes>?:
Asks whether to display the before and after versions of the
modified lines on an output device.
Output Device: <terminal>:
Requests a destination device; defaults to the principal device.
4 Util_Labels
Utility Labels
CALL Works without user interaction unless %ZR is not defined.
4 Input_Vars
Input Variable
The following input variables are only applicable when invoking
CALL^%RCE.
%ZR Contains an array of routines provided or generated with %RSEL.
%ZF Contains string to find.
%ZN Contains a replacement string.
%ZD Identifies the device to display the change trail, defaults to
principal device. Make sure you open the device if the device is
not the principal device.
%ZC Truth-value indicating whether to display the change trail,
defaults to 0 (no).
4 Ex_of_RCE
Examples of %RCE
Example:
GTM>DO ^%RCE
Routine Change Every occurrence
Routine: BES*
BEST BEST2 BEST3 BEST4
Current total of 4 routines
Routine: <RETURN>
Old string:^NAME
New string:^STUDENT
Replace all occurrences of:
>^NAME<
With
>^STUDENT<
Show changed lines <Yes>?: <RETURN>
Output Device: <RETURN>
/usr/smith/work/BEST.m
Was: S ^NAME=SMITH
Now: S ^STUDENT=SMITH
Was: S ^NAME(1)=JOHN
Now: S ^STUDENT(1)=JOHN
/usr/smith/work/BEST2.m
/usr/smith/work/BEST3.m
Was: S ^NAME=X
Now: S ^STUDENT=X
Was: W ^NAME
Now: W ^STUDENT
/usr/smith/work/BEST4.m
Total of 4 routines parsed.
4 occurrences changed in 2 routines.
GTM>
This example selects a list of routines that change the string "^NAME"
to the string "^STUDENT," and displays a trail of the changes.
Example:
GTM>DO ^%RCE
Routine Change Every occurrence
Routine: BES*
BEST BEST2 BEST3 BEST4
Current total of 4 routines
Routine: <RETURN>
Old String:<TAB>
The find string contains control characters
New string: <RETURN>
Replace all occurrences of:
><TAB><
With:
><
Show changed lines <Yes>?: N
BEST BEST2 BEST3 BEST4
Total 4 routines parsed.
4 occurrences changed in 2 routines.
GTM>
This example removes all occurrences of the <TAB> key from specified
routines and suppresses the display trail of changes.
3 RD
%RD
The %RD utility lists routine names accessible through the current
$ZROUTINES. %RD calls %RSEL and displays any routines accessible
through %RSEL. Use %RD to locate routines.
%RD accepts the wildcard characters asterisk (*) and question mark (?).
The wildcards carry their usual meanings, an asterisk (*) denotes a
field or a portion of a field, and a question mark (?) denotes a single
character in positions other than the first.
A colon (:) between two routine names specifies a range of routines.
%RD displays only those routine names accessible through the current
$ZROUTINES.
After each selection %RD displays the total number of routines listed.
Pressing <RETURN> exits %RD.
4 Prompts
Prompts
Routine: Requests (using %RSEL) the name(s) of the routines to
list; <RETURN> ends the selection.
4 Util_Labels
Utility Labels
OBJ Lists object modules accessible through the current $ZROUTINES.
LIB Lists percent (%) routines accessible through the current
$ZROUTINES.
SRC Lists the source modules accessible through the current
$ZROUTINES (same as %RD).
4 Ex_of_RD
Examples of %RD
Example:
GTM>DO ^%RD
Routine directory
Routine: TAXES
TAXES
Total of 1 routine
Routine:*
EMP FICA PAYROLL TAXES YTD
Total of 5 Routines
Routine: <RETURN>
GTM>
This example invokes %RD that prompts for routine TAXES and the
wildcard (*). %RD lists five routines accessible through the current
$ZROUTINES.
Example:
GTM>DO OBJ^%RD
Routine directory
Routine:*
EMP FICA
Total of 2 routines
Routine: <RETURN>
GTM>
This example invokes %RD with the label OBJ that lists only object
modules accessible through the current $ZROUTINES.
Example:
GTM>DO LIB^%RD
Routine directory
%D %DATE %DH %G %GD %GSEL
GTM>
This example invokes %RD with the LIB label that lists all the %
routines accessible through the current $ZROUTINES.
Example:
GTM>DO SRC^%RD
Routine directory
Routine:*
DATACHG
Total of 1 routines
Routine: <RETURN>
GTM>
This example invokes %RD with the label SRC that lists only source
modules accessible through the current $ZROUTINES.
3 RI
%RI
%RI transforms M routines in the sequential format described in the
ANSI standard into individual .m files in GT.M format. Use %RI to make
M RO format accessible as GT.M routines.
4 Prompts
Prompts
Formfeed delimited <No>?
Requests whether lines should be delimited by formfeed characters
rather than carriage returns.
Input Device: <terminal>:
Requests name of RO file containing M routines.
Output Directory:
Requests name of directory to output M routines.
4 Ex_of_RI
Examples of %RI
Example:
GTM>DO ^%RI
Routine Input utility - Converts RO file to *.m files
Formfeed delimited <No>? <RETURN>
Input device: <terminal>: file.ro
Files saved from FILEMAN directory
GT.M 07-MAY-2002 15:17:54
Output directory: /usr/smith/work/
DI DIA DIAO DIAI DIB DIBI
Restored 753 lines in 6 routines.
GTM>
3 RO
%RO
The %RO utility writes M source code for one or more routines to a
sequential device such as a disk file or a printer.
%RO uses %RSEL to select routines. For more information, refer to the
section on %RSEL in this chapter.
%RO writes the routines in alphabetical order to the specified device.
%RO displays the name of each routine as it writes the routine to the
device.
4 Prompts
Prompts
Routine: Requests (using %RSEL) the name(s) of the routines to
output; <RETURN> ends selection.
Output device: <terminal>:
Requests a destination device; defaults to the principal device.
Header label: Requests text to place in the first of the two header
records.
Strip comments <No>?:
Asks whether to remove all comment lines except those with two
adjacent semicolons.
4 Util_Labels
Utility Labels
CALL Works without user interaction unless %ZR is not defined.
4 Input_Vars
Input Variables
The following input variables are only applicable when invoking
CALL^%RO.
%ZR Contains an array of routines provided or generated with %RSEL.
%ZD Identifies the device to display output, defaults to principal
device.
4 Ex_of_RO
Examples of %RO
Example:
GTM>DO ^%RO
Routine Output - Save selected routines into RO file.
Routine: %D
%D
Current total of 1 routines.
Routine: -%D
%D
Current total of 0 routines.
Routine: BEST*
BEST BEST1 BEST2
Current total of 3 routines.
Routine: ?D
BEST BEST1 BEST2
Routine: <RETURN>
Output Device: <terminal>: output.txt
Header Label: Source code for the BEST modules.
Strip comments <No>?:<RETURN>
BEST BEST1 BEST2
Total of 53 lines in 3 routines
GTM>
This example adds and subtracts %D from the selection, then adds all
routines starting with "BEST" and confirms the current selection. The
example sends output to the designated output file output.txt. %RO
displays the label at the beginning of the output file. The first
record of the header label is the text entered at the prompt. The
second record of the header label consists of the word "GT.M" and the
current date and time.
3 RSE_
%RSE
The %RSE utility searches for every occurrence of a text string in a
routine or a list of routines.
%RSE uses %RSEL to select routines. For more information, refer to the
section on %RSEL in this chapter.
%RSE searches for text strings are case-sensitive. %RSE issues a
warning message if you specify a control character such as a <TAB> in
the text string. %RSE confirms your selection by displaying the text
string between a left and right arrow. The arrows display any blank
spaces included in the text string.
%RSE completes processing with a count of occurrences found.
4 Prompts
Prompts
Routine: Requests (using %RSEL) the name(s) of the routines to
search; <RETURN> ends selection.
Find string: Requests string for which to search.
Output device: <terminal>:
Requests a destination device; defaults to the principal device.
4 Util_Labels
Utility Labels
CALL Works without user interaction unless %ZR is not defined.
4 Input_Vars
Input Variables
The following input variables are only applicable when invoking
CALL^%RSE.
%ZR Contains an array of routines provided or generated with %RSEL.
%ZF Contains the string to find.
%ZD Identifies the device to display the results, defaults to
principal device. Make sure you open the device if the device is
not the principal device.
4 Ex_of_RSE
Examples of %RSE
Example:
GTM>DO ^%RSE
Routine Search for Every occurrence
Routine: BES*
BEST BEST2 BEST3 BEST4
Current total of 4 routines
Routine: <RETURN>
Find string:^NAME
Find all occurrences of:
>^NAME<
Output device: <terminal>:
/usr/smith/work/BEST.m
S ^NAME=SMITH
S ^NAME(1)=JOHN
/usr/smith/work/BEST2.m
/usr/smith/work/BEST3.m
S ^NAME=X
W ^NAME
/usr/smith/work/BEST4.m
Total of 4 routines parsed.
4 occurrences found in 2 routines.
GTM>
This example invokes %RSE that searches and finds a given string. The
output device specifies a terminal display of all lines where the text
string occurs.
Example:
GTM>DO ^%RSE
Routine Search for Every occurrence
Routine: BEST
BEST
Current total of 1 routine
Routine: <RETURN>
Find string:^NAME
Find all occurrences of:
>^NAME<
Output Device: out.lis
BEST
GTM>
This example instructs ^%RSE to write all lines where the text string
occurs to an output file, out.lis.
3 RSEL
%RSEL
The %RSEL utility selects M routines. %RSEL selects routines using
directories specified by the GT.M special variable $ZROUTINES.
$ZROUTINES contains an ordered list of UNIX directories that certain
GT.M functions use to locate source and object files. If $ZROUTINES is
not defined, %RSEL searches only the current default directory. Other
GT.M utilities call %RSEL.
%RSEL prompts for the name of a routine(s).
%RSEL accepts the wildcard characters asterisk (*) and question mark
(?). The wildcards carry their usual meanings: an asterisk (*) denotes
a field or a portion of a field, and a question mark (?) denotes a
single character in positions other than the first.
A colon (:) between two routines specifies a range.
%RSEL creates a read-write variable %ZR, which is a local array of
selected routines. After each selection, %RSEL reports the number of
routines in %ZR. A minus sign (-) or an apostrophe (') character
preceding a routine name removes that routine from the %ZR array. A
question mark (?) provides online help, and "?D" displays M routines
currently in the array.
If a local variable %ZRSET is defined, %RSEL places the output
information into a global variable (^%RSET) instead of the local
variable %ZR.
4 Prompts
Prompts
Routine: Requests the name(s) of the routines; <RETURN> ends
selection.
4 Util_Labels
Utility Labels
CALL Performs %RSEL without reinitializing %ZR.
OBJ Searches only object files.
SRC Searches only source files (same as %RSEL).
4 Input_Vars
Input Variables
The following input variables are only valid when invoking CALL^%RSEL:
%ZE Contains the file extension, usually either .m for source files
or .o for object files.
%ZR As input, contains an existing list of routines to be modified.
%ZRSET On being set, requests %RSEL to place the output in the
global variable ^%RSET.
4 Output_Vars
Output Variables
%ZR As output, contains list of directories indexed by selected
routine names.
^%RSET($JOB) The output global variable ^%RSET is used instead of
the local variable %RD if the input variable %ZRSET is set. It is
indexed by job number $JOB and the selected routine names.
4 Ex_of_RSEL
Examples of %RSEL
Example:
GTM>DO ^%RSEL
Routine: TES*
TEST2 TEST3
Current total of 2 routines
Routine: <RETURN>
GTM>DO OBJ^%RSEL
Routine:TEST?
Current total of 0 routines
Routine: <RETURN>
GTM>ZWRITE
%ZR=0
This example selects two source routines starting with "TES" as the
first three characters. Then, the example invokes %RSEL at the OBJ
label to select object modules only. OBJ^%RSEL returns a %ZR=0 because
object modules for the TEST routines do not exist.
Example:
GTM>DO ^%RSEL
Routine: BES*
BEST BEST2 BEST3 BEST4
Current total of 4 routines
Routine: - BEST
BEST
Current total of 3 routines
Routine: ?D
BEST2 BEST3 BEST4
Routine: 'BEST2
BEST2
Current total of 2 routines
Routine: ?D
BEST3 BEST4
Routine: <RETURN>
GTM>ZWRITE
%ZR=2
%ZR("BEST3")="/usr/smith/work/"
%ZR("BEST4")="/usr/smith/test/"
GTM>
This example selects the routines using the asterisk (*) wildcard and
illustrates how to tailor your selection list. Note that %ZR contains
two routines from different directories.
By default, %RSEL bases the contents of %ZR on source files that have a
.m extension.
Example:
GTM>DO ^%RSEL
Routine:BEST*
BEST2 BEST3
Current total of 2 routines
Routine: <RETURN>
GTM>ZWRITE
%ZR=2
%ZR("BEST2")="/usr/smith/test/"
%ZR("BEST3")="/usr/smith/test/"
This example creates a %ZR array with BEST2 and BEST3.
Example:
GTM>DO ^%RSEL
Routine:LOCK
LOCK
Current total of 1 routine
Routine: <RETURN>
GTM>ZWRITE
%ZR=1
%ZR("LOCK")="/usr/smith/work/"
GTM>DO CALL^%RSEL
Routine:BEST*
BEST2 BEST3
Current total of 2 routines
Routine: <RETURN>
GTM>ZWRITE
%ZR=3
%ZR("BEST2")="/usr/smith/work/"
%ZR("BEST3")="/usr/smith/work/"
%ZR("LOCK")="/usr/smith/work/"
GTM>
This example creates a %ZR array with LOCK and adds to it using
CALL%RSEL.
2 Internationalization_Util
Internationalization Utilities
The internationalization utilities are:
%GBLDEF Manipulates the collation sequence assigned to a global.
%LCLCOL Manipulates the collation sequence assigned to local
variables in an active process.
%PATCODE Loads pattern definition files for use within an active
database.
These utilities are an integral part of the GT.M functionality that
permits you to customize your applications for use with other
languages. For a description of these utilities, refer to the
"Internationalization" chapter in GT.M Programmers Guide.
2 Sys_Mgmt_Util
System Management Utilities
The System Management utilities are:
%FREECNT Displays the number of free blocks in the database files
associated with the current global directory.
3 FREECNT
%FREECNT
The %FREECNT utility displays the number of free blocks in the database
files associated with the current global directory.