11.07.2015 Views

Caché ObjectScript Reference - InterSystems Documentation

Caché ObjectScript Reference - InterSystems Documentation

Caché ObjectScript Reference - InterSystems Documentation

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Caché</strong> <strong>ObjectScript</strong><strong>Reference</strong>Version 5.201 September 2006<strong>InterSystems</strong> Corporation 1 Memorial Drive Cambridge MA 02142 www.intersystems.com


<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong><strong>Caché</strong> Version 5.2 01 September 2006Copyright © 2006 <strong>InterSystems</strong> Corporation.All rights reserved.This book was assembled and formatted in Adobe Page Description Format (PDF) using tools and information fromthe following sources: Sun Microsystems, RenderX, Inc., Adobe Systems, and the World Wide Web Consortium atwww.w3c.org. The primary document development tools were special-purpose XML-processing applications builtby <strong>InterSystems</strong> using <strong>Caché</strong> and Java.The <strong>Caché</strong> product and its logos are registered trademarks of <strong>InterSystems</strong> Corporation.The Ensemble product and its logos are registered trademarks of <strong>InterSystems</strong> Corporation.The <strong>InterSystems</strong> name and logo are trademarks of <strong>InterSystems</strong> Corporation.This document contains trade secret and confidential information which is the property of <strong>InterSystems</strong> Corporation,One Memorial Drive, Cambridge, MA 02142, or its affiliates, and is furnished for the sole purpose of the operationand maintenance of the products of <strong>InterSystems</strong> Corporation. No part of this publication is to be used for any otherpurpose, and this publication is not to be reproduced, copied, disclosed, transmitted, stored in a retrieval system ortranslated into any human or computer language, in any form, by any means, in whole or in part, without the expressprior written consent of <strong>InterSystems</strong> Corporation.The copying, use and disposition of this document and the software programs described herein is prohibited exceptto the limited extent set forth in the standard software license agreement(s) of <strong>InterSystems</strong> Corporation coveringsuch programs and related documentation. <strong>InterSystems</strong> Corporation makes no representations and warrantiesconcerning such software programs other than those set forth in such standard software license agreement(s). Inaddition, the liability of <strong>InterSystems</strong> Corporation for any losses or damages relating to or arising out of the use ofsuch software programs is limited in the manner set forth in such standard software license agreement(s).THE FOREGOING IS A GENERAL SUMMARY OF THE RESTRICTIONS AND LIMITATIONS IMPOSED BYINTERSYSTEMS CORPORATION ON THE USE OF, AND LIABILITY ARISING FROM, ITS COMPUTERSOFTWARE. FOR COMPLETE INFORMATION REFERENCE SHOULD BE MADE TO THE STANDARD SOFTWARELICENSE AGREEMENT(S) OF INTERSYSTEMS CORPORATION, COPIES OF WHICH WILL BE MADE AVAILABLEUPON REQUEST.<strong>InterSystems</strong> Corporation disclaims responsibility for errors which may appear in this document, and it reserves theright, in its sole discretion and without notice, to make substitutions and modifications in the products and practicesdescribed in this document.<strong>Caché</strong>, <strong>InterSystems</strong> <strong>Caché</strong>, <strong>Caché</strong> SQL, <strong>Caché</strong> <strong>ObjectScript</strong>, <strong>Caché</strong> Object, Ensemble, <strong>InterSystems</strong> Ensemble,Ensemble Object, and Ensemble Production are trademarks of <strong>InterSystems</strong> Corporation. All other brand or productnames used herein are trademarks or registered trademarks of their respective companies or organizations.For Support questions about any <strong>InterSystems</strong> products, contact:<strong>InterSystems</strong> Worldwide Customer SupportTel: +1 617 621-0700Fax: +1 617 374-9391Email: support@<strong>InterSystems</strong>.com


Table of ContentsSymbols and Abbreviations ............................................................................................... 1Symbols Used in <strong>Caché</strong> <strong>ObjectScript</strong> ............................................................................ 1Abbreviations Used in <strong>Caché</strong> <strong>ObjectScript</strong> ................................................................... 9<strong>Caché</strong> <strong>ObjectScript</strong> Commands ...................................................................................... 15BREAK ........................................................................................................................ 16CLOSE ......................................................................................................................... 20CONTINUE ................................................................................................................. 22DO ................................................................................................................................ 24DO WHILE .................................................................................................................. 33ELSE ............................................................................................................................ 37ELSEIF ........................................................................................................................ 38FOR .............................................................................................................................. 38GOTO ........................................................................................................................... 46HALT ........................................................................................................................... 50HANG .......................................................................................................................... 52IF .................................................................................................................................. 54JOB .............................................................................................................................. 57KILL ............................................................................................................................ 73LOCK ........................................................................................................................... 79MERGE ........................................................................................................................ 90NEW ............................................................................................................................ 94OPEN ......................................................................................................................... 100PRINT ........................................................................................................................ 107QUIT .......................................................................................................................... 110READ ......................................................................................................................... 115SET ............................................................................................................................ 126TCOMMIT ................................................................................................................. 135TROLLBACK ............................................................................................................ 138TSTART ..................................................................................................................... 142USE ............................................................................................................................ 145VIEW ......................................................................................................................... 151WHILE ....................................................................................................................... 156WRITE ....................................................................................................................... 160<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>iii


XECUTE .................................................................................................................... 171<strong>Caché</strong> <strong>ObjectScript</strong> Functions ....................................................................................... 177$ASCII ....................................................................................................................... 179$BIT ........................................................................................................................... 182$BITCOUNT ............................................................................................................. 184$BITFIND .................................................................................................................. 186$BITLOGIC ............................................................................................................... 187$CASE ....................................................................................................................... 191$CHAR ...................................................................................................................... 193$DATA ....................................................................................................................... 196$DOUBLE ................................................................................................................. 200$EXTRACT ............................................................................................................... 203$FACTOR .................................................................................................................. 209$FIND ........................................................................................................................ 211$FNUMBER .............................................................................................................. 213$GET .......................................................................................................................... 217$INCREMENT .......................................................................................................... 220$INUMBER ............................................................................................................... 224$ISOBJECT ............................................................................................................... 230$ISVALIDNUM ......................................................................................................... 231$JUSTIFY .................................................................................................................. 236$LENGTH .................................................................................................................. 238$LIST ......................................................................................................................... 240$LISTBUILD ............................................................................................................. 244$LISTDATA ............................................................................................................... 247$LISTFIND ................................................................................................................ 249$LISTFROMSTRING ................................................................................................ 251$LISTGET ................................................................................................................. 253$LISTLENGTH ......................................................................................................... 255$LISTNEXT .............................................................................................................. 257$LISTSAME .............................................................................................................. 258$LISTTOSTRING ..................................................................................................... 261$NAME ...................................................................................................................... 263$NEXT ....................................................................................................................... 267$NORMALIZE .......................................................................................................... 268$NUMBER ................................................................................................................ 272iv<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ORDER .................................................................................................................... 276$PIECE ...................................................................................................................... 280$QLENGTH ............................................................................................................... 287$QSUBSCRIPT ......................................................................................................... 288$QUERY .................................................................................................................... 290$RANDOM ................................................................................................................ 293$REVERSE ................................................................................................................ 295$SELECT ................................................................................................................... 296$SORTBEGIN ........................................................................................................... 298$SORTEND ............................................................................................................... 299$STACK ..................................................................................................................... 300$TEXT ....................................................................................................................... 304$TRANSLATE ........................................................................................................... 307$VIEW ....................................................................................................................... 309Math and Time Functions .............................................................................................. 315$ZABS ....................................................................................................................... 315$ZARCCOS ............................................................................................................... 316$ZARCSIN ................................................................................................................ 317$ZARCTAN ............................................................................................................... 318$ZCOS ....................................................................................................................... 319$ZCOT ....................................................................................................................... 320$ZCSC ........................................................................................................................ 322$ZDATE ..................................................................................................................... 323$ZDATEH .................................................................................................................. 334$ZDATETIME ........................................................................................................... 344$ZDATETIMEH ........................................................................................................ 355$ZEXP ........................................................................................................................ 365$ZHEX ....................................................................................................................... 366$ZLN .......................................................................................................................... 368$ZLOG ....................................................................................................................... 370$ZPOWER ................................................................................................................. 371$ZSEC ........................................................................................................................ 372$ZSIN ......................................................................................................................... 373$ZSQR ....................................................................................................................... 374$ZTAN ....................................................................................................................... 375$ZTIME ..................................................................................................................... 377<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>v


$ZTIMEH .................................................................................................................. 381Routine, Debugging, and Other Commands ................................................................ 385ZBREAK .................................................................................................................... 386ZINSERT ................................................................................................................... 389ZKILL ........................................................................................................................ 393ZLOAD ...................................................................................................................... 394ZNSPACE .................................................................................................................. 397ZPRINT ...................................................................................................................... 400ZREMOVE ................................................................................................................ 402ZSAVE ....................................................................................................................... 404ZSYNC ...................................................................................................................... 406ZTRAP ....................................................................................................................... 408ZWRITE .................................................................................................................... 411ZZDUMP ................................................................................................................... 414<strong>Caché</strong> <strong>ObjectScript</strong> Special Variables .......................................................................... 419$DEVICE ................................................................................................................... 420$ECODE .................................................................................................................... 420$ESTACK ................................................................................................................... 423$ETRAP ..................................................................................................................... 426$HALT ....................................................................................................................... 429$HOROLOG .............................................................................................................. 432$IO ............................................................................................................................. 436$JOB .......................................................................................................................... 438$KEY ......................................................................................................................... 439$PRINCIPAL ............................................................................................................. 442$QUIT ........................................................................................................................ 443$ROLES ..................................................................................................................... 444$STACK ..................................................................................................................... 446$STORAGE ............................................................................................................... 448$SYSTEM .................................................................................................................. 449$TEST ........................................................................................................................ 451$TLEVEL .................................................................................................................. 453$USERNAME ............................................................................................................ 453$X ............................................................................................................................... 454$Y ............................................................................................................................... 457$ZA ............................................................................................................................ 459vi<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZB ............................................................................................................................ 462$ZCHILD ................................................................................................................... 466$ZEOF ........................................................................................................................ 468$ZERROR .................................................................................................................. 469$ZHOROLOG ............................................................................................................ 473$ZIO ........................................................................................................................... 474$ZJOB ........................................................................................................................ 476$ZMODE ................................................................................................................... 477$ZNAME ................................................................................................................... 478$ZNSPACE ................................................................................................................ 479$ZORDER .................................................................................................................. 480$ZPARENT ................................................................................................................ 482$ZPI ............................................................................................................................ 482$ZPOS ........................................................................................................................ 483$ZREFERENCE ........................................................................................................ 484$ZSTORAGE ............................................................................................................. 488$ZTIMESTAMP ........................................................................................................ 488$ZTIMEZONE ........................................................................................................... 492$ZTRAP ..................................................................................................................... 495$ZVERSION .............................................................................................................. 498Structured System Variables ......................................................................................... 501^$GLOBAL ................................................................................................................ 502^$JOB ......................................................................................................................... 505^$LOCK ..................................................................................................................... 507^$ROUTINE .............................................................................................................. 510System and Other Functions ......................................................................................... 515$ZBOOLEAN ............................................................................................................ 515$ZCONVERT ............................................................................................................ 522$ZCRC ....................................................................................................................... 525$ZCYC ....................................................................................................................... 527$ZF ............................................................................................................................. 528$ZF(-1) ....................................................................................................................... 534$ZF(-2) ....................................................................................................................... 536$ZF(-3) ....................................................................................................................... 537$ZF(-4) ....................................................................................................................... 539$ZF(-5) ....................................................................................................................... 541<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>vii


$ZF(-6) ....................................................................................................................... 542$ZINCREMENT ........................................................................................................ 543$ZISWIDE ................................................................................................................. 544$ZLASCII .................................................................................................................. 545$ZLCHAR .................................................................................................................. 546$ZNAME ................................................................................................................... 547$ZNEXT .................................................................................................................... 551$ZORDER .................................................................................................................. 552$ZPOSITION ............................................................................................................. 553$ZPREVIOUS ............................................................................................................ 555$ZSEARCH ............................................................................................................... 556$ZSEEK ..................................................................................................................... 560$ZSORT ..................................................................................................................... 561$ZSTRIP .................................................................................................................... 562$ZUTIL(4) ................................................................................................................. 565$ZUTIL(5) ................................................................................................................. 567$ZUTIL(9) ................................................................................................................. 569$ZUTIL(12) ............................................................................................................... 571$ZUTIL(15) ............................................................................................................... 575$ZUTIL(18) ............................................................................................................... 576$ZUTIL(20) ............................................................................................................... 578$ZUTIL(21) ............................................................................................................... 581$ZUTIL(39) ............................................................................................................... 582$ZUTIL(49) ............................................................................................................... 584$ZUTIL(55) ............................................................................................................... 591$ZUTIL(56,2) ............................................................................................................ 593$ZUTIL(62,1) ............................................................................................................ 593$ZUTIL(67) ............................................................................................................... 595$ZUTIL(68) ............................................................................................................... 596$ZUTIL(68,1) ............................................................................................................ 599$ZUTIL(68,2) ............................................................................................................ 600$ZUTIL(68,3) ............................................................................................................ 601$ZUTIL(68,5) ............................................................................................................ 603$ZUTIL(68,6) ............................................................................................................ 604$ZUTIL(68,7) ............................................................................................................ 605$ZUTIL(68,11) .......................................................................................................... 606$ZUTIL(68,15) .......................................................................................................... 607viii<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(68,21) .......................................................................................................... 609$ZUTIL(68,22) .......................................................................................................... 610$ZUTIL(68,25) .......................................................................................................... 611$ZUTIL(68,26) .......................................................................................................... 613$ZUTIL(68,27) .......................................................................................................... 615$ZUTIL(68,28) .......................................................................................................... 617$ZUTIL(68,30) .......................................................................................................... 618$ZUTIL(68,32) .......................................................................................................... 619$ZUTIL(68,34) .......................................................................................................... 621$ZUTIL(68,39) .......................................................................................................... 622$ZUTIL(68,40) .......................................................................................................... 623$ZUTIL(68,42) .......................................................................................................... 624$ZUTIL(68,43) .......................................................................................................... 626$ZUTIL(68,45) .......................................................................................................... 627$ZUTIL(68,51) .......................................................................................................... 628$ZUTIL(68,63) .......................................................................................................... 629$ZUTIL(69) ............................................................................................................... 630$ZUTIL(69,0) ............................................................................................................ 634$ZUTIL(69,1) ............................................................................................................ 636$ZUTIL(69,2) ............................................................................................................ 638$ZUTIL(69,3) ............................................................................................................ 639$ZUTIL(69,4) ............................................................................................................ 640$ZUTIL(69,5) ............................................................................................................ 642$ZUTIL(69,6) ............................................................................................................ 643$ZUTIL(69,7) ............................................................................................................ 644$ZUTIL(69,8) ............................................................................................................ 645$ZUTIL(69,10) .......................................................................................................... 647$ZUTIL(69,11) .......................................................................................................... 648$ZUTIL(69,13) .......................................................................................................... 649$ZUTIL(69,14) .......................................................................................................... 650$ZUTIL(69,15) .......................................................................................................... 651$ZUTIL(69,19) .......................................................................................................... 653$ZUTIL(69,20) .......................................................................................................... 654$ZUTIL(69,21) .......................................................................................................... 655$ZUTIL(69,22) .......................................................................................................... 656$ZUTIL(69,24) .......................................................................................................... 657$ZUTIL(69,26) .......................................................................................................... 658<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>ix


$ZUTIL(69,27) .......................................................................................................... 660$ZUTIL(69,28) .......................................................................................................... 661$ZUTIL(69,30) .......................................................................................................... 663$ZUTIL(69,31) .......................................................................................................... 664$ZUTIL(69,32) .......................................................................................................... 665$ZUTIL(69,34) .......................................................................................................... 667$ZUTIL(69,35) .......................................................................................................... 668$ZUTIL(69,37) .......................................................................................................... 669$ZUTIL(69,39) .......................................................................................................... 670$ZUTIL(69,40) .......................................................................................................... 671$ZUTIL(69,42) .......................................................................................................... 672$ZUTIL(69,43) .......................................................................................................... 673$ZUTIL(69,44) .......................................................................................................... 674$ZUTIL(69,45) .......................................................................................................... 675$ZUTIL(69,49) .......................................................................................................... 676$ZUTIL(69,51) .......................................................................................................... 677$ZUTIL(69,60) .......................................................................................................... 678$ZUTIL(69,63) .......................................................................................................... 680$ZUTIL(71) ............................................................................................................... 680$ZUTIL(78,21) .......................................................................................................... 682$ZUTIL(78,22) .......................................................................................................... 684$ZUTIL(78,23) .......................................................................................................... 686$ZUTIL(78,28) .......................................................................................................... 687$ZUTIL(78,29) .......................................................................................................... 688$ZUTIL(82,12) .......................................................................................................... 689$ZUTIL(86) ............................................................................................................... 690$ZUTIL(90,4) ............................................................................................................ 691$ZUTIL(90,10) .......................................................................................................... 691$ZUTIL(94) ............................................................................................................... 693$ZUTIL(96) ............................................................................................................... 694$ZUTIL(96,4) ............................................................................................................ 695$ZUTIL(96,5) ............................................................................................................ 696$ZUTIL(96,9) ............................................................................................................ 696$ZUTIL(96,10) .......................................................................................................... 697$ZUTIL(96,14) .......................................................................................................... 697$ZUTIL(110) ............................................................................................................. 698$ZUTIL(114) ............................................................................................................. 699x<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(128,1) .......................................................................................................... 702$ZUTIL(130) ............................................................................................................. 703$ZUTIL(131) ............................................................................................................. 705$ZUTIL(132) ............................................................................................................. 707$ZUTIL(140) ............................................................................................................. 708$ZUTIL(140,7) .......................................................................................................... 712$ZUTIL(147) ............................................................................................................. 715$ZUTIL(158) ............................................................................................................. 716$ZUTIL(168) ............................................................................................................. 717$ZUTIL(186) ............................................................................................................. 719$ZUTIL(188) ............................................................................................................. 721$ZUTIL(189) ............................................................................................................. 723$ZUTIL(193) ............................................................................................................. 724$ZWASCII ................................................................................................................. 727$ZWCHAR ................................................................................................................ 729$ZWIDTH .................................................................................................................. 730$ZWPACK and $ZWBPACK .................................................................................... 731$ZWUNPACK and $ZWUNBPACK ......................................................................... 733$ZZENKAKU ............................................................................................................ 734The %ZLANG Language Extension Library .............................................................. 735%ZLANG ................................................................................................................... 735Legacy Commands and Functions ................................................................................ 739DO (legacy version) ................................................................................................... 740FOR (legacy version) ................................................................................................. 745IF (legacy version) ..................................................................................................... 753ZQUIT (legacy command) ......................................................................................... 754$ZBITAND (legacy function) .................................................................................... 758$ZBITCOUNT (legacy function) ............................................................................... 758$ZBITFIND (legacy function) ................................................................................... 759$ZBITGET (legacy function) ..................................................................................... 760$ZBITLEN (legacy function) ..................................................................................... 761$ZBITNOT (legacy function) .................................................................................... 762$ZBITOR (legacy function) ....................................................................................... 762$ZBITSET (legacy function) ..................................................................................... 763$ZBITSTR (legacy function) ..................................................................................... 764$ZBITXOR (legacy function) .................................................................................... 765<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>xi


$ZUTIL(67,0) (legacy function) ................................................................................ 766$ZUTIL(67,1) (legacy function) ................................................................................ 768$ZUTIL(67,4) (legacy function) ................................................................................ 769$ZUTIL(67,5) (legacy function) ................................................................................ 771$ZUTIL(67,6) (legacy function) ................................................................................ 773$ZUTIL(67,7) (legacy function) ................................................................................ 774$ZUTIL(67,8) (legacy function) ................................................................................ 775$ZUTIL(67,9) (legacy function) ................................................................................ 776$ZUTIL(67,10) (legacy function) .............................................................................. 777$ZUTIL(67,11) (legacy function) .............................................................................. 780$ZUTIL(67,12) (legacy function) .............................................................................. 781$ZUTIL(67,13) (legacy function) .............................................................................. 782$ZUTIL(67,14) (legacy function) .............................................................................. 783$ZUTIL(67,15) (legacy function) .............................................................................. 786$ZUTIL(100) (legacy function) ................................................................................. 787$ZUTIL(113) (legacy function) ................................................................................. 788$ZUTIL(133) (legacy function) ................................................................................. 789xii<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


List of FiguresClient/Server Connections in the Non-Concurrent and Concurrent Modes ....................... 70Initial Structure of ^X and ^Y ............................................................................................ 92Result on ^X and ^Y of MERGE Command ...................................................................... 92Conversion of a String to Multibyte Little or Big Endian Format .................................... 732Conversion of a Multibyte Little or Big Endian Format String to a Single-byte String .... 733<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>xiii


Symbols and AbbreviationsSymbols Used in <strong>Caché</strong> <strong>ObjectScript</strong>A table of characters used in <strong>Caché</strong> <strong>ObjectScript</strong> as operators, etc.Table of SymbolsThe following are the literal symbols used in <strong>Caché</strong> <strong>ObjectScript</strong>. (This list does not includesymbols indicating format conventions, which are not part of the language.) There is a separatetable for symbols used in <strong>Caché</strong> SQL.The name of each symbol is followed by its ASCII decimal code value.Symbol[space] or [tab][two spaces, twotabs, or a spaceand a tab]!"Name and UsageWhite space (Tab (9) or Space (32)): In commands, one (and onlyone) space required before first argument.Leading white space (space or tab) required before every line ofcode, except labels.Trailing white space (space or tab) required between last commandargument and any following command or comment on the sameline.At least one space required before an opening curly brace.Double white space: Trailing double white space required betweenan argumentless command and the next command on the sameline.Exclamation mark (33): Binary OR logical operator.In READ and WRITE commands, specifies a new line.As first character at terminal prompt, load interactive subshell.Quotes (34): Used to enclose string literals. In Dynamic SQL usedto enclose the SQL code as a string argument of the Preparemethod.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 1


Symbols and AbbreviationsSymbol""###$$$Name and UsageDouble quotes: Used to specify the null string (""), which is a zerolengthstring.Used to specify a literal quote character within a quoted string.Pound sign (35): Binary modulo division operator.In READ and WRITE commands, form feed. In fixed-length READ,number of characters to read.Prefix for referencing the value of a class parameter from withinthe class: #ParameterName.Macro directives prefix: #Define, #Include, #IfDelimiter for a runtime expression: #(expr)#, where expr is a <strong>Caché</strong><strong>ObjectScript</strong> expression.In the callout routine ZFENTRY, an argtype prefix indicating aDOUBLE data type: #D or #F.Double pound sign: Object class method invocation prefix: DO##class(method).##this syntax provides a handle to the OREF of the current objectinstance. ##super() syntax is used to invoke an overridden superclassmethod.SQL shell invocation prefix: ##sql(SQL command).Delimiter for a compile-time expression: ##(expr)##, where expr isa <strong>Caché</strong> <strong>ObjectScript</strong> expression.Dollar sign (36): Intrinsic (system) function prefix: $name(parameters).Special variable prefix: $name.With ZBREAK command.As first character at terminal prompt, load interactive subshell.Double dollar sign: Extrinsic (user-written) function prefix:$$name(parameters). $$ is returned by $STACK when context wasestablished by an extrinsic function reference.Prefix to a routine name to directly invoke that routine.2 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


Symbols Used in <strong>Caché</strong> <strong>ObjectScript</strong>Symbol$$$%%%&&&'Name and UsageTriple dollar sign: Macro invocation prefix.Percent sign (37): Permitted as first character of names: (1) localvariable names, indicating a “% variable” with special scoping rules,used for locking. (2) routine names, often indicates a system utility.(3) Package class names, such as %SYSTEM.class and%Library.class. (4) Method names, such as %New() and%OpenId(value). (5) Labels.Required as first character of a macro argument.VMS single-character wildcard in $ZSEARCH.Prefix for some embedded SQL variables: %msg, %ROWCOUNT, and for some SQL keywords: %STARTSWITH.Double percent sign: Prefix for the pseudo-field reference variablekeywords %%CLASSNAME, %%CLASSNAMEQ, %%ID, and%%TABLENAME, used in <strong>Caché</strong> <strong>ObjectScript</strong> computed field codeand trigger code.Ampersand (38): Binary AND logical operator. $BITLOGIC bitstringAND operator.Shell invocation prefix for embedded code. For example &sql(SQLcommands); &js; &html.UNIX batch command.Double ampersand: Binary AND logical operator.Apostrophe (39): Unary Not operator. Can be combined with: logicaloperators '& (Not And), '! (Not Or); relational operators '= (not equalto), '< (not less than), '> (not greater than); or pattern match'(operand?pattern).European numeric group separator.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 3


Symbols and AbbreviationsSymbol( )****/+Name and UsageParentheses (40,41): Used to enclose a procedure or functionparameter list. Parentheses are mandatory, even when empty.Used to nest expressions; nesting overrides the <strong>Caché</strong> default ofstrict left-to-right evaluation of operators, and allows you to giveprecedence to expressions.Used to specify array subscripts for a local variable: a(1,1), aglobal variable: ^a(1,1), or a process-private global: ^||a(1,1).Used to enclose an alternating pattern match (following a ?).With NEW and KILL commands, exclusive (everything but) indicator.For postconditionals, required if postconditional contains a space.Used to enclose embedded SQL code, following an &sql shellinvocation command: &sql(SQL commands).Asterisk (42): Multiplication operator.In $ZSEARCH, wild card for zero, one, or more than one characters.In $EXTRACT, specifies the last character in a string.In WRITE command specifies an integer expression.As prefix to $ZTRAP string value, specifies that call stack levelshould be left unchanged.In certain error codes returned to $ZERROR, a name prefix denotingan undefined local variable, class, method, or property.Double asterisk: Binary exponentiation operator.Asterisk slash Multi-line comment ending indicator. Comment beginswith /*.Plus sign (43): Unary arithmetic positive operator.Addition operator.Line offset indicator: label+offset.With LOCK and ZBREAK commands, enable/increment indicator.4 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


Symbols Used in <strong>Caché</strong> <strong>ObjectScript</strong>Symbol,,,–––...Name and UsageComma (44): In functions and procedures, multiple parametersseparator.In commands, multiple arguments delimiter.In array variables, subscript levels separator.American numeric group separator or European decimal pointcharacter (configurable).In $ECODE, surround error code: ,M7,Two commas: In functions, a placeholder for an unspecifiedpositional parameter (which takes a default value).Minus sign (45): Unary arithmetic negative operator.Subtraction operator.With LOCK and ZBREAK commands, decrement/remove indicator.Double minus sign: With ZBREAK command.Period (46): American decimal point character, or European numericgroup separator (configurable).Object dot syntax used to refer to a method or property of an object:person.Name.Windows and UNIX: As a pathname or part of a pathname, specifiesthe current directory. Used by $ZSEARCH and $ZUTIL(12), amongothers.Pattern match repeat indicator.May be included within a global name or a routine name.Prefixed to variable or array name, specifies passing by reference:.name.Following argumentless DO command, a code block structure lineprefix.Double period: Windows and UNIX: As a pathname or part of apathname, specifies the parent directory of the current directory.Used by $ZSEARCH and $ZUTIL(12), among others... syntax: a prefix that specifies a method or property of the currentobject. For example, WRITE ..foo()<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 5


Symbols Used in <strong>Caché</strong> <strong>ObjectScript</strong>Symbol?@A, aC, cE, eI, iL, lN, nP, pU, u[[ ]\]]]Name and UsageQuestion mark (63): Pattern match operator.In $ZSEARCH, wild card for a single character.In READ and WRITE commands, column position indicator.In ZBREAK command, help text.In Dynamic SQL, an input parameter variable supplied by the Executemethod.At sign (64): Indirection operator. For subscript indirection, appearsas: @array@(subscript).The letter “A” (65,97): Pattern match code (following a ?).The letter “C” (67,99): Pattern match code (following a ?).The letter “E” (69,101): Exponent operator. The uppercase “E” isthe standard exponent operator; the lowercase “e” is a configurableexponent operator. See $ZUTIL(69,63).Pattern match code (following a ?).The letter “I” (73,105): in $NUMBER function: integer indicator.The letter “L” (76,108): Pattern match code (following a ?).The letter “N” (78,110): Pattern match code (following a ?).The letter “P” (80,112): Pattern match code (following a ?).The letter “U” (85,117): Pattern match code (following a ?).Open square bracket (91): Binary contains operator.Square brackets (91,93): Used to enclose a namespace name,directory name, or the null string in an extended global reference:^["namespace"]global or a structured system variable:^$["namespace"]GLOBAL(). Also used with process-private globals,as follows: ^["^"]ppgname.Backslash (92): Integer division operator (drop remainder).Close square bracket (93): Binary follows operator.Double close square brackets: Binary sorts after operator.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 7


Symbols and AbbreviationsSymbol^^^^$^%^(^|_{ }{*}|Name and UsageCaret (94): Global variable name prefix, for example, ^myglobal(i).Routine invocation prefix, for example, DO ^routine or DOlabel^routine.Implied namespace prefix with the format ^system^dir.Double caret: Implied namespace prefix for the current system, withthe format ^^dir.Caret dollar: Structured system variable prefix. For example,^$GLOBAL() or ^$|"namespace"|GLOBAL().Caret percent: System global prefix, for example, ^%utility or^%qStream.Caret parenthesis: A naked global reference, where themost-recently-named subscripted global name is implied. Forexample: ^(1,2)Caret bar: depending on the character(s) that follow, this may beeither:An extended global reference, a global reference where a pair ofbars encloses a null string, or a quoted namespace or directoryname. The bars and their contents are not part of the global name.For example: ^|""|globname, or ^|"namespace"|globname.A process-private global prefix with the prefix ^||. The bars are partof the process-private global name. For example, ^||ppgname. Alsovalid as syntax for this process-private global: ^|"^"|ppgname or^["^"]ppgname.Underscore (95): Binary concatenate operator.Curly braces (123,125): Code block delimiters used in procedures,or with the IF, FOR, DO WHILE, and WHILE commands.In SQL compute code, encloses a field name. In this case, no blankspaces are permitted: SET {Age}=18Asterisk within curly braces: In SQL compute code, specifies thecurrent SQL field name.Vertical bar (124): $BITLOGIC bitstring OR operator.For other uses, see ^| and ^$.8 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


Abbreviations Used in <strong>Caché</strong> <strong>ObjectScript</strong>Symbol||~Name and UsageDouble vertical bar (bar bar): Binary OR logical operator.Tilde (126):$BITLOGIC bitstring NOT (one's complement) operator.Abbreviations Used in <strong>Caché</strong> <strong>ObjectScript</strong>A table of abbreviations for commands, functions, and special variables available in <strong>Caché</strong><strong>ObjectScript</strong>.Table of AbbreviationsThe following are the name abbreviations used in <strong>Caché</strong> <strong>ObjectScript</strong>. Most, but not all,<strong>Caché</strong> <strong>ObjectScript</strong> commands, functions, and special variables have name abbreviations.Other uses of letters as code characters are found in the table of symbols used in <strong>Caché</strong><strong>ObjectScript</strong>.Abbreviation$ABC$CD$DE$E$EC$ES$ETF$F$FNGFull Name$ASCII functionBREAK commandCLOSE command$CHAR functionDO command$DATA functionELSE command (legacy version only)$EXTRACT function$ECODE special variable$ESTACK special variable$ETRAP special variableFOR command$FIND function$FNUMBER functionGOTO command<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 9


Symbols and AbbreviationsAbbreviation$G^$GH$HI$I$INJ$J^$JK$KL$L^$L$LB$LD$LF$LFS$LG$LI$LL$LS$LTSMFull Name$GET function^$GLOBAL structured system variableHALT command (no arguments) or HANG command (withargument)$HOROLOG special variableIF command$INCREMENT function (with arguments) or $IO special variable(no arguments).$INUMBER functionJOB command$JUSTIFY function (with arguments) or $JOB special variable (noarguments).^$JOB structured system variableKILL command$KEY special variableLOCK command$LENGTH function^$LOCK structured system variable$LISTBUILD function$LISTDATA function$LISTFIND function$LISTFROMSTRING function$LISTGET function$LIST function$LISTLENGTH function$LISTSAME function$LISTTOSTRING functionMERGE command10 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


Abbreviations Used in <strong>Caché</strong> <strong>ObjectScript</strong>AbbreviationN$N$NA$NUMO$OP$PQ$Q$QL$QSR$R^$R$RES$S$ST$TTC$TL$TRTROFull NameNEW command$NEXT function$NAME function$NUMBER functionOPEN command$ORDER functionPRINT command$PIECE function (with arguments) or $PRINCIPAL special variable(no arguments).QUIT command$QUERY function (with arguments) or $QUIT special variable (noarguments).$QLENGTH function$QSUBSCRIPT functionREAD command$RANDOM function^$ROUTINE structured system variable$REVERSE functionSET command$SELECT function (with arguments) or $STORAGE special variable(no arguments).$STACK function (with arguments) or $STACK special variable (noarguments).$TEXT function (with arguments) or $TEST special variable (noarguments).TCOMMIT command$TLEVEL special variable$TRANSLATE functionTROLLBACK command<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 11


Symbols and AbbreviationsAbbreviationTSUV$VWX$X$Y$ZAZB$ZB$ZC$ZCVT$ZD$ZDH$ZDT$ZDTH$ZE$ZF$ZHZI$ZI$ZISZKZLFull NameTSTART commandUSE commandVIEW command$VIEW functionWRITE commandXECUTE command$X special variable (no abbreviation).$Y special variable (no abbreviation).$ZA special variable (no abbreviation).ZBREAK command$ZBOOLEAN function (with arguments) or $ZB special variable (noarguments, no abbreviation).$ZCYC function (with argument) or $ZCHILD special variable (noarguments).$ZCONVERT function$ZDATE function$ZDATEH function$ZDATETIME function$ZDATETIMEH function$ZERROR special variable$ZF functions (no abbreviation). See also $ZF(-1), $ZF(-2), $ZF(-3),$ZF(-4), $ZF(-5), and $ZF(-6) functions.$ZHEX function (with arguments) or $ZHOROLOG special variable(no arguments).ZINSERT command$ZIO special variable$ZISWIDE functionZKILL commandZLOAD command12 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsThis document provides detailed descriptions of the commands supported by <strong>Caché</strong><strong>ObjectScript</strong>. In this manual, <strong>Caché</strong> <strong>ObjectScript</strong> commands are divided into three groups:• General Commands.• Routine and Debugging Commands (the names of which begin with “Z”).• Legacy (obsolete) Commands.Within each group, the commands are presented in alphabetical order.For more information on <strong>ObjectScript</strong> commands generally, see the Commands chapter ofUsing <strong>Caché</strong> <strong>ObjectScript</strong>.You can abbreviate most commands to the first letter of the command name, or, in the caseof commands that begin with the letter Z, to the first two letters of the command name. Inthe Synopsis for each command, the full name syntax is first presented, and below it is shownthe abbreviated name (if one exists).The Synopsis for each command contains only literal syntactical punctuation. The Synopsisdoes not include punctuation for format conventions, such as what elements of the syntax areoptional. This information is provided in the table of arguments immediately following theSynopsis.The one exception is the ellipsis (...). An ellipsis following a comma indicates that the argument(or argument group) preceding the comma can be repeated multiple times as a comma-separatedlist. An ellipsis within curly braces { . . . } indicates that a block of code containing oneor more commands can be specified within the curly braces. The curly braces are literalcharacters that must be specified in the code.Most commands take one or more arguments. Arguments are expressions (for example, afunction and its parameters, a variable, an operator and its operands, an object property, oran object method) that define or control the action of the command. Multiple arguments usedwith a command are generally referred to as an argument list. Some commands have argumentsthat themselves take argument parameters. For example, each argument of the DO commandcan take a parameter list. This is indicated in the syntax.Some commands are argumentless, and can be invoked without any arguments. Some commandsnever take arguments; other commands take arguments only in certain circumstances.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 15


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsSuch commands change their meaning depending on whether they are argumentless, orspecify an argument list.Most commands can take an optional postconditional expression, which specifies a conditionthat dictates whether or not the command should be executed. A postconditional expressionis appended to the command name by a colon (:). No spaces or line breaks are permittedbetween a command name and its postconditional expression. While a postconditionalexpression is not, strictly speaking, a command argument, they are here presented with thearguments. An argumentless command can take a postconditional expression.Most <strong>Caché</strong> <strong>ObjectScript</strong> commands are the same on all hardware platforms. Any platformspecificfeatures of a command are marked with the type of platform that supports it (forexample, Windows, UNIX, or OpenVMS.) Any command not marked with a platform limitationis supported by all platforms.BREAKArgumentless: Interrupts execution of the current routine and returns control to programmermode. With an Argument: Enables or disables interrupts.BREAK:pc statusB:pc statusBREAK:pc "extend"B:pc "extend"ArgumentspcstatusextendOptional — A postconditional expression.Optional — Switch to enable or disable interrupts. Valid values are: 0disable, 1 enable. Cannot be used with the extend argument.Optional — A code indicating the kind of interrupts to enable or disable,specified as a quoted string. Valid values are listed in BREAK ExtendedArguments. Cannot be used with the status argument.DescriptionThe BREAK command has two forms:• Without an argument• With an argument16 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


BREAKBREAK without an ArgumentArgumentless BREAK inserted into routine code interrupts execution of the current routineand returns control to programmer mode for debugging purposes.Argumentless BREAK included in code sets a breakpoint, which interrupts routine executionand returns the process to programmer mode. <strong>InterSystems</strong>, however, recommends that youuse the ZBREAK command to invoke the <strong>Caché</strong> debugger, rather than setting breakpointswith BREAK.BREAK with an ArgumentBREAK status enables or disables interrupts.BREAK extend enables or disables a specified type of breakpoints, as described in BREAKExtended Arguments.ArgumentspcAn optional postconditional expression. <strong>Caché</strong> executes the BREAK command if the postconditionalexpression is true (evaluates to a non-zero numeric value). <strong>Caché</strong> does not executethe command if the postconditional expression is false (evaluates to zero). For further details,refer to Command Postconditional Expressions in Using <strong>Caché</strong> <strong>ObjectScript</strong>.statusA switch to enable or disable interrupts. If set to 0, interrupts are disabled. If set to 1, interruptsare enabled.ExamplesThe following example, issued at programmer prompt or included in source code, enablesuser interrupts with a CTRL-CB 1 ; Enable user interrupts with NotesBreak Command SyntaxOlder versions of <strong>Caché</strong> <strong>ObjectScript</strong> accepted only the abbreviation (B) for the BREAKcommand. Current versions accept either form.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 17


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsThe Argumentless BREAK CommandYou can use the argumentless BREAK command in program source code, with or withouta postconditional, to interrupt program execution and return to the programmer prompt.If you include an argumentless BREAK within a routine, it designates a breakpoint. Byimbedding breakpoints in your code, you can establish specific contexts for debugging. Eachtime execution reaches a BREAK, <strong>Caché</strong> suspends the routine and returns you to the programmerprompt. You can then use other <strong>Caché</strong> <strong>ObjectScript</strong> commands to perform debuggingactivities. For example, you might use the WRITE command to examine the values of variablesat the current stopping point and the SET command to supply new values for these orother variables. You can also invoke the Routine Line Editor (XECUTE ^%), which providesbasic editing capabilities for modifying the routine After you suspend routine execution witha BREAK, you can resume normal execution by using an argumentless GOTO. Alternatively,you can resume execution at a different location by specifying this location as an argumentof the GOTO command.Note:<strong>InterSystems</strong> recommends that you use the ZBREAK command to invoke the <strong>Caché</strong>Debugger, rather than using the BREAK command in code. The Debugger providesmuch more extensive debugging capabilities.Using Argumentless BREAK with a ConditionYou may find it useful to specify a condition on an argumentless BREAK command in codeso that you can rerun the same code simply by setting a variable rather than having to changethe routine. For example, you may have the following line in a routine:BREAK:$DATA(debug)You can then set the variable debug to suspend the routine and return the job to programmermode or clear the variable debug to continue running the routine.Setting User Interrupts with the BREAK CommandUse BREAK status to control whether user interrupts, such as CTLR-C, are enabled or disabled.The valid values for status are 1 (enabled) and 0 (disabled).• BREAK 1 enables interrupts from any terminal owned by the process.• BREAK 0 disables interrupts from any terminal owned by the process.This behavior takes place even if you did not specifically enable interrupts for the terminalin the argument list for the associated OPEN or USE command.18 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


BREAKNote:BREAK 0 is ineffective in <strong>Caché</strong> <strong>ObjectScript</strong> if you issue it after issuing an OPENcommand that specifically enables interrupts.BREAK Extended ArgumentsYou do not have to place argumentless BREAK commands at every location where you wantto suspend your routine. BREAK has a series of "extended" arguments (extend) that canperiodically suspend a routine as if you scattered argumentless BREAKs throughout thecode. BREAK command extended arguments are listed in the following table.Argument"S""S-""S+""L""L-""L+""C""OFF"DescriptionUse BREAK "S" (Single Step) to step through your code a singlecommand at a time, breaking on every <strong>Caché</strong> <strong>ObjectScript</strong> command.The system stops breaking when a DO command, an XECUTEcommand, a FOR loop, or a user-defined function is encountered, andresumes when the command or loop is done.Use BREAK "S-" to disable single stepping at the current level andenable command stepping at the previous level.BREAK "S+" acts like BREAK "S", except that <strong>Caché</strong> continues tobreak on every command, including when a DO command, an XECUTEcommand, a FOR loop, or a user-defined function is encountered.Use BREAK "L" (Line Break) to step through your code a single routineline at a time, breaking at the beginning of every line. The system stopsbreaking when a DO command, an XECUTE command, or user-definedfunction is encountered, and resumes when the command or loop isdone.Use BREAK "L-" to disable single stepping at the current level andenable line stepping at the previous level.BREAK "L+" acts like BREAK "L", except that <strong>Caché</strong> continues tobreak at the beginning of every routine line when a DO command,XECUTE command, or user-defined function is encountered.Use BREAK "C" (Clear Break) to stop breaking. Breaking resumes ata higher routine level after the job executes a QUIT if a BREAK stateis in effect at that higher level.BREAK "OFF" removes all debugging that has been established forthe process. It removes all breakpoints and watchpoints, and turns offstepping at all program stack levels. It also removes the associationwith the debug and trace devices, but does not close them.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 19


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsSee Debugging in Using <strong>Caché</strong> <strong>ObjectScript</strong> for more information about these extendedarguments.Issuing a BREAK "OFF" command is equivalent to issuing the following series of commands:ZBREAK /CLEARZBREAK /TRACE:OFFZBREAK /DEBUG:""ZBREAK /ERRORTRAP:ONBREAK "C" ; applied to all stack levelsSee Also• ZBREAK command• OPEN command• USE command• $ZUTIL(68,5) Argumentless BREAK Process Switch function• $ZUTIL(69,5) Argumentless BREAK System Default function• Debugging in Using <strong>Caché</strong> <strong>ObjectScript</strong>• Terminal I/O in <strong>Caché</strong> I/O Device GuideCLOSEShuts down a device.CLOSE:pc closearg,...C:pc closearg,...where closearg is :device:parametersArgumentspcdeviceparametersOptional — A postconditional expression.The device to be closed.Optional — A list of parameters used to set characteristics of thedevice.20 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


DescriptionCLOSE device releases ownership of the specified device, optionally sets certain devicecharacteristics, and returns it to the pool of available devices. If the process does not own thespecified device, the system ignores the CLOSE.ArgumentspcAn optional postconditional expression. <strong>Caché</strong> executes the CLOSE command if the postconditionalexpression is true (evaluates to a non-zero numeric value). <strong>Caché</strong> does not executethe command if the postconditional expression is false (evaluates to zero). For further details,refer to Command Postconditional Expressions in Using <strong>Caché</strong> <strong>ObjectScript</strong>.deviceThe device to be closed. It is required and can be specified as a single device ID or as acomma-separated list of device IDs. Specify the same device ID (mnemonic or number) asspecified on the corresponding OPEN command. For more information on specifying deviceIDs, refer to the OPEN command.The device ID of the current device is contained in the $IO special variable.parametersCLOSEA colon separated list of parameters used to set certain characteristics of the specified device.The available parameters are as follows:"D""R":newnamecloses and deletes a sequential filecloses and renames a sequential fileRefer to RMS and Sequential File I/O in the <strong>Caché</strong> I/O Device Guide for further information.ExamplesIn the following UNIX example, the CLOSE command closes device C (/dev/tty02), butonly if it is not the current device. The postconditional uses the $IO special variable to checkfor the current device.CloseDevCSET C="/dev/tty02"OPEN C; ...CLOSE:$IO'=C C<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 21


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsNotesAcquiring Ownership of a DeviceA process acquires ownership of a device with the OPEN command and makes it active withthe USE command. If the closed device is the active (that is, current) device, the default I/Odevice becomes the current device. (The default I/O device is established at log-in.) When aprocess is terminated (for example, after a HALT), all of its opened devices are automaticallyclosed and returned to the system.If the process's default device is closed, any subsequent output (such as error messages) tothat device causes the process to hang. In this case, you must explicitly re-open the defaultdevice.See Also• OPEN command• I/O Devices and Commands in <strong>Caché</strong> I/O Device GuideCONTINUEJumps to FOR, WHILE, or DO WHILE command and reexecutes test and loop.CONTINUE:pcArgumentpcOptional — A postconditional expression.DescriptionThe CONTINUE command is used within the code block following a FOR, WHILE, or DOWHILE command. CONTINUE causes execution to jump back to the FOR, WHILE, or DOWHILE command. The FOR, WHILE, or DO WHILE command evaluates its test condition,and, based on that evaluation, re-executes the code block loop. Thus, the CONTINUE commandhas exactly the same effect on execution as reaching the closing curly brace ( } ) of thecode block.CONTINUE takes no arguments (other than the postconditional). At least two blank spacesmust separate it from a command following it on the same line.22 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


ArgumentspcAn optional postconditional expression that can make the command conditional. <strong>Caché</strong> executesthe CONTINUE command if the postconditional expression is true (evaluates to a nonzeronumeric value). <strong>Caché</strong> does not execute the command if the postconditional expressionis false (evaluates to zero). For further details, refer to Command Postconditional Expressionsin Using <strong>Caché</strong> <strong>ObjectScript</strong>.ExampleLoopSET val=4,x=valFOR num=val {WRITE num*3CONTINUE:xWRITE "more to come",val}QUITCONTINUESee Also• DO WHILE command• FOR command• WHILE command<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 23


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsDOCalls a routine.DO:pc doargument,...D:pc doargument,...where doargument is:entryref(param,...):pcArgumentspcentryrefparamOptional — A postconditional expression.Optional — The label name of the routine to be called.Optional — Parameter values to be passed to the called routine.DescriptionThe DO command and the DO WHILE command are separate commands. This page documentsthe DO command. In the DO WHILE command, the DO keyword and the WHILEkeyword may be separated by several lines of code; however, you can immediately identifya DO WHILE command because the DO keyword is followed by an open curly brace.The DO command has two forms:• Without an argument• With an argumentDO without an argument calls the next inner routine in a block structure. That is, <strong>Caché</strong>executes the block of code that immediately follows the DO command, then executes thenext command after that block of code.Note:DO without an argument uses an older block structure syntax that has been supersededby the curly brace block structure. Therefore, DO without an argument is consideredobsolete and should only be used to maintain existing applications and should notbe used in new code.DO with an argument calls a specified subroutine, function, or procedure. <strong>Caché</strong> executesthis block of code, then executes the next command after the DO command. You can call the24 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


outine with or without parameter passing. The DO command cannot receive a return valuefrom the called routine.Each invocation of DO places a new context frame on the call stack for your process. The$STACK special variable contains the current number of context frames on the call stack.ArgumentspcAn optional postconditional expression. If the postconditional expression is appended to theDO command keyword, <strong>Caché</strong> executes the DO command if the postconditional expressionis TRUE (evaluates to a non-zero numeric value). <strong>Caché</strong> does not execute the DO commandif the postconditional expression is FALSE (evaluates to zero).If the postconditional expression is appended to an argument, <strong>Caché</strong> executes the argumentif the postconditional expression is TRUE (evaluates to a non-zero numeric value). If thepostconditional expression is FALSE (evaluates to zero), <strong>Caché</strong> skips that argument andproceeds to evaluate the next argument (if there is one) or the next command.When using DO to invoke an object method, the postconditional expression must appendedto the DO command keyword, not the argument. Appending a postconditional expression toan object reference argument results in a compilation error. For example, use DO:xmyoref.mymethod() not DO myoref.mymethod():x.For further details, refer to Command Postconditional Expressions in Using <strong>Caché</strong><strong>ObjectScript</strong>.entryrefThe label name of the routine (Subroutines, Procedures, or Extrinsic Functions) to be called.You can specify multiple routines as a comma-separated list.entryref can take any of the following forms.DO<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 25


<strong>Caché</strong> <strong>ObjectScript</strong> Commandslabel+offsetlabel+offset^routine^routineoref.Method()Specifies a line label within the current routine. Theoptional +offset can only be used when calling asubroutine to which no parameters are passed; it cannotbe used when calling a procedure or when passingparameters to a subroutine. offset is a nonnegativeinteger that specifies the number of lines after the labelat which execution of the subroutine is to start.Specifies a line label within the named routine thatresides on disk. <strong>Caché</strong> loads the routine from disk andbegins execution at the indicated label. The +offset isoptional.Specifies a routine that resides on disk. The systemloads the routine from disk and begins execution at thefirst executable line of the routine.Specifies an object method. The system accesses theobject and executes the specified method, passing thearguments (if any) specified in param, the method'sargument list. Object calls use dot syntax: oref (theobject reference) and Method() are separated by a dot;blank spaces are not permitted. A method must specifyits open and close parentheses, even if there are noparam arguments.If you specify a non-existent label, <strong>Caché</strong> issues a error message. If you specifya non-existent routine, <strong>Caché</strong> issues a error message. If you specify a nonexistentmethod, <strong>Caché</strong> issues a error message. For furtherdetails on these errors, refer to the $ZERROR special variable.paramParameter values to be passed to the subroutine, procedure, extrinsic function or object method.You can specify a single param value, or a comma-separated list of param values. A paramlist is enclosed in parentheses. When no param is specified, the enclosing parentheses arerequired when calling a procedure or extrinsic function, optional when calling a subroutine.Parameters can be passed by value or by reference. The same call can mix parameters passedby value and parameters passed by reference. When passing by value, you can specify aparameter as a value constant, expression, or unsubscripted local variable name. (See PassingBy Value.) When passing by reference, the parameters must reference the name of a localvariable or unsubscripted array in the form .name. (See Passing By <strong>Reference</strong>.)26 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


The Argumentless DO CommandThe argumentless DO command executes a block of code that immediately follows it in thesame program. Argumentless DO blocks can be nested, and a postconditional expression onthe DO command can be used to determine whether or not to execute a code block.The block structures provided by the IF, FOR, DO WHILE, and WHILE commands are apreferable means to perform the same operations. The argumentless DO command continuesto be supported, but its use in new coding is discouraged. For further details, see ArgumentlessDO (legacy version).The DO Command with ArgumentsThe DO command with entryref arguments invokes the execution of one or more blocks ofcode that are defined elsewhere. Each block of code to execute is specified by its entryref.The DO command can specify multiple blocks of code to execute as a comma-separated list.The execution of the DO command, and the execution of each entryref in a comma-separatedlist can be governed by optional postconditional expressions.DO can invoke the execution of a subroutine (with or without parameter passing), a procedure,or an extrinsic function. Upon completion of the execution of the block of code, executionresumes at the next command after the DO command. A block of code invoked by the DOcommand cannot return a value to the DO command. Thus DO can execute an extrinsicfunction, but cannot receive the return value of that function.You can specify a $CASE function as a DO command argument.The DO Command without Parameter PassingThe DO command without parameter passing is only used with subroutines. Use of DOentryref without parameter passing (that is, without specifying the param option) takesadvantage of the fact that a calling routine and its called subroutine share the same variableenvironment. Any variable updates made by the subroutine are automatically available to thecode following the DO command.When using DO without parameter passing, you must make sure that both the calling routineand the called subroutine reference the same variables.DONote:Procedures handle variables entirely differently. Refer to Procedures in Using <strong>Caché</strong><strong>ObjectScript</strong>.In the following example, Start (the calling routine) and Exponent (the called subroutine)share access to three variables: num, powr, and result. Start sets num and powr to the usersuppliedvalues. These values are automatically available to Exponent when it is called by<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 27


<strong>Caché</strong> <strong>ObjectScript</strong> Commandsthe DO command. Exponent references num and powr and places the calculated value inresult. When Exponent executes the QUIT command, control returns to the WRITE commandimmediately after the DO. The WRITE command outputs the calculated value by referencingresult.Start ; Raise an integer to a specified power.READ !,"Integer= ",num QUIT:num=""READ !,"Power= ",powr QUIT:powr=""DO ExponentWRITE !,"Result= ",result!QUITExponentSET result=numFOR i=1:1:powr-1 { SET result=result*num }QUITIn the following example, DO invokes the Admit() method on the object referred to by pat.The method does not receive parameters or return a value.DO pat.Admit()In the following example, the DO command calls, in succession, the subroutines Init andRead1 in the current routine and the subroutine Convert in routine Test.DO Init,Read1,Convert^TestDO and GOTOThe DO command can be used to invoke a subroutine (with or without parameter passing),a procedure, or an extrinsic function. At the completion of the call, <strong>Caché</strong> executes the nextcommand following the DO command.The GOTO command can only be used to invoke a subroutine without parameter passing.At the completion of the call, <strong>Caché</strong> issues a QUIT, ending execution.DO with Parameter PassingWhen used with parameter passing, DO entryref explicitly passes one or more values to thecalled subroutine, procedure, extrinsic function or object method. The passed values arespecified as a comma-separated list with the param option. With parameter passing, you mustmake sure that the called subroutine is defined with a parameter list. The subroutine definitiontakes the form:>label( param)where label is the label name of the subroutine, procedure, extrinsic function or object method,and param is a comma separated list of one or more unsubscripted local variable names. Forexample,28 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


DOMainSET x=1,y=2,z=3WRITE !,"In Main ",x,y,zDO Sub1(x,y,z)WRITE !,"Back in Main ",x,y,zQUITSub1(a,b,c)WRITE !,"In Sub1 ",a,b,cQUITThe list of parameters passed by the DO command is known as the actual parameter list.The list of parameter variables defined as part of the label of the coded routine is known asthe formal parameter list. When DO calls the routine, the parameters in the actual parameterlist are mapped, by position, to the corresponding variables in the formal parameter list. Inthe above example, the value of the first actual parameter (x) is placed in the first variable(a) of the subroutine's formal parameter list; the value of the second actual parameter (y) isplaced in the second variable (b); and so on. The subroutine can then access the passed valuesby using the appropriate variables in its formal parameter list.If there are more variables in the formal parameter list than there are parameters in the actualparameter list, the extra variables are left undefined. In the following example, the formalparameter c is left undefined:MainSET x=1,y=2,z=3WRITE !,"In Main ",x,y,zDO Sub1(x,y)WRITE !,"Back in Main ",x,y,zQUITSub1(a,b,c)WRITE !,"In Sub1 ",a,b,cQUITYou can specify a default value for a formal parameter, to be used when no actual parametervalue is specified.You can leave any variable undefined by omitting the corresponding parameter from the DOcommand's actual parameter list. However, you must include a comma as a place holder foreach omitted actual parameter. In the following example, the formal parameter b is leftundefined:MainSET x=1,y=2,z=3WRITE !,"In Main ",x,y,zDO Sub1(x,,z)WRITE !,"Back in Main ",x,y,zQUITSub1(a,b,c)WRITE !,"In Sub1 ",a,b,cQUIT<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 29


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsThe DO command can pass parameters either by value or by reference. You can mix passingby value and passing by reference within the same DO command. For further details, referto Parameter Passing in Using <strong>Caché</strong> <strong>ObjectScript</strong>.DO with IndirectionYou can use indirection to supply a target subroutine location for DO. For example, youmight implement a generalized menu program by storing the various menu functions at differentlocations in a separate routine. In your main program code, you could use name indirectionto provide the DO command with the location of the function corresponding to eachmenu choice.You cannot use indirection with <strong>Caché</strong> object dot syntax. This is because dot syntax is parsedat compile time, not at runtime.In name indirection, the value of the expression to the right of the indirection operator (@)must be a name (that is, a label or a routine name). In the following code segment, nameindirection supplies the DO with the location of a target function in the routine Menu.READ !,"Enter the number for your choice: ",num QUIT:num=""DO @("Item"_num)^MenuThe DO command invokes the subroutine in Menu whose label is Item concatenated withthe user-supplied num value (for example, Item1, Item2, etc.).You can also use the argument form of indirection to substitute the value of an expressionfor a complete DO argument. For example, consider the following DO command:DO @(eref_":fstr>0")This command calls the subroutine specified by the value of eref if the value of fstr is greaterthan 0.For more information, refer to Indirection in Using <strong>Caché</strong> <strong>ObjectScript</strong>.DO with PostconditionalsYou can use postconditional expressions to select a target subroutine for a DO command. Ifthe postconditional expression returns FALSE (0), <strong>Caché</strong> ignores the associated subroutinecall. If the postconditional expression returns TRUE (1), <strong>Caché</strong> executes the associated subroutinecall, then returns to the DO command. You can use postconditionals on both the DOcommand and the subroutine arguments.For example, consider the command:DO:F>0 A:F=1,B:F=2,C30 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


The DO command has a postconditional expression; if F is not greater than 0, no part of theDO is executed. The DO command's arguments also have postconditional expressions. DOuses these argument postconditionals to select which subroutine(s) (A, B, or C) to execute.All subroutines that fulfill the truth condition are executed, in the order presented. Thus, inthe above example, C, with no postconditional, is always executed: if F=1 both A and C areexecuted; if F=2, B and C are executed; if F=3 (or any other number) C is executed. Toestablish C as a true default, do the following:DO:F>0 A:F=1,B:F=2,C:((F'=1)&&(F'=2))In this example, one and only one subroutine is executed.For more information on how postconditional expressions are evaluated, see CommandPostconditional Expressions in Using <strong>Caché</strong> <strong>ObjectScript</strong>.When using argument postconditionals, make sure there are no unwanted side effects. Forexample, consider the following command:DO @^Control(i):z=1In this case, ^Control(i) contains the name of the subroutine to be called if the postconditionalz=1 tests TRUE. Whether or not z=1, <strong>Caché</strong> evaluates the value of ^Control(i) and resets thecurrent global naked indicator accordingly. If z=1 is FALSE, <strong>Caché</strong> does not execute the DO.However, it does reset the global naked indicator just as if it had executed the DO. For moredetails on the naked indicator, see Naked Global <strong>Reference</strong> in Using <strong>Caché</strong> Multi-DimensionalStorage.$TEST Behavior with DOWhen you use DO to call a subroutine (either with or without parameter passing), <strong>Caché</strong> doesnot preserve the value of the $TEST special variable across the call. The argumentless DOis the only standard form that preserves the value of $TEST.To save the $TEST value across a DO call, you can explicitly assign it to a variable prior tothe call. You can then reference the variable in code that follows the call.The following code illustrates some unexpected $TEST behavior that can result when usingDO with the legacy IF command (which sets $TEST). This behavior does not occur withthe standard (code block) IF command, because the standard IF does not set $TEST.DO<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 31


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsStart ; This routine uses the legacy IF command syntaxSET x=1IF x=1 DO Sub1(x) ; sets $TEST to TRUE (1)ELSE DO Sub2(x)QUITSub1(y) ; a subroutine that evaluates a FALSE IFWRITE !,"hello from subroutine 1"IF y=2 WRITE " - IF in Sub1 was TRUE" ; Set $TEST to FALSE (0)ELSE WRITE " - IF in Sub1 was FALSE"QUITSub2(z) ; another subroutineWRITE !,"hello from subroutine 2"QUITAt first glance, you might expect that Start will call only Sub1 and then exit.In fact, execution of this code produces the following:USER>DO ^Starthello from subroutine 1 - IF in Sub1 was FALSEhello from subroutine 2This unexpected behavior results from the fact the $TEST value is reset in Sub1, that causes<strong>Caché</strong> to execute the ELSE command in Start. The processing sequence is as follows:1. <strong>Caché</strong> evaluates the IF command expression in Start as TRUE. It sets $TEST to TRUEand calls Sub1.2. <strong>Caché</strong> evaluates the IF command expression in Sub1 as FALSE. It sets $TEST to FALSEand then executes the following ELSE command.3. <strong>Caché</strong> returns to Start when it encounters the QUIT.4. <strong>Caché</strong> executes the ELSE in Start and performs the DO call to Sub2. It executes theELSE because $TEST was set to FALSE in Sub1, replacing the TRUE value set by theIF command in Start.To produce the expected behavior, you could replace the ELSE in either Start or Sub1with an additional IF. For example, you might recast Start as follows:StartSET x=1IF x=1 DO Sub1(x)IF x'=1 DO Sub2(x)QUITSee Also• GOTO command• XECUTE command• FOR command32 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


DO WHILE• QUIT command• Argumentless DO (legacy version) command• IF (legacy version) command• $CASE function• $STACK special variable• Subroutines in Using <strong>Caché</strong> <strong>ObjectScript</strong>• Procedures in Using <strong>Caché</strong> <strong>ObjectScript</strong>• Parameter Passing in Using <strong>Caché</strong> <strong>ObjectScript</strong>DO WHILEExecutes code while a condition exists.DO {code} WHILE expression,...ArgumentscodeexpressionA block of <strong>Caché</strong> Objectscript commands.A test condition.DescriptionDO WHILE executes code, then evaluates expression. If expression evaluates to TRUE, DOWHILE loops and re-executes code. If expression is not TRUE, code is not re-executed, andthe next command following DO WHILE is executed.Note that DO WHILE is always written in block-oriented form. The code to be executed isplaced between the DO and the WHILE keywords, and is enclosed by curly braces.The DO keyword of a DO WHILE must be separated from the opening curly brace by exactlyone blank space. If there is more than one space after the DO keyword, <strong>Caché</strong> interprets itas a legacy argumentless DO command. There are no other special whitespace restrictions.The curly braces, comments, commands within the code block and arguments within commandsmay be separated from one another by one or more blank spaces and/or line returns.However, as in all <strong>Caché</strong> Objectscript commands, each command keyword must be separatedfrom its first argument by exactly one space.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 33


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsArgumentscodeA block of one or more <strong>Caché</strong> Objectscript commands. The code block may span severallines. The code block is enclosed by curly braces.expressionA test condition which can take the form of a single expression or a comma separated list ofexpressions. For an expression list, <strong>Caché</strong> evaluates the individual expressions in left to rightorder. It stops evaluation if it encounters an expression that is FALSE. If all expressionsevaluate to TRUE, <strong>Caché</strong> re-executes the code commands. DO WHILE executes repeatedly,testing expression for each loop. If any expression evaluates to FALSE, <strong>Caché</strong> ignores anyremaining expressions, and does not loop. It executes the next command after DO WHILE.ExamplesThe following examples show first a DO WHILE in which expression is TRUE, and then aDO WHILE in which expression is FALSE. When expression is FALSE, the code block isexecuted once.DoWhileTrueSET x=1DO {WRITE !,"Looping",xSET x=x+1} WHILE x


DO WHILEQUIT and GOTOThe QUIT command within code ends the DO WHILE loop and returns execution to thecommand following, as shown in the following example:TestloopSET x=1DO {WRITE !,"looping "SET x=x+1WRITE " x=",xQUIT} WHILE x


<strong>Caché</strong> <strong>ObjectScript</strong> Commandsmainloop ; Example of a GOTO out of a nested code blockSET x=1DO {WRITE !,"First time through, x=",xIF x#2=0 {WRITE !,"Even numbered loop, x=",xSET x=x+1GOTO tag}ELSE {WRITE !,"Odd numbered loop, x=",xSET x=x+1GOTO tag}WRITE !,"this should never write"tagWRITE !,"bottom of the DO WHILE loop"} WHILE x


ELSEELSEClause of block-oriented IF command.ELSE { code_block }Refer to IF command.DescriptionELSE is not a separate command, but a clause of the block-oriented IF command. Refer tothe IF command for details.Note:An earlier version of the ELSE command may exist in legacy applications where itis used with a line-oriented IF command. These commands may be recognizedbecause they do not use curly braces. The old and new forms of IF and ELSE aresyntactically different and should not be combined; therefore, an IF of one typeshould not be paired with an ELSE of the other type.The earlier line-oriented ELSE command could be abbreviated as E. The block-orientedELSE keyword cannot be abbreviated.The ELSE keyword must be followed by an opening and closing curly brace ({) and (}).Usually these curly braces enclose a block of code. However, an ELSE with no code blockis permissible, as in the following:SET x=1LoopIF x=1{WRITE "Once only"SET x=x+1GOTO Loop}ELSE{}WRITE !,"All done"There are no whitespace restrictions on the ELSE keyword.See Also• IF command• IF (legacy version) command• Flow Control Commands in Using <strong>Caché</strong> <strong>ObjectScript</strong><strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 37


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsELSEIFClause of block-oriented IF command.Refer to IF command for syntaxDescriptionELSEIF is not a separate command, but a clause of the block-oriented IF command. Referto the IF command for details.See Also• IF commandFORExecutes a block of code repeatedly, testing at the beginning of each loop.FOR variable=forparameter,...{. . .}F variable=forparameter,...{. . .}where forparameter can be:exprstart:incrementstart:increment:endArgumentsvariableexprstartincrementendOptional — A counter variable for the FOR loop.Optional — The value of variable before executing the loopcommands.Optional — The value of variable on the first iteration of the FORloop.Optional — The value used to increment variable after each iterationof the FOR loop.Optional — The value used to terminate the FOR loop.38 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


DescriptionFOR is a block-oriented command. The block of code that constitutes the loop is enclosedin curly braces. This block of code can contain line returns, indents, and blank spaces asneeded. When the loop concludes, execution continues with next command after the closingcurly brace. This next command may be on the same line or on the next line.The FOR command has two basic forms:• Without an argument• With an argumentFOR Without an ArgumentFOR without an argument executes the loop code block indefinitely. <strong>Caché</strong> repeats thecommands within the curly braces until it encounters a QUIT or GOTO command.The FOR keyword without an argument must be separated from the open curly brace thatfollows it by at least one space or tab.FOR With an ArgumentThe action FOR performs depends on the argument form you use.FORFOR variable=expr executes the looping commands once, setting variable to the value ofexpr.FOR variable=start:increment executes the looping commands indefinitely. On the firstiteration, <strong>Caché</strong> sets variable to the value of start. Each execution of the FOR commandincrements the variable value by the specified increment value. <strong>Caché</strong> repeats the commandsuntil it encounters a QUIT or GOTO command.FOR variable=start:increment:end sets variable to the value of start. <strong>Caché</strong> then executesthe looping commands based on the conditions described in this table:increment is positiveIf start > end, do not execute FOR. Whenvariable > (end-increment), or if <strong>Caché</strong>encounters a QUIT or GOTO command,stop.increment is negativeIf start < end, do not execute FOR. Whenvariable < (end-increment), or if <strong>Caché</strong>encounters a QUIT or GOTO command,stop.<strong>Caché</strong> evaluates the start, increment, and end values when it begins execution of the loop.Any changes made to these values within the loop are ignored and have no effect on thenumber of loop executions.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 39


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsWhen the loop terminates, variable contains a value that reflects the increment resulting fromthe last execution of the loop. However, variable is never incremented beyond the maximumvalue specified in end.ArgumentsvariableA variable that holds the current count for the FOR loop. It is a local variable name whichholds the numeric value specified by the other arguments of the FOR command.exprThe numeric value <strong>Caché</strong> assigns to variable before executing the loop commands. The valueof expr can be specified as a literal or any valid expression; <strong>Caché</strong> evaluates expr for itsnumeric value.startThe numeric value <strong>Caché</strong> assigns to variable on the first iteration of the FOR loop. The valueof start can be specified as a literal or any valid expression; <strong>Caché</strong> evaluates start for itsnumeric value.incrementThe numeric value <strong>Caché</strong> uses to increment variable after each iteration of the FOR loop. Itis required if you specify start. The value of increment can be specified as a literal or anyvalid expression; <strong>Caché</strong> evaluates increment for its numeric value. increment can be an integeror a fractional number; it can be a positive number (to increment) or a negative number (todecrement).endThe numeric value <strong>Caché</strong> uses to terminate a FOR loop. When variable equals this value,the FOR loop is executed one last time and then terminated. The value of end can be specifiedas a literal or any valid expression; <strong>Caché</strong> evaluates end for its numeric value.ExamplesArgumentless FORIn the following example, demonstrating argumentless FOR, the user is prompted repeatedlyfor a number that is then passed to the Calc subroutine by the DO command. The FOR loopterminates when the user enters a null string (presses ENTER without inputting a number),which causes the QUIT command to execute.40 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


FORMainloopFOR {READ !,"Number: ",numQUIT:num=""DO Calc(num)}Calc(a)WRITE !,"The number squared is ",a*aQUITUsing FOR variable=exprWhen you specify variable=expr, <strong>Caché</strong> executes the FOR loop once. The value in expr canbe a literal or any valid expression. If you specify an expression, it must evaluate to a singlenumeric value.In the following example, the WRITE command within the curly braces of the FOR commandexecutes once, with num having the value 4. It writes the number 12:LoopSET val=4FOR num=val {WRITE num*3 }QUITUsing FOR variable=start:increment:endThe arguments start, increment, and end specify a start, increment, and end value, respectively.All three are evaluated as numbers. They can be integer or real, positive or negative. If yousupply string values, they are converted to their numeric equivalents at the start of the loop.When <strong>Caché</strong> first enters the loop, it assigns the start value to variable and compares thevariable value to the end value. If the variable value is less than the end value (or greaterthan it, in the case of a negative increment value), <strong>Caché</strong> executes the loop commands. Itthen updates the variable value using the increment value. (The variable value is decrementedif a negative increment is used.)Execution of the loop continues until the incrementing of the variable value would exceedthe end value (or until <strong>Caché</strong> encounters a QUIT or GOTO). At that point, to prevent variablefrom exceeding end, <strong>Caché</strong> suppresses variable assignment and loop execution ends. If theincrement causes the variable value to equal the end value, <strong>Caché</strong> executes the FOR loopone last time and then terminates the loop.The following code executes the WRITE command repetitively to output, in sequence, allof the characters in string1, except for the last character. Because the end value is specifiedas len-1, the last character is not output. This is because the test is performed at the top of theloop, and the loop is terminated when the variable value (index) exceeds (not just matches)the end value (len-1).<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 41


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsStringwriteloopSET string1="123 Primrose Path"SET len=$LENGTH(string1)FOR index=1:1:len-1 {WRITE $EXTRACT(string1,index)}Using FOR variable=start:incrementIn this form of the FOR command there is no end value; the loop must contain a QUIT orGOTO command to terminate the loop.The start and increment values are evaluated as numbers. They can be integer or real, positiveor negative. If string values are supplied, they are converted to their numeric equivalents atthe start of the loop. <strong>Caché</strong> evaluates the start and increment values when it begins executionof the loop. Any changes made to these values within the loop are ignored.When <strong>Caché</strong> first enters the loop, it assigns the start value to variable and executes the loopcommands. It then updates the variable value using the increment value. (The variable valueis decremented if a negative increment is used.) Execution of the loop continues until <strong>Caché</strong>encounters a QUIT or GOTO within the loop.The following example illustrates use of the FOR variable=start:increment form to computean average for a series of user supplied numbers. The postconditional QUIT is included toterminate execution of the loop when the user enters a null string (that is, presses ENTERwithout inputting a value). When the postconditional expression (num="") tests TRUE, <strong>Caché</strong>executes the QUIT and terminates the loop.The loop counter (the i variable) is used to keep track of how many numbers have beenentered. i is initialized to 0 because the counter increment occurs after the user inputs anumber. <strong>Caché</strong> terminates the loop when the user enters a null. After the loop is terminated,the SET command references i (as a local variable) to calculate the average.AverageloopSET sum=0FOR i=0:1 {READ !,"Number: ",numQUIT:num=""SET sum=sum+num}SET average=sum/iFurther Examples of FOR with Increment SyntaxThe following example of the FOR variable=start:increment form prompts the user for anumber and then passes the number and the current value of x to the Calc subroutine invokedby the DO command. The value of x is initialized to 1 and is incremented by 1 for each exe-42 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


cution of the loop. The FOR loop terminates when the user presses ENTER, which causesthe QUIT command to execute.MainloopFOR x=1:1 {READ !,"Number: ",numQUIT:num=""DO Calc(num,x)}Calc(a,b)The following example of the FOR variable=start:increment:end form prompts the user fora number and then passes the number to the Calc subroutine invoked by DO. The value of xis initialized to 1 and is incremented by 1 for each execution of the loop. The FOR loop terminateseither when the value of x would exceed the end value (3) or when the user pressesENTER, causing the QUIT command to execute.MainloopFOR x=1:1:3 {READ !,"Number: ",numQUIT:num=""DO Calc(num)}Calc(a)The following example of the FOR variable=start:increment:end form shows a FOR loopwhich is never executed, since the first value of i (10) is already greater than the end value(1) minus the increment value (1).WRITE !,"Before the FOR"FOR i=10:1:1 {WRITE !,"In the FOR loop, i=",i}WRITE !,"After the FOR"The following example shows a FOR loop that executes the WRITE command 10 times,then completes with i=10.Writeloop1FOR i=1:1:10 {WRITE i,!}WRITE "i=",iQUITThe following example shows a FOR loop that executes the WRITE command 10 times,then completes with i=11.Writeloop2FOR i=1:0:10 {WRITE i,!SET i=i+1}WRITE "i=",iQUITFOR<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 43


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsUsing FOR with Multiple forparametersA single FOR command can contain both types of parameter syntax. The following is anexample of FOR with multiple forparameters. The first forparameter is the expr syntax. Thesecond forparameter is the start:increment:end syntax. The two forparameters are separatedby a comma. The first time through the FOR, <strong>Caché</strong> uses the expr syntax, and invokes theTest subroutine with x equal to the value of y. In the second (and subsequent) iterations, <strong>Caché</strong>uses the start:increment:end syntax. It sets x to 1, then 2, etc. On the final iteration, x=10.MainloopSET y="beta"FOR x=y,1:1:10 {DO Test}QUITTestWRITE !,"Running test number ",xQUITIncrementing with Argumentless FORThe argumentless FOR operates the same as the FOR variable=start:increment form. Theonly difference is that it does not provide a way to keep track of the number of loop executions.The following example shows how the previous loop counter example might be rewrittenusing the argumentless FOR. The assignment i=i+1 replaces the loop counter.Average2loopSET sum=0SET i=0FOR {READ !,"Number: ",num QUIT:num=""SET sum=sum+num,i=i+1}SET average=sum/iWRITE !!,"Average is: ",averageQUITNotesFOR and WatchpointsYou have limited use of watchpoints with FOR. If you establish a watchpoint for the control(index) variable of a FOR command, <strong>Caché</strong> triggers the specific watchpoint action only onthe initial evaluation of each FOR command argument. This restriction is motivated by performanceconsiderations.The following example contains three kinds of FOR command arguments for the watchedvariable x: a range, with initial value, increment, and limit (final value); a single value; and44 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


a range with initial value, increment, and no limit. Breaks occur when x has the initial values1, 20, and 50.USER>ZBREAK *xUSER>FOR x=1:1:10,20,50:2 {SET t=x QUIT:x>69}USER 2f0>WRITEx=1USER 2f0>gUSER>FOR x=1:1:10,20,50:2 {SET t=x QUIT:x>69}USER 2f0>WRITEt=10x=20USER> 2f0>gUSER>FOR x=1:1:10,20,50:2 {SET t=x QUIT:x>69}USER 2f0>WRITEt=20x=50USER 2f0>gUSER>WRITEt=70x=70Terminating a FOR Loop with QUIT or GOTOA FOR loop is terminated by a QUIT only if the QUIT appears within the code block. If<strong>Caché</strong> encounters a QUIT in a subroutine called by the DO command, it terminates only thesubroutine, not the FOR loop itself.A FOR loop is terminated by a GOTO that transfers control outside of its code block. AFOR loop is not terminated by a GOTO that transfers control within its code block. If aGOTO exits from a subroutine called by the DO command, <strong>Caché</strong> exits only the DO command,not the FOR loop.See Also• FOR (legacy version) command• DO WHILE command• WHILE command• IF command• GOTO command• DO command• QUIT commandFOR<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 45


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsGOTOTransfers control.GOTO:pcGOTO:pc goargument,...G:pcG:pc goargument,...where goargument is:location:pcArgumentspclocationOptional — A postconditional expression.Optional — The point to which control will be transferred.DescriptionThe GOTO command has two forms:• Without an argument• With an argumentGOTO Without an ArgumentGOTO without an argument resumes normal program execution after <strong>Caché</strong> encounters aBREAK command in the currently executing code. You can use the argumentless GOTOonly from the programmer prompt.GOTO With an ArgumentGOTO with the argument location transfers control to the specified location. If you specifya postconditional expression on either the command or the argument, <strong>Caché</strong> transfers controlonly if the postconditional expression evaluates to TRUE (non-zero).You can use GOTO location from the programmer prompt to resume at a different location.You can specify a $CASE function as a GOTO command argument.46 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


ArgumentspcAn optional postconditional expression that can make the command conditional. If the postconditionalexpression is appended to the GOTO command keyword, <strong>Caché</strong> executes theGOTO command if the postconditional expression is true (evaluates to a non-zero numericvalue). <strong>Caché</strong> does not execute the GOTO command if the postconditional expression isfalse (evaluates to zero). If the postconditional expression is appended to an argument, <strong>Caché</strong>executes the argument if the postconditional expression is true (evaluates to a non-zeronumeric value). If the postconditional expression is false (evaluates to zero), <strong>Caché</strong> skips thatargument and evaluates the next argument (if there is one) or the next command. For furtherdetails, refer to Command Postconditional Expressions in Using <strong>Caché</strong> <strong>ObjectScript</strong>.locationThe point to which control will be transferred. It is required in routine code. It is optionalfrom the programmer prompt. You can specify location as a single value or as a commaseparatedlist of values (with postconditionals) and can take any of the following forms:label+offset specifies a line label within the current routine. The optional +offset is a nonnegativeinteger that specifies the number of lines after the label at which execution is to start.label+offset^routine specifies a line label within the named routine, which resides on disk.<strong>Caché</strong> loads the routine from disk and continues execution at the indicated label. The optional+offset is a nonnegative integer that specifies the number of lines after the label at whichexecution is to start.^routine specifies a routine that resides on disk. <strong>Caché</strong> loads the routine from disk and continuesexecution at the first line of executable code within the routine. If you specify a nonexistentroutine, <strong>Caché</strong> issues a error message. For more information, referto the $ZERROR special variable.You can also reference location as a variable containing any of the above forms. In this case,though, you must use name indirection. location cannot specify a subroutine label that isdefined with a formal parameter list or the name of a user-defined function or procedure. Ifyou specify a non-existent label, <strong>Caché</strong> issues a error message. For more information,refer to Indirection in Using <strong>Caché</strong> <strong>ObjectScript</strong>.ExampleGOTOIn the following example, the GOTO directs execution to one of three locations dependingon the user-supplied age value. The location is a subroutine label that is stored in variableloc and then referenced by means of name indirection (@loc).<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 47


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsmainloopSET age=""READ !,"What is your age? ",age QUIT:age=""IF age29)&(age59 {SET loc="Elder" }ELSE {WRITE "data input error"QUIT }GOTO @locQUITYoungWRITE !,"You're still young"QUITMidageWRITE !,"You're in your prime"QUITElderWRITE !,"You have a lifetime of wisdom to impart"QUITAs an alternative, you could omit the IF command and code the GOTO with a comma-separatedlist using postconditionals on the arguments, as follows:GOTO Young:age29)&(age59You might also code this example using a DO command to call the appropriate subroutinelocation. In this case, though, when <strong>Caché</strong> encounters a QUIT, it returns control to the commandfollowing the DO.NotesHow Control Is Transferred When QUIT is EncounteredUnlike the DO command, GOTO transfers control unconditionally. When <strong>Caché</strong> encountersa QUIT in a subroutine called by DO, it passes control to the command following the mostrecent DO.When <strong>Caché</strong> encounters a QUIT after a GOTO transfer, it does not return control to thecommand following the GOTO. If there was a preceding DO, it returns control to the commandfollowing the most recent DO. If there was no preceding DO, then it returns to theprogrammer prompt.In the following code sequence, the QUIT in C returns control to the WRITE command followingthe DO in A:48 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


GOTOtestgotoAWRITE !,"running A"DO BWRITE !,"back to A, all done"QUITBWRITE !,"running B"GOTO CWRITE !,"this line in B should never execute"QUITCWRITE !,"running C"QUITUsing GOTO with Code BlocksGOTO can be used to exit a code block, but not to enter a code block. If you use GOTOinside a FOR, IF, DO WHILE, or WHILE loop, you can go to a tag outside of all codeblocks, a tag within the current code block, or go from a nested code block to a tag in thecode block that encloses it. You cannot go from a code block to a tag within another codeblock, either an independent code block, or a code block nested within the current code block.For code examples, refer to the individual commands.A GOTO to a tag outside a code block terminates the loop. A GOTO to a tag within a codeblock does not terminate the loop. A GOTO from a nested code block to an enclosing codeblock terminates the inner (nested) loop, but not the outer loop.See Also• DO command• FOR command• IF command• DO WHILE command• WHILE command• BREAK command• QUIT command• $CASE function<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 49


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsHALTTerminates execution of the current process.HALT:pcH:pcArgumentpcOptional — A postconditional expression.DescriptionThe HALT command terminates execution of the current process. If a $HALT special variableis defined in the current context (or a prior context), issuing a HALT command invokes thehalt trap routine specified in $HALT, rather than terminating the current process. Typically,a halt trap routine performs some clean-up or reporting operations, then issues a secondHALT command to terminate execution.HALT has the same minimum abbreviation as the HANG command. HANG is distinguishedby its required hangtime argument.ArgumentspcAn optional postconditional expression that can make the command conditional. <strong>Caché</strong> executesthe HALT command if the postconditional expression is true (evaluates to a non-zeronumeric value). <strong>Caché</strong> does not execute the command if the postconditional expression isfalse (evaluates to zero). For further details, refer to Command Postconditional Expressionsin Using <strong>Caché</strong> <strong>ObjectScript</strong>.ExamplesIn the following example, HALT allows the user to end the current application and return tothe operating system. The system performs all necessary cleanup for the user. Note the useof the postconditional on the command.MainREAD !,"Do you really want to stop (Y or N)? ",ans QUIT:ans=""HALT:(ans["Y")!(ans="y")GOTO StartStartWRITE !,"This is the Start routine"QUIT50 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


HALTIn the following example, HALT invokes the halt trap routine specified in $HALT. In thiscase, it is the second HALT command that actually halts execution:MainNEW $ESTACKSET $HALT="OnHalt"WRITE !,"Main $ESTACK= ",$ESTACK // 0DO SubAWRITE !,"this should never display"QUITSubAWRITE !,"SubA $ESTACK= ",$ESTACK // 1HALT // invoke the OnHalt routineWRITE !,"this should never display"QUITOnHaltWRITE !,"OnHalt $ESTACK= ",$ESTACK // 0// clean-up and reporting operationsHALT // actually halt the current processQUITNotesEffects of HALTWhen HALT terminates a process and causes an exit from <strong>Caché</strong> the system automaticallyrelinquishes all locks and closes all devices owned by the process. This ensures that the haltedprocess does not leave behind locked variables or unreleased devices.HALT behaves the same whether it is encountered in routine code or entered from the programmermode prompt. In either case, you must log in again to return to <strong>Caché</strong> <strong>ObjectScript</strong>.HALT TrapsExecution of a HALT command is interrupted by a halt trap. Halt traps are established usingthe $HALT special variable.If a halt trap has been established for the current context frame, issuing a HALT commandinvokes the halt trap routine specified by $HALT. The HALT command itself is not executed.If a halt trap has been established for a lower context frame, a HALT command removescontext frames from the frame stack until the context frame with the halt trap is reached.HALT then invokes the halt trap routine specified by $HALT and ceases execution.See Also• $HALT special variable• Debugging in Using <strong>Caché</strong> <strong>ObjectScript</strong><strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 51


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsHANGSuspends execution for a specified number of seconds.HANG:pc hangargH:pc hangargwhere hangarg can be:hangtime,...ArgumentspchangtimeOptional — A postconditional expression.The amount of time to wait, in seconds.DescriptionHANG suspends the executing routine for the specified time period. If there are multiplearguments, <strong>Caché</strong> suspends execution for the sum of the arguments.HANG has the same minimum abbreviation (H) as the HALT command. HANG is distinguishedby its required hangtime argument.ArgumentspcAn optional postconditional expression. <strong>Caché</strong> executes the HANG command if the postconditionalexpression is true (evaluates to a non-zero numeric value). <strong>Caché</strong> does not executethe command if the postconditional expression is false (evaluates to zero). For further details,refer to Command Postconditional Expressions in Using <strong>Caché</strong> <strong>ObjectScript</strong>.hangtimeThe amount of time to wait, in seconds. This time can be expressed as any numeric expression.You can specify whole seconds as an integer, or fractional seconds using a decimal value.You can use exponentiation (**), arithmetic expressions, and other numeric operators. Youcan set hangtime to 0 (zero), in which case no hang is performed. Setting hangtime to a negativenumber is the same as setting it to 0.52 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


HANGNote:You cannot express hangtime as a decimal value on PowerPC/AIX 4.1 andRS/6000/AIX 4.1 based systems. On these systems, express hangtime in integerwhole seconds.You can specify hangtime as a comma-separated list of numeric expressions. The resultinghang is the sum of these expressions. Negative numbers are treated as zero. Therefore, ahangtime of 16,-15 would hang for 16 seconds.ExamplesThe following example suspends the process for 10 seconds:WRITE !,$ZTIME($PIECE($HOROLOG,",",2))HANG 10WRITE !,$ZTIME($PIECE($HOROLOG,",",2))The following example suspends the process for 1/2 second. $ZTIMESTAMP, unlike$HOROLOG, can return fractional seconds if the precision parameter of the $ZTIMEfunction is specified.WRITE !,$ZTIME($PIECE($ZTIMESTAMP,",",2),1,2)HANG .5WRITE !,$ZTIME($PIECE($ZTIMESTAMP,",",2),1,2)Returns values such as the following:14:34:19.7514:34:20.25NotesHow HANG Time is CalculatedThe HANG time is calculated using the system clock. If the clock is midway between secondswhen a HANG with 1 second or less is executed, the actual elapsed HANG time is only theremaining portion of the current clocktime second.HANG Compared with Timed READYou can use HANG to pause the routine while the user reads an output message. However,you can handle this type of pause more effectively with a timed READ command. A timedREAD allows the user to continue when ready, but a HANG does not because it is set to afixed duration.See Also• READ command<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 53


<strong>Caché</strong> <strong>ObjectScript</strong> Commands• $ZTIME function• $HOROLOG special variable• $ZTIMESTAMP special variableIFEvaluates an expression, then selects which block of code to execute based on the truth valueof the expression.IF expression1 {. . .}ELSEIF expression2 {. . .}ELSE {. . .}orI expression1 {. . .}ELSEIF expression2 {. . .}ELSE {. . .}Argumentsexpression1expression2A test condition for the IF clause. A single condition or acomma-separated list of conditions.A test condition for an ELSEIF clause. A single condition or acomma-separated list of conditions.DescriptionThis page describes the IF, ELSEIF, and ELSE command keywords, all of which are consideredto be component clauses of the IF command. An IF command consist of one IFclause, followed by any number of ELSEIF clauses, followed by one ELSE clause. The54 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


ELSEIF and ELSE clauses are optional, but it is a good programming practice to alwaysspecify an ELSE clause.IF is a block-oriented command. Each command keyword is followed by a block of codeenclosed in curly braces. Within these curly braces you can freely use line returns, indents,and blank spaces as desired.IFNote:An earlier, line-oriented version of the IF command may exist in legacy applications.This form of IF does not use curly braces or support the ELSEIF clause. These twoforms of IF are syntactically different and should not be combined. Thus, an IF ofone type should not be paired with an ELSE of the other type. The earlier line-orientedELSE could be abbreviated as E; the block-oriented ELSE keyword shouldnot be abbreviated.The IF command evaluates expression1 and, if expression1 is TRUE, it executes the blockof commands within the curly braces that follow it, and the IF command completes.If expression1 is FALSE, execution jumps to the next clause of the IF statement. It evaluatesthe first ELSEIF clause (if present). If expression2 in the ELSEIF clause is TRUE, theELSEIF code block is executed and the IF command completes. If expression2 is FALSE,the next ELSEIF clause is evaluated. Each successive ELSEIF clause is tested in the orderlisted until one of them evaluates TRUE, or all of them evaluate FALSE.If the IF clause and all ELSEIF clauses evaluate to FALSE, execution continues with theELSE clause. The ELSE clause block of code executes, and the IF command completes. Ifno ELSE clause is present, the IF command completes.Argumentsexpression1A test condition for the IF clause. It can take the form of a single expression or a commaseparatedlist of expressions. For an expression list, <strong>Caché</strong> evaluates the individual expressionsin left to right order. It stops evaluation if it encounters an expression that is FALSE. If allexpressions evaluate to TRUE, <strong>Caché</strong> executes the block of code associated with the clause.This block of code is enclosed in curly braces. If any expression evaluates to FALSE, <strong>Caché</strong>ignores any remaining expressions, and does not execute the block of code associated withthe clause. An IF clause list of expressions should not be broken into multiple lines.expression2A test condition for an ELSEIF clause. It can take the form of a single expression or a commaseparatedlist of expressions. It is evaluated the same way as expression1.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 55


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsNotesA block-oriented IF statement does not read or set the value of the $TEST special variable.If expression evaluates to TRUE, it executes the block of code within the curly braces,regardless of the setting of $TEST. If expression evaluates to FALSE, it continues executionafter the block of code enclosed in curly braces.An IF command can consist of an IF clause, one or more optional ELSEIF clauses, and anoptional ELSE clause. Only the block of code associated with one of these clauses can beexecuted. Successful execution of an IF clause or an ELSEIF clause completes the executionof the IF command.IF, ELSEIF, and ELSE clauses may use white space (line returns, indents, and blank spaces)freely. However, each IF and ELSEIF keyword and the first character of its expression mustbe on the same line, separated by one blank space. An expression can span multiple lines andcontain multiple blank spaces.IF with GOTO and QUITIf a GOTO or QUIT is encountered within an IF code block, program execution obeys thatstatement, with certain restrictions.A GOTO statement can jump to a location outside of the IF command, or within the codeblock of the current clause. A GOTO statement cannot jump into another code block: neithera code block that belongs to another clause of the current IF command, nor a code block thatbelongs to another IF, FOR, DO WHILE, or WHILE command.A QUIT command breaks out of the IF code block. However, if the IF code block is nestedwithin a loop structure, such as a FOR loop, the QUIT breaks out of that loop structure aswell.ExamplesIn the following example, the IF command is used to categorize responders into one of threegroups for subsequent processing. The three groups are females aged 24 or less, males aged24 or less, and either females or males aged 25 or more. In this example, the test expressionsuse the Binary Contains operator ( [ ). (See Operators in Using <strong>Caché</strong> <strong>ObjectScript</strong>.)56 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


JOBMainloopNEW sex,ageREAD !,"What is your sex? (M or F): ",!,sex QUIT:sex=""READ !,"What is your age? ",!,age QUIT:age=""IF "Ff"[sex,age


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsLocal Jobs:routine(routine-params):(process-params):timeoutroutine(routine-params)[joblocation]:(process-params):timeoutroutine(routine-params)|joblocation|:(process-params):timeout##class(classname).methodname(args):(process-params):timeout$ZOBJCLASSMETHOD(classname,methodname,args):(process-params):timeoutRemote Jobs:routine[joblocation]:(process-params)routine|joblocation|:(process-params)Arguments58 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


JOBpcroutineroutine-paramsclassname.methodname(args)process-paramstimeoutjoblocationOptional — A postconditional expression.The routine to be executed by the process created by JOB.Optional — A comma-separated list of parameters to passto the routine.These parameters can be values, expressions,or existing local variable names. If specified, the enclosingparentheses are required. Routine parameters can only bepassed to local jobs.The class method to be executed by the process created byJOB. Only class methods can be jobbed. The classnamecannot be $SYSTEM; it can be %SYSTEM. You cannotspecify the classname as a class reference (oref), you mustspecify a class name. A comma-separated list of argsarguments is optional; the enclosing parentheses arerequired. For further details on using$ZOBJCLASSMETHOD, refer to the Technical Article Usingthe <strong>Caché</strong> $ZOBJxxx Intrinsic Functions.Optional — A colon-separated list of positional parametersused to set various elements in the job's environment. Toindicate a positional parameter is missing, its colon must bepresent, though trailing colons may be omitted. Theprocess-params list is enclosed in parentheses and theparenthesized list preceded by a colon.Optional — The number of seconds to wait for the jobbedprocess to start. The preceding colon is required. Timeoutcan only be specified for local jobs.Optional — An explicit or implied namespace used to specifythe system and directory on which to run a remote job. Animplied namespace is a directory path or OpenVMS filespecification preceded by two caret characters: "^^dir".Enclose joblocation in either square brackets or vertical bars.You cannot specify a joblocation when jobbing a classmethod. If joblocation specifies a remote system, you cannotspecify routine-params or timeout.DescriptionJOB creates a separate process known as a job, jobbed process, or batch job. The createdprocess runs in the background, independently of the current process, usually without user<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 59


<strong>Caché</strong> <strong>ObjectScript</strong> Commandsinteraction. A jobbed process inherits all system defaults, except what is explicitly specifiedin the JOB command.By contrast, a routine invoked with the DO command runs in the foreground as part of thecurrent process.JOB can create a local process on your local system, or it can invoke the creation of a remoteprocess on another system. For more on remote jobs, see Starting Remote Jobs.ArgumentspcAn optional postconditional expression. <strong>Caché</strong> executes JOB if the postconditional expressionis true (evaluates to a non-zero numeric value). <strong>Caché</strong> does not execute the command if thepostconditional expression is false (evaluates to zero). For further details, refer to CommandPostconditional Expressions in Using <strong>Caché</strong> <strong>ObjectScript</strong>.routineThe process to be started. It can take any of the following forms:Process Specificationlabel^routinelabel^routinelabel+offsetlabel+offset^routineDescriptionSpecifies a line label within the current routine.Specifies a routine that resides on disk. <strong>Caché</strong> loadsthe routine from disk and starts execution at the firstline of executable code within the routine.Specifies a line label within the named routine,which resides on disk. <strong>Caché</strong> loads the routine fromdisk and starts execution at the indicated label.Specifies an offset of a specified number of linesfrom the label. Use of offsets can cause problemswith program maintenance, and is discouraged.If you specify a non-existent label, <strong>Caché</strong> issues a error. If you specify a nonexistentroutine, <strong>Caché</strong> issues a error. For further details on these errors,refer to the $ZERROR special variable.routine-paramsA comma-separated list of values, expressions, or existing local variable names. The enclosingparentheses are required. This list is known as the actual parameter list. The routine must60 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


have a formal parameter list with the same or a greater number of parameters. If you specifyextra actual parameters, <strong>Caché</strong> issues a error. Note that if the invokedroutine contains a formal parameter list, you must specify the enclosing parentheses, even ifyou do not pass any parameters.You can pass routine parameters only by value, which means that you cannot pass arrays.This is different from the DO command where you can pass parameters by value and by reference.A special consequence of this restriction is you cannot pass arrays with the JOBcommand, since they are passed only by reference.When the routine starts, <strong>Caché</strong> evaluates any expressions and maps the value of eachparameter in the actual list, by position, to the corresponding variable in the formal list. Ifthere are more variables in the formal list than there are parameters in the actual list, <strong>Caché</strong>leaves the extra variables undefined.Routine parameters can only be passed to local processes. You cannot specify routineparameters when creating a remote job. See Starting Remote Jobs.process-paramsA colon-separated list of positional parameters used to set various elements in the job'senvironment. The preceding colon and enclosing parentheses are required. You are allowedyou specify up to four positional parameters for process-params. The four parameters are:(nspace:switch:principal-input:principal-output)Since the parameters are positional, you must specify them in the order shown. If you omita parameter that precedes a specified parameter, you must include a colon as a placeholderfor it.The following table describes the four process parameters.JOBParameternspaceDescriptionThe default namespace of the process.The specified routineis drawn from this namespace. If you omit nspace, yourcurrent default namespace is the default namespace of thejobbing process. An invalid namespace may prevent the jobfrom starting. A remote job cannot specify namespace as aprocess parameter; see Starting Remote Jobs for details.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 61


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsParameterswitchprincipal-inputDescriptionTwo values: An integer value that is interpreted as a bit maskthat can represent zero or more of the following flags:1 - Pass the symbol table to the spawned job.2 - OpenVMS and UNIX: Do not use a JOB server.4 - Pass an open TCP/IP socket to the spawned job.8 - Establish the process-specific window for two-digit yearsof the spawned job to be the system-wide default slidingwindow definition. Otherwise, the spawned job inherits thesliding window definition of the process issuing the JOBcommand.An additional numeric value that specifies a partition size forthe JOBbed child process. Values (in kilobytes) can rangefrom 128 through 16384 in multiples of 32. See "SpecifyingChild Process Partition Size” for more information.switch can be the sum of any combination of these masks.For example, a switch value of 13 (1+4+8) passes the symboltable (1), passes the open TCP/IP socket (4), and establishesa process-specific window for two-digit years that is the system-widedefault (8).Principal input device for the process.UNIX: See principal-output for default.VMS : The default is your current input device. If your currentinput device is your principal device and you log off, thejobbed process will be unable to issue JOB commands tostart new processes.VMS: If you do not specify a principal input and output device,the JOB command may not know which device to open and,as a result, does not start the process.To avoid this situation,you should always specify a principal input and output device.If you do not require any I/O, specify the null device: NL:.62 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


JOBParameterprincipal-outputDescriptionPrincipal output device for the process. The default is thedevice you specify for principal-input.UNIX : If you do not specify either device, the process usesthe default principal device for processes started with theJOB command, which is /dev/null. To make the principalinput or output device default to your current device insteadof /dev/null, use the $ZUTIL(69,4) function.VMS: If you do not specify either device, the process usesyour current principal input and output devices.VMS: If the jobbed process is using your current device andyou log off, the jobbed process will be unable to issue JOBcommands to start new processes. If you do not require anyI/O, specify the null device: NL:timeoutThe number of seconds to wait for the jobbed process to start before timing out and abortingthe job. The preceding colon is required. You must specify timeout as an integer value orexpression. If a jobbed process times out, <strong>Caché</strong> aborts the process and sets $TEST to FALSE(0). Execution then proceeds to the next command in the calling routine; no error messageis issued.Timeout can only be specified for a local process.ExamplesThis example starts the monitor routine in the background. If the process does not start in 20seconds, <strong>Caché</strong> sets $TEST to FALSE (0).JOB ^monitor::20WRITE $TESTThis example starts execution of the monitor routine at the line label named Disp.JOB Disp^monitorThe following example starts the Add routine, passing it the value in variable num1, the value8, and the value resulting from the expression a+2. The Add routine must contain a formalparameter list that includes at least three parameters.JOB ^Add(num1,8,a+2)<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 63


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsThe following example starts the Add routine, which has a formal parameter list, but passesno parameters. In this case, the Add routine must include code to assign default values to itsformal parameters, since they receive no values from the calling routine.JOB ^Add()The following example creates a process running your current routine at label AA. The processparameters pass your current symbol table to the routine. If running on OpenVMS or UNIXit can use a JOB Server.JOB AA:("":1)The following OpenVMS command creates a process running the ^REPORT routine inimplied namespace, the directory [USER.TEST]. An implied namespace is a directory pathor OpenVMS file specification preceded by two caret characters: "^^dir". Because ^REPORTdoes not require input from the principal device, the null device is specified as principal input.The file report.L is the principal output device.JOB ^REPORT:("^^[USER.TEST]"::"NL:":"report.L")This following command passes the routine parameters VAL1 and the string "DR." to theroutine ^PROG, starting at entry point ABC, in the current namespace. The routine expectstwo arguments. <strong>Caché</strong> does not pass the current symbol table to this job, it will use a JOBServer if possible, and use tta5: as principal input and output device.JOB ABC^PROG(VAL1,"DR."):(:0:"tta5:")The following examples show the jobbing of a class method, with a timeout of ten seconds.They use tta5: as principal input and output device.JOB ##class(MyClass).New():(:0:"tta5:"):10JOB $ZOBJCLASSMETHOD(MyClass,New):(:0:"tta5:"):10Notes<strong>Caché</strong> Assigns Job Numbers and Memory PartitionsAfter you start a jobbed process, <strong>Caché</strong> allocates a separate memory partition for it and assignsit a unique job number (also referred to as a Process ID or PID). The job number is stored inthe $JOB special variable. The status of the job (including whether or not it was started bya JOB command) is stored in the $ZJOB special variable.Since jobbed processes have separate memory partitions, they do not share a common localvariable environment with the process that created them or with each other. When you start64 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


a jobbed process, you can use parameter passing (routine–params) to pass values from thecurrent process to the jobbed process.If the JOB command fails, it is usually because:• There are no free partitions.• There is not enough memory to create a partition with the characteristics specified byprocess—params.Communicating Between JobsJOBParameter passing by value can occur in only one direction and only at job start up. For processesto communicate with each other, they must use mutually agreed upon global variables.Such variables are commonly known as scratch globals because their sole purpose is to allowprocesses to exchange information among themselves.Note:You can pass all local variables in the current process to the invoked process byspecifying a special process parameter.Processes can also communicate through the IPC (Interprocess Communication)devices (device numbers 224 through 255) or, on UNIX operating systems, throughUNIX pipes.Establishing Device Ownership<strong>Caché</strong> assumes that the invoked routine includes code (that is, OPEN and USE commands)to handle device ownership for the new process. The default device is the null device.<strong>Caché</strong> does not assign a default device to any process other than the process started at signin.Setting Job PriorityThe %PRIO utility allows you to control the priority at which a jobbed process runs. Forexample, with a priority of HIGH, a jobbed process competes on an equal basis with interactiveprocesses for CPU resources.<strong>Caché</strong> also allows you to establish default priorities for jobbed processes.Using the JOB Command in a Raw Partition (UNIX)You can use the JOB command in a raw partition in either of two ways:• Issue the JOB command while in the raw partition.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 65


JOBProcess parameters are optional. However, a remote job cannot specify the first processparameter (nspace) because this would conflict with the joblocation parameter. Therefore,only the second, third, and fourth process parameters can be specified, and the missing nspaceparameter must be indicated by a colon.joblocationA specification of the location of the job. The enclosing squarebrackets or vertical bars are required.The action <strong>Caché</strong> takes depends on the job location syntax you are using.joblocation Syntax["namespace"]["dir","sys"]["^sys^dir"]["^^dir"]["dir",""]Result<strong>Caché</strong> checks whether this explicit namespace has its defaultdataset on the local system or on a remote system. If the defaultdataset is on the local system, <strong>Caché</strong> starts the job using theparameters you specify. If the default dataset is on a remotesystem, <strong>Caché</strong> starts the remote job in the directory of thenamespace's default dataset.<strong>Caché</strong> converts this location to the implied namespace form["^sys^dir"].The job runs in the specified directory on the specified remotesystem. <strong>Caché</strong> does not allow any routine parameters or timeoutspecification.The job runs in the specified directory (implied namespace) asa local job on the current system using the parameters youspecify. An implied namespace is a directory path or OpenVMSfile specification preceded by two caret characters: "^^dir".<strong>Caché</strong> issues a error.Global Mapping with Remote Jobs (Windows)<strong>Caché</strong> does not provide global mapping for remote jobs, whether or not global mapping hasbeen defined on the requesting system. To avoid the lack of global mapping, use extendedreferences with your global specifications that point to the location of any globals not in thatnamespace. If the namespace you specify in an extended reference is not defined on the systemyou specify, you receive a error. Namespaces and the syntax for extendedglobal references are described in Global Structure in Using <strong>Caché</strong> Multi-Dimensional Storage.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 67


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsRemote Job Success ConfirmationYou do not receive a direct message on the requesting system indicating whether job initiationwas successful on the target system. However, <strong>Caché</strong> does write a message indicating jobinitiation success or failure on the console log of the target system.Configuration File on Remote SystemsYou must configure the ability to receive remote job requests on any system that will receivethem.On the receiving system, go to the System Management Portal, select System Configuration,select Advanced Settings, on the pull-down Category list select Connectivity. Select NetworkRemoteJobs.When “true” , incoming remote job requests via DCP or ECP will behonored on this server. The default is “true” .The license on the remote system must support enough users to run remotely initiated jobs.Using the $ZCHILD and $ZPARENT Special Variables$ZPARENT contains the PID (process ID) of the process which jobbed the current process,or 0 if the current process was not created through the JOB command.$ZCHILD contains the PID of the last process created by the JOB command, whether or notthe attempt was successful.Using JOB ServersJOB Servers are <strong>Caché</strong> processes that wait to process job requests. Jobbed processes thatattach to JOB Servers avoid the added overhead of having to create a new process. Whenevera user issues a JOB command with the switch parameter set to use JOB Server if available,<strong>Caché</strong> checks to see if any JOB Servers are available to handle it. If not, it will create a process.If there is a free JOB Server, the job attaches to that JOB Server.When a job halts while running in a JOB Server, the JOB Server hibernates until it receivesanother job request. A jobbed process not running in a JOB Server exits and the process isdeleted.There are some unavoidable differences between the JOB Server environment and the jobbedprocess environment, which may be a security concern with jobbed processes executing inJOB Servers. A jobbed process normally takes on the security attributes of the process thatissued the JOB command at both the <strong>Caché</strong> and the OpenVMS level.However, a jobbed process that runs in a JOB Server uses the UIC of the JOB Server at theOpenVMS level. The UIC of a JOB Server is the same as the UIC of the <strong>Caché</strong> systemmanager, usually [1,4]. This means that when the JOB Server accesses OpenVMS RMS files68 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


or devices, OpenVMS grants maximum access. This feature does not concern you if you run<strong>Caché</strong> in an application environment, but does apply if you use <strong>Caché</strong> in Programmer mode.Input and Output DevicesOnly one process can own a device at a time. Under OpenVMS it is impossible to close yourprincipal input or output device. This means that a job executing in a JOB Server is unableto perform input or output to your principal I/O devices even though you may close device0.Therefore, if you expect a JOB Server to perform input, you must specify:• An alternative input device for it• The null device for an output device (if you do not want to see the output)Failure to follow these guidelines may cause the job executing in the JOB Server to hang ifit needs to do any input or output from/to your principal I/O devices. You may find that frequentlyjob output does get through to your terminal (for example, if you have the SHAREprivilege), but typically it will not.Troubleshooting Jobs That Won't ExecuteIf your job does not start, check your I/O specification. Your job will not start if <strong>Caché</strong> cannotopen the devices you requested. Note that the null device (NL: on OpenVMS and /dev/nullon UNIX) is always available.If your job starts but then halts immediately, make sure you have sufficient swap space. Yourjob receives an error if you do not have enough swap space.If your job does not start, make sure that you have used the correct namespace in the JOBcommand. You can test whether a namespace is defined by using $ZUTIL(90,10).If the JOB command is still not working, try the following:• Execute the routine with the DO command.• OpenVMS: Jobbed processes all execute the system login file, SYS$MANAGER:SYLO-GIN.COM. Check to make sure it contains no statements that will cause a jobbed processto hang.• OpenVMS: Jobbed processes that do not run in JOB Servers also execute yourLOGIN.COM file. Check this file as well.• Make sure you are not exceeding the number of processes for which you are licensed inOpenVMS or <strong>Caché</strong>.JOB<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 69


<strong>Caché</strong> <strong>ObjectScript</strong> Commands• If there is a timeout parameter in your JOB command, check whether the speed of yoursystem is using up the timeout period.JOB Command CompletionA jobbed process continues to completion even if the process that created it logs off beforethat completion.JOB Command with TCP DevicesYou can use the JOB command to implement a TCP concurrent server. A TCP concurrentserver allows multiple clients to be served simultaneously. In this mode a client does not haveto wait for the server to finish serving other clients. Instead, each time a client requests theserver, it spawns a separate subjob for that client which remains open as long as the clientneeds it. As soon as this subjob has been spawned (indicated by the return of the JOB command),another client may request service and the server will create a subjob for that clientas well.Client/Server Connections in the Non-Concurrent and Concurrent ModesA concurrent server uses the JOB command with the concurrent server bit (the bit with value4) turned on. Then the JOB command passes to the spawned process the TCP device in the70 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


principal–input and principal–output process parameters. Whenever you include bit 4 inswitch, you must specify the TCP device in both principal–input and principal–output processparameters. You must use the same device for both principal–input and principal–output.It is important to note that the JOB command will pass the TCP socket to the jobbed processif the concurrent bit is set. This capability may be combined with other featured of the JOBcommand by adding the appropriate bit code for each additional feature to 4. For example,when switch includes the bit with value 1, the symbol table is passed. To turn on concurrencyand pass the symbol table, switch would have the value 5.Before you issue the JOB command, the device you specify for principal–input andprincipal–output must:• Be open• Be listening on a TCP port• Have accepted an incoming connectionAfter the JOB command, the device in the spawning process is still listening on the TCPport, but no longer has an active connection. The application should check the $ZA specialvariable after issuing the JOB command to make sure that the CONNECTED bit in the stateof the TCP device was reset.The spawned process starts at the designated entry point using the specified TCP device asboth its principal–input and principal–output device. The TCP device has the same name inthe child process as in the parent process. The TCP device has one attached socket. Theinherited TCP device is in S (stream) mode. However, the child process can change the modewith a USE command. We recommend that the server open TCP device in the "A" (accept)mode.TCP device in the spawned process is in a connected state: the same state the device wouldreceive after it is opened from a client. The spawned process can use the TCP device withUSE 0 or USE $PRINCIPAL. It can also use the TCP device implicitly (as shown in the followingexample).The following example shows a very simple concurrent server that spawns off a child jobwhenever it detects a connection from a client.JOB<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 71


<strong>Caché</strong> <strong>ObjectScript</strong> Commandsserver ;SET io="|TCP|1"SET ^serverport=7001OPEN io:(:^serverport:"MA"):200IF $TEST=0 {WRITE !,"Cannot open server port"QUIT }ELSE { WRITE !,"Server port opened" }loopUSE io READ x ; Read for acceptUSE 0 WRITE !,"Accepted connection"JOB child:(:5:io:io) ;Concurrent server bit is onGOTO loopchild ;WRITE $JOB,! ;Send job id on TCP device to be read by clientQUITclient ;SET io="|TCP|2"SET host="127.0.0.1"OPEN io:(host:^serverport:"M"):200 ;Connect to serverIF $TEST=0 {WRITE !,"Cannot open connection"QUIT }ELSE { WRITE !,"Client connection opened" }USE io READ x#3:200 ;Reads from subjobELSE WRITE !,"No message from child" CLOSE io QUITUSE 0 WRITE !,"Child is on job ",XECUTECLOSE ioQUITThe child uses the inherited TCP connection to pass its job ID (in this case assumed to be 3characters) back to the client, after which the child process exits. The client opens up a connectionwith the server and reads the child's job ID on the open connection. In this example,the value "127.0.0.1" for the variable "host" indicates a loopback connection to the local hostmachine. You can set up a client on a different machine from the server if "host" is set to theserver's IP address or name.In principle, the child and client can conduct extended communication, and multiple clientscan be talking concurrently with their respective children of the server.Specifying Child Process Partition Size<strong>Caché</strong> supports specifying the partition size of the jobbed child process. By default, the jobbedprocess has a partition size equal to the system-wide default partition size in effect when youexecute JOB, regardless of the partition size of the parent process from which you issue JOB.The system-wide partition size increases dynamically to a maximum of 16mb.You can specify the partition size (in kilobytes) of the jobbed process in the second processparameter of the JOB command. The value you use must be a multiple of 32 and must rangefrom 128 through 16384.You can optionally specify the partition-size process parameter value in combination withother process information that you would normally put in the second process parameter ofJOB. Consider the following JOB command:72 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


KILLJOB ^routine(:544+1)This command specifies that the symbol table of the jobbing process should be passed to thejobbed process and that the jobbed process should have a partition size of 544K. Althoughyou can specify this second parameter, which passes two values (544 and 1) as 545, 544 +1is clearer and has exactly the same effect.See Also• ^$JOB structured system variable• $JOB special variable• $TEST special variable• $ZJOB special variable• $ZCHILD special variable• $ZPARENT special variable• The Spool Device in <strong>Caché</strong> I/O Device Guide• Using the System Management Portal to monitor and control processes in Managing<strong>Caché</strong> in <strong>Caché</strong> System Administration GuideKILLDeletes variables.KILL:pc killargument,...K:pc killargument,...where killargument can be:variable,...(variable,...)ArgumentspcvariableOptional — A postconditional expression.Optional — A variable name or comma-separated list of variable names.Without parentheses: the variable(s) to be deleted. With parentheses:the variable(s) to be kept.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 73


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsDescriptionThere are three forms of the KILL command:• KILL without an argument (argumentless KILL.)• KILL with a variable list (inclusive KILL.)• KILL with a variable list enclosed in parentheses (exclusive KILL.)The KILL command without an argument deletes all local variables. It does not delete processprivateglobals, globals, or user-defined special variables.KILL with a variable or comma-separated variable list as an argument:KILL variable,...is called an inclusive KILL. It deletes only the variable(s) you specify in the argument. Thevariables can be local variables, process-private variables, or globals. They do not have tobe actual defined variables, but they must be valid variable names. You cannot kill a specialvariable, even if its value is user-specified. Attempting to do so generates a error.KILL with a variable or comma-separated variable list enclosed in parentheses as an argument:KILL (variable,...)is called an exclusive KILL. It deletes all local variables except those you specify in theargument. The variables you specify can only be local variables. The local variables youspecify do not have to be actual defined variables, but they must be valid local variable names.Note:KILL can delete local variables created by <strong>Caché</strong> objects. Therefore, do not useeither argumentless KILL or exclusive KILL in any context where they might affectsystem structures (such as %objTX currently used in %Save) or system objects (suchas the stored procedure context object). In most programming contexts, these formsof KILL should be avoided.Using KILL to delete variables frees up local variable storage space. To determine or set themaximum local variable storage space (in kilobytes), use the $ZSTORAGE special variable.To determine the currently available local variable storage space (in bytes), use the $STOR-AGE special variable.74 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


ArgumentspcAn optional postconditional expression. <strong>Caché</strong> executes the KILL command if the postconditionalexpression is true (evaluates to a non-zero numeric value). <strong>Caché</strong> does not executethe command if the postconditional expression is false (evaluates to zero). For further details,refer to Command Postconditional Expressions in Using <strong>Caché</strong> <strong>ObjectScript</strong>.variableIf not enclosed in parentheses: the variable(s) to be deleted by the KILL command. variablecan be a single variable or a comma-separated list of variables.If enclosed in parentheses: the local variable(s) to be kept by the KILL command; the KILLcommand deletes all other local variables. variable can be a single variable or a commaseparatedlist of variables.ExamplesIn the following example, an inclusive KILL deletes local variables a, b, and c, and thedeletes the process-private global ^||ppglob and all of its subscripts. No other variables areaffected.SET ^||ppglob(1)="fruit"SET ^||ppglob(1,1)="apples"SET ^||ppglob(1,2)="oranges"SET a=1,b=2,c=3,d=4,e=5KILL a,b,c,^||ppglobWRITE "d=",d,!,"e=",eIn the following example, an exclusive KILL deletes all local variables except for variablesd and e.SET a=1,b=2,c=3,d=4,e=5KILL (d,e)WRITE "d=",d,!,"e=",eNote that because an exclusive KILL deletes object variables, the above program works froma terminal session, but does not work within an object method.The following example, an inclusive KILL deletes two process-private globals and anexclusive KILL deletes all local variables except for variables d and e.SET ^||a="one",^||b="two"SET a=1,b=2,c=3,d=4,e=5KILL ^||a,^||b,(d,e)WRITE "d=",d,!,"e=",eKILL<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 75


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsNotesKILL and ObjectsObject variables (OREFs) automatically maintain a reference count — the number of itemscurrently referring to an object. Whenever you SET a variable or object property to refer toan object, <strong>Caché</strong> increments the object's reference count. When you KILL a variable, <strong>Caché</strong>decrements the corresponding object reference count. When this reference count goes to 0,the object is automatically destroyed; that is, <strong>Caché</strong> removes it from memory. The objectreference count is also decremented when a variable is SET to a new value, or when thevariable goes out of scope.In the case of a persistent object, call the %Save() method before removing the object frommemory if you wish to preserve changes to the object. The %Delete() method deletes thestored version of a <strong>Caché</strong> object; it does not remove the in-memory version of that object.Prior to <strong>Caché</strong> version 5.0, the %Close() method could be used to remove objects frommemory. With <strong>Caché</strong> version 5.0 and subsequent, the %Close() method performs no operationand always returns successful completion. Do not use %Close() when writing new code.Inclusive KILLAn inclusive KILL deletes only those variables explicitly named. The list can include localvariables, process-private globals, and globals—either subscripted or unsubscripted. Theinclusive KILL is the only way to delete global variables.Exclusive KILLAn exclusive KILL deletes all local variables except those that you explicitly name. Listednames are separated by commas. The enclosing parentheses are required.The exception list can contain only local unsubscripted variable names. For example, if youhave a local variable array named fruitbasket, which has several subscript nodes, you canpreserve the entire local variable array by specifying KILL (fruitbasket); you cannot useexclusive KILL to selectively preserve individual subscript nodes. An exclusive kill listcannot specify a process-private global, a global, or a special variable; attempting to do soresults in a error. Local variables not named in the exception list are deleted;subsequent references to such variables generate an error. The exclusiveKILL has no effect on process-private globals, globals, and special variables. However, itdoes delete local variables created by system objects.Using KILL with Arrays• To delete a local variable array, use any form of KILL.76 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


• To delete a selected node within a local variable array, you must use an inclusive KILL.• To delete a global variable array, you must use an inclusive KILL.• To delete a selected node within a global variable array, you must use an inclusive KILL.To delete an array, simply supply its name to an inclusive KILL. For example, the followingcommand deletes global array ^fruitbasket and all of its subordinate nodes.SET ^fruitbasket(1)="fruit"SET ^fruitbasket(1,1)="apples"SET ^fruitbasket(1,2)="oranges"WRITE !,^fruitbasket(1)," contains ",^fruitbasket(1,1)," and ",^fruitbasket(1,2)KILL ^fruitbasketWRITE !,"Try to display array values"WRITE !,^fruitbasket(1),!,^fruitbasket(1,1),!,^fruitbasket(1,2)QUITTo delete an array node, supply the appropriate subscript. For example, the following KILLcommand deletes the node at subscript 1,2.SET ^fruitbasket(1)="fruit"SET ^fruitbasket(1,1)="apples"SET ^fruitbasket(1,2)="oranges"SET ^fruitbasket(1,2,1)="navel"SET ^fruitbasket(1,2,2)="mandarin"WRITE ^fruitbasket(1)," contains ",^fruitbasket(1,1)," and ",^fruitbasket(1,2),!WRITE ^fruitbasket(1,2)," contains ",^fruitbasket(1,2,1)," and ",^fruitbasket(1,2,2),!KILL ^fruitbasket(1,2)WRITE "1st level node: ",^fruitbasket(1),!WRITE "2nd level node: ",^fruitbasket(1,1),!WRITE "Deleted 2nd level node: ",^fruitbasket(1,2),!WRITE "3rd level node under deleted 2nd: ",^fruitbasket(1,2,1),!QUITWhen you delete an array node, you automatically delete all nodes subordinate to that nodeand any immediately preceding node that contains only a pointer to the deleted node. If adeleted node is the only node in its array, the array itself is deleted along with the node.To delete multiple local variable arrays, you can use either the inclusive form or exclusiveform of KILL, as described above. For example, the following command removes all localarrays except array1 and array2.KILL (array1,array2)To delete multiple array nodes, you can use only the inclusive form of KILL. For example,the following command removes the three specified nodes, deleting one node from each array.KILL array1(2,4),array2(3,2),array3(1,7)KILL<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 77


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsThe nodes can be in the same or different arrays.You may delete a specified local or global array node by using the ZKILL command. UnlikeKILL, ZKILL does not delete all nodes subordinate to the specified node.Effects of KILL with Parameter PassingWith parameter passing, values are passed to a user-defined function or to a subroutine calledwith the DO command. The values to be passed to the user-defined function or subroutineare supplied in a comma separated list called the actual parameter list. Each value suppliedis mapped, by position, into a corresponding variable in the formal parameter list defined forthe user-defined function or subroutine.Depending on how the actual parameter list is specified, parameter passing can occur in eitherof two ways: by value or by reference. For more information on these two types of parameterpassing, see DO with Parameter Passing.Killing a variable in the formal parameter list has different results depending on whetherpassing by value or passing by reference is in effect.If you are using passing by value, killing a variable in the formal list has no effect outsidethe context of the invoked function or subroutine. This is because <strong>Caché</strong> automatically savesthe current value of the corresponding actual variable when the function or subroutine isinvoked. It then automatically restores the saved value on exit from the function or subroutine.If you are passing by reference, killing a variable in the formal list also kills the correspondingactual variable. When the function or subroutine terminates, the actual variable will no longerexist. In the following example, the KILL in Subrt1 deletes both the formal variable x andthe actual variable a.TestSET a=17WRITE !,"Before: a=",aDO Subrt1(a)WRITE !,"After: a=",aQUITSubrt1(x)WRITE !,"x=",xKILL xQUITAs a general rule, you should not KILL variables specified in a formal parameter list. When<strong>Caché</strong> encounters a function or subroutine that uses parameter passing (whether by value orby reference), it implicitly executes a NEW command for each variable in the formal list.When it exits from the function or subroutine, it implicitly executes a KILL command foreach variable in the formal list. In the case of a formal variable that uses passing by reference,78 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


it updates the corresponding actual variable (to reflect changes made to the formal variable)before executing the KILL.See Also• ZKILL command• $ZUTIL(68,28) Control Root (Unsubscripted) Node Kills function• $STORAGE special variableLOCKLOCKEnables processes to request control and release control of data resources.LOCK:pcL:pcLOCK:pc oper(lockname#locktype,...):timeout,...L:pc oper(lockname#locktype,...):timeout,...ArgumentspcoperlocknamelocktypetimeoutOptional — A postconditional expression.Optional — The lock operation indicator (a + or – sign) to apply or removea lock.The resource(s) to be locked or unlocked. Must be a valid identifier,following the same naming conventions as local variables or globals.Optional — A letter code specifying the type of lock to apply or remove.Optional — The time to wait before the transaction times out. Specifiedas an integer number of seconds.DescriptionThere are two basic forms of the LOCK command:• Without an argument• With an argument<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 79


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsLOCK Without an ArgumentThe argumentless LOCK removes all locks currently held by the process. This includes bothsimple and incremental locks. It also includes all accumulated incremental locks. For example,if there are three incremental locks on a given lock name, <strong>Caché</strong> removes all three locks andresets the lock name's entry in the lock table to zero. Argumentless LOCK removes bothshared and exclusive locks.Argumentless LOCK is used to explicitly release all existing locks. Completion of a processalso releases all locks held by that process. Completion of a transaction releases all locks heldwithin that transaction.LOCK With an ArgumentLOCK with an argument specifies one or more lock names on which to perform locking andunlocking operations. The effect of the LOCK depends on the argument you use.• LOCK lockname sets a simple lock on the specified lock name and unlocks all previouslocks.• LOCK +lockname sets an incremental lock on the specified lock name.• LOCK -lockname performs an unlock operation. Unlocking decrements a lock countfor the specified lock name; when this lock count decrements to zero, the lock is unlocked.You can specify multiple locks with a single LOCK command in either of two ways:• By enclosing a comma-separated list of lock names in parentheses, you can perform theselocking operations on multiple locks as a single operation. For example:LOCK +(var1,var2):10All lock operations in a parentheses-enclosed list are governed by a single timeout argument:either all of the locks are applied or none of them are applied.• By specifying multiple lock arguments without parentheses as a comma-separated list,you can specify multiple independent lock operations, each of which can have its owntimeout. (This is functionally identical to specifying a separate LOCK command for eachlock.) For example, a single LOCK command could perform a simple lock and anincremental lock, each with its own timeout:LOCK var1:10,+var2:15However, if you use multiple lock arguments, be aware that the simple lock operationunlocks all prior locks, including locks set by an earlier part of the same LOCK command.80 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


LOCKViewing the Current LocksTo view a list of the current locks for your process, go to the <strong>Caché</strong> System ManagementPortal and select Locks. The Locks window displays a list of processes with the current locksfor each. Separate lock counts are maintained for Exclusive locks and Shared locks. You mayneed to use the Refresh option to view the most current list of locks.You can delete locks by clicking “Remove”, “Remove All Locks for Process”, or “Removeall Locks for Server” (at top of window). This gives you the option of deleting that lock,deleting all locks for the process, or deleting all locks for the server.ArgumentspcAn optional postconditional expression that can make the command conditional. <strong>Caché</strong> executesthe LOCK command if the postconditional expression is true (evaluates to a non-zeronumeric value). <strong>Caché</strong> does not execute the command if the postconditional expression isfalse (evaluates to zero). For further details, refer to Command Postconditional Expressionsin Using <strong>Caché</strong> <strong>ObjectScript</strong>.operThe lock operation indicator is used to apply or remove a lock. In a comma-separated list oflock names, each lock name must have its own lock operation indicator. The lock operationindicator can be one of the following values:No characterPlus sign (+)Minus sign (-)Apply a simple lock to a lock name and unlock all prior locks.Apply an incremental lock to a lock name.Remove a lock from a lock name.If the lock name has a lock count of 1, remove the lock from the lock table. If the lock namehas a lock count of more than 1, remove one of its incremental locks (decrement the lockcount). By default, this removes exclusive locks. To remove a shared lock, you must specifythe lock type specifying a shared lock. If your LOCK command contains multiple commaseparatedlock argument syntactical units, each lock argument can have its own lock operationindicator. <strong>Caché</strong> parses this as multiple LOCK commands; therefore a simple lock will deleteany locks created by a lock argument specified earlier in the command.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 81


<strong>Caché</strong> <strong>ObjectScript</strong> CommandslocknameThe name of a single data resource, or a comma-separated list of data resources, to be lockedor unlocked. A lockname is a name representing a data resource; it is not the variable itself.That is, your program can use a lock named "a" and a variable named "a" without conflict.Lock names are case sensitive. In <strong>Caché</strong>, the following are all valid and unique lock names:a, A, ^a, ^A, ab. Lock names follow the same naming conventions as local variables andglobal variables, as described in the Variables chapter of Using <strong>Caché</strong> <strong>ObjectScript</strong>.Note:Process-private global names should not be used as lock names.Lock names can be local or global. A lock name such as A is a local lock name. It appliesonly to that machine, but does apply across namespaces. A conflict occurs when twonamespaces attempt to lock the same lock name. A lock name that begins with a caret (^)character is a global lock name; the mapping for this lock follows the same mapping as thecorresponding global, and thus can apply across systems. (See Global Structure in Using<strong>Caché</strong> Multi-Dimensional Storage.)A lock name can represent a local or global variable, subscripted or unsubscripted. It can bean implicit global reference, or an extended reference to a global on another computer. (SeeGlobal Structure in Using <strong>Caché</strong> Multi-Dimensional Storage.)The reference for a lock name does not need to exist. For example, your applications maylock the lock name "ACCT" to mean, by convention, that other routines may not accessglobals in the database in the namespace "ACCTING".locktypeThe type of lock to apply or remove. You can specify a different lock type for each lockname. locktype is an optional argument; if omitted, the lock name defaults to an exclusivelock. The syntax for lock type is a mandatory pound sign (#), followed by one or more locktypes enclosed in quotation marks. Lock type codes can be specified in any order and are notcase sensitive. The following are the lock type codes:• S: Shared lockAllows multiple processes to simultaneously hold nonconflicting locks on the sameresource. For example, two (or more) processes may simultaneously hold shared lockson the same resource, but an exclusive lock limits the resource to one process. An existingshared lock prevents all other processes from setting an exclusive lock, and an existingexclusive lock prevents all other processes from setting a shared lock on that resource.However, a process can first set a shared lock on a resource and then the same processcan set an exclusive lock on the resource, upgrading the lock from shared to exclusive.82 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


Shared and Exclusive lock counts are independent. Therefore, to release such a resourceit is necessary to release both the exclusive lock and the shared lock. All locking andunlocking operations not specified as shared, default to exclusive.• I: Immediate unlockAllows you to release an incremental lock within a transaction. An immediate unlockcan only be used on an incremental lock applied within the current transaction. Animmediate unlock can be specified for a shared lock (#"SI") or an exclusive lock (#"I").Unlocks not specified as Immediate default to unlock at the conclusion of the transaction.timeoutThe number of seconds to wait for a lock request to succeed before the transaction times out.If the LOCK command performs multiple locks, all locks must succeed within the timeoutperiod. If the timeout period expires before all locks are successful, none of the locks specifiedin the LOCK command are held, and control returns to the process. It is an optional argument.If omitted, the LOCK command waits indefinitely for a resource to be lockable; if the lockcannot be set, the process will hang. The syntax for timeout is a mandatory colon (:), followedby an integer value or an expression that evaluates to an integer value. A value of zero permitsone locking attempt before timing out. A negative number is equivalent to zero. If you usetimeout and the lock is successful, <strong>Caché</strong> sets the $TEST special variable to True (1). If thelock cannot be set within the timeout period, <strong>Caché</strong> sets $TEST to False (0). (Note that$TEST is set by other <strong>Caché</strong> <strong>ObjectScript</strong> commands as well.) If the LOCK command containsmultiple comma-separated lock argument syntactical units, each lock argument canhave its own timeout. <strong>Caché</strong> parses this as multiple LOCK commands, so the timeout of onelock argument does not affect the other lock arguments.Examples and NotesSimple LockingSimple locking places a lock on a single lock name or a group of lock names and simultaneouslyremoves any locks (whether simple or incremental, exclusive or shared) previously seton any lock names by the current process. Issuing a simple lock does the following:• Releases all locks previously held by the process. This is the same as an argumentlesslock.• Locks the specified resources.LOCK<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 83


<strong>Caché</strong> <strong>ObjectScript</strong> Commands• Sets the lock table count for those lock names to 1. By default it sets the Exclusive locktable count; if lock type is #"S", it instead sets the Shared lock table count to 1 for thatlock name.The following example sets a simple lock on lock name ^a.LOCK ^aThis command requests an exclusive lock: no other process can simultaneously hold a lockon this resource. If another process already holds a lock on this resource (exclusive or shared),this example must wait for that lock to be released. It can wait indefinitely, hanging the process.To avoid this, specifying a timeout value is recommended.If a simple lock is issued during a transaction, the release of previously held resources isdeferred until the completion of the transaction. A simple lock acquired during a transactioncannot be released during that transaction. (Incremental locks can be released during atransaction using the Immediate Unlock lock type.) The TCOMMIT command completesthe transaction and releases all locks held during the transaction.The following example sets simple locks on lock names ^b, ^c, and ^d as a group.LOCK (^b,^c,^d)Note that like all simple locks, this LOCK command first releases all locks previously heldby the process. Thus the lock ^a held by the previous command would be released by issuingthis command.The grouping parentheses are required when issuing a simple lock with multiple lock names.These parentheses cause LOCK to lock all of the specified resources. If a timeout is specified,either all of the specified resources are locked or the LOCK command times out and noneof them are locked.If the parentheses were omitted, the command LOCK ^b,^c,^d would be parsed as threesimple lock commands, with the result of first releasing previously held locks and locking^b, then immediately releasing ^b in order perform a simple lock on ^c, then immediatelyreleasing ^c in order perform a simple lock on ^d. As a result, only ^d would be locked.Incremental LockingIncremental locking permits you to set multiple locks on the same resource. Your processcan then increment and decrement this lock count. As of <strong>Caché</strong> 4.1, the lock table maintainsindependent lock counts for exclusive locks and shared locks.Issuing an incremental lock does the following:84 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


• Incremental locking adds new locks without removing existing locks. It leaves unchangedthe processes' existing locks, unless those lock names are specified in the incrementalLOCK command. This gives you more explicit control over locking than available withsimple locking, permitting you to add locks without releasing existing locks.• If a specified lock name was previously unlocked, it is locked and assigned a lock countof 1. This is identical to a simple lock.• If a specified lock name was previously locked (by either a simple lock or an incrementallock), the lock continues in effect and the lock count is incremented by 1.Lock counts are assigned in the locking table as either Exclusive or Shared, depending onthe lock type used.The following example sets an incremental lock on lock names ^x and ^y.LOCK +(^x,^y)The enclosing parentheses are required when specifying multiple lock names.UnlockingThe following example removes an exclusive lock from lock name ^a.LOCK -^aIf the lock count for ^a is 1, the lock is unlocked (removed from the lock table.) This can beeither a simple lock, or an incremental lock with a lock count of 1. If the lock count for ^a isgreater than 1, the lock count is decremented.Note that only the Exclusive lock count and lock are affected, not the Shared lock count andlock. The same lock name can have both an Exclusive and a Shared lock. The followingexample removes a shared lock from lock name ^a:LOCK -^a#"S"The following example performs unlocking on lock names ^a, ^b, ^c, ^d, and ^e.LOCK ^aLOCK +(^b)LOCK +(^b,^e,^e#"S")LOCK +(^c#"S",^d#"S")LOCK -(^a,^b,^c#"S",^d,^e)The unlock command in this example does the following:• ^a is unlocked and removed from the lock table. ^a had an exclusive lock count of 1.• ^b remains in the lock table, but its exclusive lock count is decremented from 2 to 1.LOCK<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 85


<strong>Caché</strong> <strong>ObjectScript</strong> Commands• ^c is unlocked and removed from the lock table. ^c had a shared lock count of 1.• ^d is unaffected. The unlock attempted to unlock an exclusive lock, but ^d did not havean exclusive lock; it had (and continues to have) a shared lock count of 1.• ^e has both an Exclusive and a Shared lock. The unlock removed the Exclusive lock, butleft the shared lock with a lock count of 1.If a specified lock name does not have any locks on it, no operation is performed.Locking ProtocolBy itself a lock does not prevent another process from modifying the associated data because<strong>Caché</strong> does not enforce unilateral locking. Locking works only by convention: it requiresthat mutually competing processes all implement locking on the same variables.All processes in competition for write access to a given variable must lock that variable priorto updating it. A lock remains in effect until it is unlocked by the process that set it. Thus,each process must unlock the variables when it finishes with them. Without this cooperation,the concept of locking has no meaning.While in effect on a given variable, a lock causes a wait condition for any other process thatattempts to lock that variable. If a process simply writes to a locked variable without firstasserting its own lock, the write attempt will succeed.<strong>Caché</strong> maintains a system-wide lock table that records all locks that are in effect and theprocesses that have set them. Use the System Management Portal or the LOCKTAB utilityto display the existing locks in the Lock Table or to remove selected locks.Locks on Local VariablesThe behavior of LOCK on local (non-careted) variables is the same on <strong>Caché</strong>, Open M[DTM], and DSM for OpenVMS. Refer to $ZUTIL(69,8) Set ZA and ZD Modes for informationon compatibility with older DSM for OpenVMS locking commands.In Open M [DTM] and DSM for OpenVMS, local locks are always taken out in the manager'sdataset regardless of the first character. If an application ported to <strong>Caché</strong> uses local locks thatdo not begin with a % character, the application may experience deadlock conditions if ituses the same, local, non-% lock names in different datasets. The locks now collide becausethey resolve to the same item. If this is part of a hierarchical locking system, a deadly embracemay occur that can hang an application.The current behavior is:• Local (non-careted) locks acquired in the context of a specific namespace, either becausethe default namespace is an explicit namespace or through an explicit reference to a86 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


namespace, are taken out in the manager's dataset on the local machine. This occursregardless of whether the default mapping for globals is a local or a remote dataset.• Local (non-careted) locks acquired in the context of an implied namespace or throughan explicit reference to an implied namespace on the local machine, are taken out usingthe manager's dataset of the local machine. An implied namespace is a directory path orOpenVMS file specification preceded by two caret characters: "^^dir".Referencing explicit and implied namespaces is further described in Global Structure in Using<strong>Caché</strong> Multi-Dimensional Storage.Locks on Global VariablesLocking is typically used with global variables to synchronize the activities of multiple processesthat may access these variables simultaneously. Global variables differ from localvariables in that they reside on disk and are available to all processes. The potential exists,then, for two processes to write to the same global at the same time. In fact, <strong>Caché</strong> processesone update before the other, so that one update overwrites and, in effect, discards the other.Global lock names begin with a caret (^) character.To illustrate locking with global variables, consider the case in which two data entry clerksare concurrently running the same student admissions application to add records for newlyenrolled students. The records are stored in a global array named ^student. To ensure a uniquerecord for each student, the application increments the simple global variable ^index for eachstudent added. The application includes the LOCK command to ensure that each studentrecord is added at a unique location in the array, and that one student record does not overwriteanother.The relevant code in the application is shown below. In this case, the LOCK controls not theglobal array ^student but the simple global variable ^index. ^index is a scratch global that isshared by the two processes. Before a process can write a record to the array, it must lock^index and update its current value (SET ^index=^index+1). If the other process is alreadyin this section of the code, ^index will be locked and the process will have to wait until theother process releases the lock (with the argumentless LOCK command).READ !,"Last name: ",!,lname QUIT:lname="" SET lname=lname_","READ !,"First name: ",!,fname QUIT:fname="" SET fname=fname_","READ !,"Middle initial: ",!,minit QUIT:minit="" SET minit=minit_":"READ !,"Student ID Number: ",!,sid QUIT:sid=""SET rec = lname_fname_minit_sidLOCK ^indexSET ^index = ^index + 1SET ^student(^index)=recLOCKLOCK<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 87


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsLocking an Array NodeWhen you lock an array, you can lock either:• The entire array• One or more specific nodes in the arrayLocking an array node locks the node itself and, implicitly, all nodes that are subordinate tothat node. It also locks all nodes that are direct parents to the locked node. Other nodes onthe same level as the locked node remain unlocked, even though they have the same parentsas the locked node.The following example recasts the previous example to use locking on the node to be addedto the ^student array. Only the affected portion of the code is shown. In this case, the ^indexvariable is updated after the new student record is added. The next process to add a recordwill use the updated index value to write to the correct array node.LOCK ^student(^index)SET ^student(^index) = recSET ^index = ^index + 1LOCKNote that the lock location of an array node is where the top level global is mapped. <strong>Caché</strong>ignores subscripts when determining lock location. Therefore, ^student(name) is mapped tothe namespace of ^student, regardless of where the data for ^student(name) is stored.Queuing of Array Node LocksThe <strong>Caché</strong> queuing algorithm for array locks is to queue locks for the same resource in theorder received, even when there is no direct resource contention. As this may differ fromexpectations, or from implementations of lock queuing on other databases, some clarificationis provided here.Consider the case where three locks on the same global array are requested by three differentjobs:Job #1: LOCK ^X(1)Job #2: LOCK ^XJob #3: LOCK ^X(2)In this case, Job #1 gets a lock on ^X(1) and its direct parent ^X. Therefore, Job #2 must waitfor Job #1 to release ^X. But what about Job #3? The lock granted to Job #1 blocks Job #2,but does not block the lock requested by Job #3. But in <strong>Caché</strong>, Job #3 must wait for Job #2.The <strong>Caché</strong> lock queuing algorithm is fairest for Job #2. Other database implementations thatallowed Job #3 to jump the queue can speed Job #3, but could (especially if there are manyjobs such as Job #3) result in an unacceptable delay for Job #2.88 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


LOCKLocks in a NetworkIn a networked system, one or more servers may be responsible for resolving locks on globalvariables.You can use the LOCK command with any number of servers, up to 255. Remote locks heldby a client job on a remote server system are released when you call the RESJOB utility toremove the client job.Avoiding DeadlockIncremental locking is potentially dangerous because it can lead to a situation known as"deadlock". This situation occurs when two processes each assert an incremental lock on avariable already locked by the other process. Because the attempted locks are incremental,the existing locks are not released. As a result, each process hangs while waiting for the otherprocess to release the existing lock.To prevent deadlocks, you should use simple locking or always include the timeout optionwhen using incremental locks. Another way to avoid deadlocks is to follow a strict protocolfor the order in which you issue incremental LOCK commands. Deadlocks cannot occur aslong as all process follow the same order. A simple protocol is to add locks in collatingsequence order.If a deadlock occurs, you can resolve it by using the System Management Portal or theLOCKTAB utility to remove one of the locks in question. From the System ManagementPortal, open the Locks window, then select the Remove option for the deadlocked process.Global UnlockingWhen a process terminates, <strong>Caché</strong> performs an implicit argumentless LOCK to clear alllocks that were set by the process.See Also• $TEST special variable• $ZUTIL(69,8) Set ZA and ZD Modes function• Using <strong>ObjectScript</strong> for Transaction Processing in Using <strong>Caché</strong> <strong>ObjectScript</strong>• The Monitoring Locks section of the Managing <strong>Caché</strong> chapter in <strong>Caché</strong> System AdministrationGuide<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 89


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsMERGEMerges global nodes or subtrees from source into destination.MERGE:pc mergeargument,...M:pc mergeargument,...where mergeargument is:destination=sourceArgumentspcdestination and sourceOptional — A postconditional expression.Local variables, process-private globals, or globals to bemerged.DescriptionMERGE destination=source copies source into destination and all descendants of sourceinto descendants of destination. It does not modify source, or kill any nodes in destination.MERGE simplifies the copying of a sub-tree (multiple subscripts) of a variable to anothervariable. Either variable can be a local variable, a process-private global, or a global. A subtreeis all variables that are descendants of a specified variable. MERGE offers a one-commandalternative to the current technique for doing sub-tree copy: a series of SET commands with$ORDER references.MERGE returns a error if the source and destination have a parent-childrelationship.The MERGE command can take longer than most other <strong>Caché</strong> <strong>ObjectScript</strong> commands toexecute. As a result, it is more prone to interruption. The effect of interruption is implementation-specific.Under <strong>Caché</strong>, an interruption may cause an unpredictable subset of the sourceto have been copied to the destination subtree.ArgumentspcAn optional postconditional expression. <strong>Caché</strong> executes the MERGE command if the postconditionalexpression is true (evaluates to a non-zero numeric value). <strong>Caché</strong> does not execute90 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


the command if the postconditional expression is false (evaluates to zero). For further details,refer to Command Postconditional Expressions in Using <strong>Caché</strong> <strong>ObjectScript</strong>.destination and sourceVariables to be merged. Either variable can be a local variable, a process-private global, ora global. If destination is undefined, MERGE defines it and sets it to source. If source isundefined, MERGE completes successfully, but does not change destination.You can specify multiple, comma-separated destination=source pairs. They are evaluated inleft-to-right order.ExamplesThe following example copies a subtree from one global variable (^a) to another globalvariable (^b). In this case, the merge is being used to create a smaller global ^b, which containsonly the ^a(1,1) subtree of the information in ^a.SET ^a="cartoons"SET ^a(1)="The Flintstones",^a(2)="The Simpsons"SET ^a(1,1)="characters",^a(1,2)="place names"SET ^a(1,1,1)="Flintstone family"SET ^a(1,1,1,1)="Fred"SET ^a(1,1,1,2)="Wilma"SET ^a(1,1,2)="Rubble family"SET ^a(1,1,2,1)="Barney"SET ^a(1,1,2,2)="Betty"MERGE ^b=^a(1,1)WRITE ^b,!,^b(2),!,^b(2,1)," and ",^b(2,2)The following example shows how a destination global variable looks after it has been mergedwith a sub-tree of a source global variable.Suppose you execute the following:KILL ^X,^YSET ^X(2,2)="first"SET ^X(2,2,4)="second"SET ^Y(3,6,7)="third"SET ^Y(3,6,8)="fourth"SET ^Y(3,6,7,8,4)="fifth"SET ^Y(3,6,7,8,9)="sixth"WRITE ^X(2,2),!,^X(2,2,4),!WRITE ^Y(3,6,7),!,^Y(3,6,8),!WRITE ^Y(3,6,7,8,4),!,^Y(3,6,7,8,9)The following figure shows the resulting logical structure of ^X and ^Y.MERGE<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 91


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsInitial Structure of ^X and ^YConsider the following MERGE command:MERGE ^X(2,3)=^Y(3,6,7,8)When you issue the previous statement, <strong>Caché</strong> copies part of ^Y into ^X(2,3). The global ^Xnow has the structure illustrated in the figure below.Result on ^X and ^Y of MERGE Command92 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


NotesNaked IndicatorWhen both destination and source are local variables, the naked indicator is not changed. Ifsource is a global variable and destination is a local variable, then the naked indicator referencessource.When both source and destination are global variables, the naked indicator is unchanged ifsource is undefined ($DATA(source)=0). In all other cases (including $DATA(source)=10),the naked indicator takes the same value that it would have if the SET command replacedthe MERGE command and source had a value. For more details on the naked indicator, seeNaked Global <strong>Reference</strong> in Using <strong>Caché</strong> Multi-Dimensional Storage.Merge to SelfWhen the destination and source are the same variable, no merge occurs. Nothing is recordedin the journal file. However, the naked indicator may be changed, based on the rules describedin the previous section.WatchpointsThe MERGE command supports watchpoints. If a watchpoint is in effect, <strong>Caché</strong> triggersthat watchpoint whenever that MERGE alters the value of a watched variable. To setwatchpoints, use the ZBREAK command.See Also• ZBREAK command• Debugging chapter in Using <strong>Caché</strong> <strong>ObjectScript</strong>• Global Structure chapter in Using <strong>Caché</strong> Multi-Dimensional StorageMERGE<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 93


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsNEWCreates empty local variable environment.NEW:pc newargument,...N:pc newargument,...where newargument can be:variable,...or(variable,...)ArgumentspcvariableOptional — A postconditional expression.Optional — Name of variable(s) to be added to the existing local variableenvironment. The effect of a NEW on existing local variables dependson whether variable is enclosed in parentheses (exclusive NEW) or isnot enclosed in parentheses (inclusive NEW).DescriptionThe NEW command has two forms:• Without an argument• With an argumentNEW without an argument creates an empty local variable environment for a called subroutineor user-defined function. Existing local variable values are not available in this new localenvironment. They can be restored by returning to the previous local environment.The action NEW with an argument performs depends on the argument form you use.• NEW variable (inclusive NEW) retains the existing local variable environment and addsthe specified variable(s) to it. If any of the specified local variables has the same nameas an existing local variable, the old value for that named variable is no longer accessiblein the current environment.• NEW (variable) (exclusive NEW) replaces all existing variables in the local variableenvironment except the specified variable(s).94 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


NEWNote:Exclusive NEW (NEW (x,y,z)) temporarily removes local variables from the currentscope. This can affect local variables created by <strong>Caché</strong> objects. For example, <strong>Caché</strong>maintains %objcn which is the cursor pointer for <strong>Caché</strong> Objects queries. Removingthis from the current scope can result in collisions with other internal structures.Therefore, do not use exclusive NEW in any context where it might affect systemstructures.NEW RestrictionsThe NEW command cannot be used on the following:• Globals• Process-Private Globals• Local variable subscripts• Private variables• Special variables, with the exception of $ETRAPAttempting to use NEW in any of these contexts results in a error.ArgumentspcAn optional postconditional expression. <strong>Caché</strong> executes the NEW command if the postconditionalexpression is true (evaluates to a non-zero numeric value). <strong>Caché</strong> does not executethe command if the postconditional expression is false (evaluates to zero). For further details,refer to Command Postconditional Expressions in Using <strong>Caché</strong> <strong>ObjectScript</strong>.variableName of a single variable or a comma-separated list of variable names. You can specify onlyunsubscripted variable names, although you can NEW an entire array (that is, an array namewithout subscripts). You can specify undefined variable names or you can reuse the namesof existing local variables. For an inclusive NEW, when you specify an existing local variable,<strong>Caché</strong> reinitializes that variable in the local environment, but saves its current value on theprogram stack and restores it after the subroutine or function terminates.When a variable name or comma-separated list of variable names is enclosed in parentheses(exclusive NEW), <strong>Caché</strong> performs the opposite operation. That is, all local variables arereinitialized except the specified variable names, which retain their previous values. <strong>Caché</strong><strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 95


<strong>Caché</strong> <strong>ObjectScript</strong> Commandssaves the current values of all variables on the program stack and restores them after thesubroutine or function terminates.ExamplesThe following example illustrates an inclusive NEW, which keeps the existing local variablesa, b, and c, and adds variables d and e, in this case, overlaying the prior value of d.MainSET a=7,b=8,c=9,d=10WRITE !,"Before NEW:",!,"a=",a,!,"b=",b,!,"c=",c,!,"d=",dDO Sub1WRITE !,"Returned to prior context:"WRITE !,"a=",a,!,"b=",b,!,"c=",c,!,"d=",dQUITSub1NEW d,eSET d="big number"WRITE !,"After NEW:",!,"a=",a,!,"b=",b,!,"c=",c,!,"d=",dQUITThe following example illustrates an exclusive NEW, which removes all existing local variablesexcept the specified variables a and c.SET a=7,b=8,c=9,d=10NEW (a,c)WRITENotesWhere to Use NEWNEW allows you to insulate the current process's local variable environment from changesmade by a subroutine, user-defined function, or XECUTE string. NEW is most frequentlyused within a subroutine called by the DO command.The basic purpose of the NEW command is to redefine the local variable environment withina called subroutine or user-defined function. A subroutine or user-defined function calledwithout parameter passing inherits its local variable environment from the calling routine.To redefine this environment for a subroutine or function, you can use NEW for all localvariables (argumentless NEW), for named local variables (inclusive NEW) or for all localvariables except the named variables (exclusive NEW).Special considerations apply in the case of a subroutine called by the DO command withparameter passing. These considerations are described under "Subroutines with ParameterPassing".96 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


NEWNEW and KILLVariables created by NEW do not require explicit and corresponding KILL commands.When a called subroutine or a user-defined function terminates, <strong>Caché</strong> executes an implicitKILL for each variable initialized by a NEW command within that subroutine or function.Inclusive NEWAn inclusive NEW — NEW variable — retains the existing local variable environment andadds the specified variables to it. If an existing variable is named, the "new" variable replacesthe existing variable, which is saved on the stack and then restored when the subroutine orfunction terminates.In the following example, assume that the local variable environment of the calling routine(Start) consists of variables a, b, and c. When the DO calls Subr1, the NEW command redefinesSubr1's local variable environment to add variables c and d. After the NEW, the subroutine'senvironment consists of the existing variables a and b plus the new variables c and d.The variables a and b are inherited and retain their existing values. The new variables c andd are created undefined. Since c is the name of an existing local variable, <strong>Caché</strong> saves theexisting value on the stack and restores it when Subr1 QUITs. Note that the first SET commandin Subr1 references a and b to assign a value to d. If c were referenced at this point,<strong>Caché</strong> would issue an error.Start SET a=2,b=4,c=6DO Subr1WRITE !,"c in Start: ",cQUITSubr1 NEW c,dSET d=a*bSET c=d*2WRITE !,"c in Subr1: ",cQUITWhen executed, this code produces the following results:c in Subr1: 16c in Start: 6Exclusive NEWAn exclusive NEW — NEW (variable) — replaces the entire existing local variable environmentexcept the specified variables. If an existing variable is named, it is retained and can bereferenced in the new environment. However, any changes made to such a variable arereflected in the existing variable when the function or subroutine terminates.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 97


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsIn the following example, assume that the local variable environment of the calling routine(Start) consists of variables a, b, and c. When the DO calls Subr1, the NEW commandredefines Subr1's local variable environment to exclude all variables except c and d.After the NEW, the subroutine's environment consists only of the new variables c and d. Thenew variable c is retained from the calling routine's environment and keeps its existing value.The new variable d is created undefined.The first SET command in Subr1 references c to assign a value to d. The second SET commandassigns a new value (24) to c. When the subroutine QUITs, c will have this updatedvalue (and not the original value of 6) in the calling routine's environment.Start SET a=2,b=4,c=6DO Subr1WRITE !,"c in Start: ",cQUITSubr1 NEW (c,d)SET d=c+cSET c=d*2WRITE !,"c in Subr1: ",cQUITWhen executed, this code produces the following results:c in Subr1: 24c in Start: 24Argumentless NEWThe argumentless NEW provides an empty local variable environment for a called subroutineor user-defined function. The existing local variable environment (in the calling routine) issaved and then restored when the subroutine or function terminates. Any variables createdafter the NEW are deleted when the subroutine or function terminates.If a command follows the NEW on the same line, be sure to separate the NEW commandfrom the command following it by (at least) two spaces.$ETRAP and Special VariablesYou cannot use NEW on special variables; attempting to do so results in a error.The one exception is $ETRAP. When you issue the command NEW $ETRAP, <strong>Caché</strong> createsa new context for error trapping. You can then set $ETRAP in this new context with thedesired error trapping command(s). The $ETRAP value in the previous context is preserved.If you set $ETRAP without first issuing the NEW $ETRAP command, <strong>Caché</strong> sets $ETRAPto this value in all contexts. It is therefore recommended that you always NEW the $ETRAPspecial variable before setting it.98 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


NEWSubroutines with Parameter PassingIf you call a subroutine with parameter passing, <strong>Caché</strong> issues an implicit NEW commandfor each of the variables named in the subroutine's formal parameter list. It then assigns thevalues passed in the DO command's actual parameter list (by value or by reference) to thesevariables.If the DO command uses parameter passing by value and if the formal list names any existinglocal variables, <strong>Caché</strong> places the existing variables and their values on the stack. When thesubroutine terminates (with either an explicit or an implicit QUIT), <strong>Caché</strong> issues an implicitKILL command for each of the formal list variables to restore them from the stack.When using NEW command within a subroutine, never specify any of the variables namedin the subroutine's formal parameter list. By defining these variables as NEW, you renderthem undefined and make their passed values inaccessible.See Also• DO command• QUIT command• SET command• $ETRAP special variable<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 99


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsOPENAcquires ownership of a specified device or file for input/output operations.OPEN:pc device:(parameters):timeout:"mnespace",...O:pc device:(parameters):timeout:"mnespace",...ArgumentspcdeviceparameterstimeoutmnespaceOptional — A postconditional expression.The device to be opened, specified by a device ID or a device alias.A device ID can be an integer (a device number), a device name,or the pathname of a sequential file. If a string, it must be enclosedwith quotation marks.Optional — The list of parameters used to set device characteristics.The parameter list is enclosed in parentheses, and the parametersin the list are separated by colons. Parameters can either bepositional (specified in a fixed order in the parameter list) or keyword(specified in any order). A mix of positional and keyword parametersis permitted. The individual parameters and their positions andkeywords are highly device-dependent.Optional — The number of seconds to wait for the request tosucceed, specified as an integer.Optional — The name of the mnemonic space that contains thecontrol mnemonics to use with this device, specified as a quotedstring.DescriptionUse the OPEN command to acquire ownership of a specified device (or devices) forinput/output operations. An OPEN retains ownership of the device until ownership is releasedwith the CLOSE command.An OPEN command can be used to open multiple devices by using a comma to separatedthe specifications for each device. Within the specification of a device, its arguments areseparated by using colons (:). If an argument is omitted, the positional colon must be specified;however, trailing colons are not required.100 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


The OPEN command can be used to open devices such as terminal devices, magnetic tapedevices, spool devices, TCP bindings, interprocess pipes, named pipes, and inter-job communications.The OPEN command can also be used to open a sequential file. The device argument specifiesthe file pathname as a quoted string. The parameters argument specifies the parametersgoverning the sequential file. These parameters can include the option of creating a new fileif the specified file does not exist. Specifying the timeout argument, though optional, isstrongly encouraged when opening a sequential file. Sequential file open option defaults areset for the current process using the $ZUTIL(68,2) and $ZUTIL(68,3) functions, and systemwideby using the $ZUTIL(69,2) and $ZUTIL(69,3) functions. For much more details onopening sequential files, see Sequential File I/O in the <strong>Caché</strong> I/O Device Guide.The OPEN command is not used to access a <strong>Caché</strong> database file.On Windows, <strong>Caché</strong> <strong>ObjectScript</strong> allocates each process an open file quota between databasefiles and files opened with OPEN. When OPEN causes too many files to be allocated toOPEN commands, you receive a error. <strong>Caché</strong> does not limit thenumber of open files; the maximum number of open files for each process is a platform-specificsetting. Consult the operating system documentation for your system.ArgumentspcAn optional postconditional expression. <strong>Caché</strong> executes the OPEN command if the postconditionalexpression is true (evaluates to a non-zero numeric value). <strong>Caché</strong> does not executethe OPEN command if the postconditional expression is false (evaluates to zero). Only onepostconditional is permitted, even if the OPEN command opens multiple devices or files.For further details, refer to Command Postconditional Expressions in Using <strong>Caché</strong><strong>ObjectScript</strong>.deviceThe device to be opened. You can specify the device using any of the following:OPEN• Physical device number, specified as a positive integer. For example, 2 is always thespooler device. This is the only way to specify a magnetic tape device (numbers 47through 62). This number is internal to <strong>Caché</strong> and is unrelated to device numbers assignedby the platform operating system.• Device ID, specified as a quoted string. For example, "|TRM|:|4294318809". This valuefor the current device is found in the $IO special variable.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 101


<strong>Caché</strong> <strong>ObjectScript</strong> Commands• Device alias, specified as a positive integer. A device alias refers to a physical devicenumber.• File pathname, specified as a quoted string. This is used for opening sequential files. Apathname can be canonical (c:\myfiles\testfile) or relative to the current directory(\myfiles\testfile).See "Specifying the Device" for more information.parametersThe list of parameters used to set operating characteristics of the device to be opened. Theenclosing parentheses are required if there is more than one parameter. (It's good programmingpractice to always use parentheses when you specify a parameter.) Note the required colonbefore the left parenthesis. Within the parentheses, colons are used to separate multipleparameters.The parameters for a device can be specified using either positional parameters or keywordparameters. You can also mix positional parameters and keyword parameters within the sameparameter list.In most cases, specifying contradictory, duplicate, or invalid parameter values does not resultin an error. Wherever possible, <strong>Caché</strong> ignores inappropriate parameter values and takesappropriate defaults.If you do not specify a list of parameters, <strong>Caché</strong> uses the device's default parameters. Thedefault parameters for a device are configurable. Go to the System Management Portal, selectSystem Configuration, select Advanced Settings, on the pull-down Category list select Devices.Click “contents” to display the current list of devices. For the desired device, click “edit”to display its Open Parameter: option. Specify this value in the same way you specify theOPEN command parameters, including the enclosing parentheses. For example,("AVL":0:2048).The available parameters are specific to the type of device that is being opened. For moreinformation on device parameters, see I/O Devices and Commands in <strong>Caché</strong> I/O DeviceGuide.Positional ParametersPositional parameters must be specified in a fixed sequence in the parameter list. You canomit a positional parameter (and receive the default value), but you must retain the colon toindicate the position of the omitted positional parameter. Trailing colons are not required;excess colons are ignored. The individual parameters and their positions are highly devicedependent.There are two types of positional parameters: values and letter code strings.102 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


A value can be an integer (for example, record size), a string (for example, host name), or avariable or expression that evaluates to a value.A letter code string uses individual letters to specify device characteristics for the openoperation. For most devices, this letter code string is one of the positional parameters. Youcan specify any number of letters in the string, and specify the letters in any order. Lettercodes are not case sensitive. A letter code string is enclosed in quotation marks; no spacesor other punctuation is allowed within a letter code string (exception: K and Y may be followedby a name delimited by backslashes: thus: K\name\). For example, when opening a sequentialfile, you might specify a letter code string of “ANDFW” (append to existing file, create newfile, delete file, fix-length records, write access.) The position of the letter code stringparameter, and the meanings of individual letters is highly device-dependent.Keyword ParametersKeyword parameters can be specified in any sequence in the parameter list. A parameter listcan consist entirely of keyword parameters, or it can contain a mix of positional and keywordparameters. (Commonly, the positional parameters are specified first (in their correct positions)followed by the keyword parameters.) You must separate all parameters (positional or keyword)with a colon (:). A parameter list of keyword parameters has the following generalsyntax:OPENdevice:(/KEYWORD1=value1:/KEYWORD2=value2:.../KEYWORDn=valuen):timeoutThe individual parameters and their positions are highly device-dependent. As a general rule,you can specify the same parameters and values using either a positional parameter or akeyword parameter. You can specify a letter code string as a keyword parameter by usingthe /PARAMS keyword.timeoutOPENThe number of seconds to wait for the OPEN request to succeed. The preceding colon isrequired. timeout must be specified as an integer value or expression. If timeout is set to zero(0), OPEN makes a single attempt to open the file. If the attempt fails, the OPEN immediatelyfails. If the attempt succeeds it successfully opens the file. If timeout is not set, <strong>Caché</strong> willcontinue trying to open the device until the OPEN is successful or the process is terminatedmanually. If you use thetimeout option and the device is successfully opened, <strong>Caché</strong> sets the$TEST special variable to TRUE (non-zero). If the device cannot be opened within thetimeout period, <strong>Caché</strong> sets $TEST to FALSE (0).<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 103


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsmnespaceThe name of the mnemonic space that contains the device control mnemonics used by thisdevice. By default, <strong>Caché</strong> provides two mnemonic spaces: ^%XMAG for magnetic tapedevices, and ^%X364 (ANSI X3.64 compatible) for all other devices and sequential files.Default mnemonic spaces are assigned by device type.Go to the System Management Portal, select System Configuration, select Advanced Settings,on the pull-down Category list select IO. Select either MnemonicMagTape, MnemonicOther,MnemonicSeqFile, or MnemonicTerminal. For the desired device type, click “edit” to displayand edit its mnemonic space setting.A mnemonic space is a routine that contains entrypoints for the device control mnemonicsused by READ and WRITE commands. The READ and WRITE commands invoke thesedevice control mnemonics using the /mnemonic(params) syntax. These device controlmnemonics perform operations such a moving the cursor to a specified screen location orrewinding a magnetic tape.Use the mnespace argument to override the default mnemonic space assignment. Specify a<strong>Caché</strong> <strong>ObjectScript</strong> routine that contains the control mnemonics entrypoints used with thisdevice. The enclosing double quotes are required. Specify this option only if you plan to usedevice control mnemonics with the READ or WRITE command. If the mnemonic spacedoes not exist, a error is returned. For further details on mnemonic spaces,see I/O Devices and Commands in the <strong>Caché</strong> I/O Device Guide.ExamplesIn the following example, the OPEN command attempts to acquire ownership of device 2(the spooler). The first positional parameter (3) specifies the file number within the ^SPOOLglobal and the second positional parameter (12) specifies the line number within the file. Ifyou later use the USE command to make this the current device (that is, USE 2), <strong>Caché</strong><strong>ObjectScript</strong> sends subsequent output to the spooler.OPEN 2:(3:12)In the following example, the OPEN command attempts to acquire ownership of thesequential file CUSTOMER within the timeout period of 10 seconds.OPEN "\myfiles\customer"::10Note that because no parameters are specified, the parentheses are omitted, but the colonmust be present.104 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


The following example opens a sequential file named Seqtest; the letter code positionalparameter is ”NRW”. The “N” letter code specifies that if the file does not exist, create a newsequential file with this name. The “R” and “W” letter codes specify that the file is beingopened for reading and writing. The timeout is 5 seconds.ZNSPACE "%SYS"SET dir=$ZUTIL(168) ; determine <strong>Caché</strong> directorySET seqfilename=dir_"Samples\Seqtest"OPEN seqfilename:("NRW"):5WRITE !,"Opened a sequential file named Seqtest"USE seqfilenameWRITE "a line of data for the sequential file"CLOSE seqfilename:"D"WRITE !,"Closed and deleted Seqtest"QUITNotesDevice Ownership and the Current DeviceOPEN establishes ownership of the specified device. The process retains ownership of thedevice until the process either terminates or releases the device with a subsequent CLOSEcommand. While a device is owned by a process, no other process can acquire or use thedevice.A process can own multiple devices at the same time. However, only one device can be thecurrent device. You establish an owned device as the current device with the USE command.The ID of the current device is found in the $IO special variable.A process always owns at least one device (designated as device 0), which is its principaldevice. This device is assigned to the process when it is started and is typically the terminalused to sign onto <strong>Caché</strong>. The ID of the principal device is found in the $PRINCIPAL specialvariable.When a process terminates, <strong>Caché</strong> issues an implicit CLOSE for each of the devices ownedby the process and returns them to the pool of available devices.Changing Parameters for an Owned DeviceTo change the parameters for a device that is already owned by the process, you can:• Close and then reopen the device• Specify the device on another OPEN command, but with new parameter values.OPENIf you specify the device on another OPEN command, any device parameters set by the initialOPEN command remain in effect unless explicitly changed. Depending on the type of device,subsequent I/O may be different than if you had closed and then reopened the device.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 105


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsFor some devices, you can omit the parameters option and later set the desired characteristicswith the parameters option on the USE command.Specifying the DeviceWhen you open a device, you can identify the device by supplying a device number or analias assigned to the device.Using Physical Device Numbers<strong>Caché</strong> allows you to identify certain devices by supplying their system-assigned physicaldevice numbers. All implementations of <strong>Caché</strong> recognize the following physical devicenumbers:• 0 = The process's principal device (usually the device at which you sign on).• 2 = The spooler (to store output for later printing).• 63 = The view buffer.Open 63 accepts a namespace as follows:OPEN 63:namespaceSee About I/O Devices in <strong>Caché</strong> I/O Device Guide for more information about device numbers.Using a Device AliasAn alias is an alternate numeric device ID. It must be a valid device number, it must be uniqueand cannot conflict with an assigned device number.You can establish a numeric alias for a device. Go to the System Management Portal, selectSystem Configuration, select Advanced Settings, on the pull-down Category list select Devices.Click “contents” to display the current list of devices. For the desired device, click “edit”to display and edit its Alias: option.After you have assigned an alias to a device, you can use the OPEN command or the %ISutility to open the device using this alias.Exceeding the Open File Quota<strong>Caché</strong> allocates each process' open file quota between database files and files opened withOPEN. When OPEN causes too many files to be allocated to OPEN commands, you receivea error.See Also• CLOSE command106 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


PRINT• USE command• $TEST special variable• $IO special variable• $ZUTIL(55) Language Mode Switch function• $ZUTIL(96,14) Current Device Type function• I/O Devices and Commands in <strong>Caché</strong> I/O Device Guide• Terminal I/O in <strong>Caché</strong> I/O Device Guide• Magnetic Tape I/O in <strong>Caché</strong> I/O Device Guide• Sequential File I/O in <strong>Caché</strong> I/O Device Guide• The Spool Device in <strong>Caché</strong> I/O Device Guide• ^%IS global and %IS utility in <strong>Caché</strong> I/O Device GuidePRINTSends lines of code to printer.PRINT:pc printargumentP:pc printargumentwhere printargument can be:lineref1:lineref2Argumentspclineref1lineref2Optional — A postconditional expression.Optional — A line to be printed, or the first line of a range of lines tobe printed.Optional — The last line of a range of lines to be printed.DescriptionThe PRINT command has two forms:• Without an argument<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 107


<strong>Caché</strong> <strong>ObjectScript</strong> Commands• With an argumentPRINT without an argument prints all the lines of code in the currently-loaded routine.PRINT with an argument prints the lines from the currently-loaded routine that you specifyin the argument. PRINT lineref1 prints a single specified line of code (lineref1). PRINTlineref1:lineref2 prints the range of lines that starts with lineref1 and ends with lineref2.ArgumentspcAn optional postconditional expression. <strong>Caché</strong> executes the PRINT command if the postconditionalexpression is true (evaluates to a non-zero numeric value). <strong>Caché</strong> does not executethe command if the postconditional expression is false (evaluates to zero). For further details,refer to Command Postconditional Expressions in Using <strong>Caché</strong> <strong>ObjectScript</strong>.lineref1A line to be printed. It can be specified in either of the following forms:+offsetlabel [+offset]offset is a positive integer specifying the line number withinthe current routine.label is a label within the routine and offset is the line numberwithin the label. If you omit offset, <strong>Caché</strong> prints the first codeline and the label. With this form, offset actually evaluates tooffset+1. For example, label+1 prints the second line withinthe label.lineref2The last line in a range of lines to be printed. Specified the same as lineref1. The precedingcolon is required.ExamplesThis example prints the sixth line in the currently-loaded routine.PRINT +6This example prints the third through eighth lines.PRINT +3+8108 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


NotesPrinting to the Current DeviceThe output from PRINT is sent to the current device. You establish the current device withthe USE command. <strong>Caché</strong> maintains the current device ID in the $IO special variable.Printing a RangeTo print a range, include the lineref2 option. lineref2 can be specified in the same two formsas lineref1. Consider the following example:PRINT Getid:Getid+6The previous example prints the first through seventh (offset+1) lines within label Getid.You can use different label names when specifying a range, but only if the second label followsthe first. For example, if label Checkid follows label Getid, the following command printsonly the first line of Checkid:PRINT Checkid:Getid+2On the other hand, the following command prints all lines from the first line in Getid to thethird line in Checkid:PRINT Getid:Checkid+3ZPRINT Equivalent to PRINTThe ZPRINT command is the equivalent of the PRINT command.See Also• ZLOAD command• ZPRINT command• ZREMOVE command• The Spool Device in <strong>Caché</strong> I/O Device GuidePRINT<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 109


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsQUITTerminates execution.QUIT:pc expressionQ:pc expressionArgumentspcexpressionOptional — A postconditional expression.Optional — A <strong>Caché</strong> <strong>ObjectScript</strong> expression.DescriptionThe QUIT command has two forms:• Without an argument• With an argumentA postconditional is not considered an argument. The $QUIT special variable indicateswhether or not an argumented QUIT command is required to exit from the current context.Two error codes are provided for this purpose: M16 “Quit with an argument not allowed”and M17 “Quit with an argument required.” For further details, see $ECODE and the ANSI-Standard M Error Messages listing in the <strong>Caché</strong> Error <strong>Reference</strong>.QUIT Without an ArgumentQUIT without an argument terminates the execution level of a process started with a DO,XECUTE, or FOR command.If the DO, XECUTE, or (unnested) FOR command was given in programmer mode, QUITreturns control to programmer mode. If the terminated process contains any NEW commandsbefore QUIT, QUIT automatically KILLs the affected variables and restores them to theiroriginal values.QUIT With an ArgumentQUIT expression terminates a user-defined function or an object method and returns thevalue resulting from the specified expression.If an argumented QUIT is invoked inside a subroutine called by a DO command and is inthe scope of that DO argument, then the QUIT command evaluates its argument (and anyside effects of that evaluation occur) but otherwise ignores the QUIT argument and returns110 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


to the caller of the subroutine. It does not generate an M16 "Quit with an argument notallowed" error.ArgumentspcAn optional postconditional expression. <strong>Caché</strong> executes the command if the postconditionalexpression is true (evaluates to a non-zero numeric value). <strong>Caché</strong> does not execute the commandif the postconditional expression is false (evaluates to zero). For further details, referto Command Postconditional Expressions in Using <strong>Caché</strong> <strong>ObjectScript</strong>. If the QUIT commandtakes no other arguments, there must be two or more spaces between the postconditional andthe next command following it on the same line.expressionAny valid <strong>Caché</strong> <strong>ObjectScript</strong> expression. It can be used only within a user-defined functionto return the evaluated result to the calling routine.ExamplesIn this example, execution of the QUIT command is controlled by a postconditional (:x


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsQUIT and LoopsA QUIT can be used to break out of a FOR loop, a DO WHILE loop, or a WHILE loop.If these loop structures are nested, the QUIT breaks out of the loop from which it was calledto the next enclosing loop.A QUIT cannot be used to break out of a nested IF block. When an IF block is nested withina loop structure (such as a FOR loop), a QUIT in the IF block breaks out of the enclosingloop as well.Implicit QUITIn the following cases, a QUIT command is not required, because <strong>Caché</strong> automatically issuesan implicit QUIT to prevent execution "falling through" to a separate unit of code.• <strong>Caché</strong> executes an implicit QUIT at the end of a routine.• <strong>Caché</strong> executes an implicit QUIT when it encounters a label with parameters. A labelwith parameters is defined as one with parentheses, even if the parentheses contain zeroparameters. All procedures begin with a label with parameters (even if no parameters aredefined). Many subroutines and functions also have a label with parameters.You can, of course, code an explicit QUIT in any of these circumstances.Behavior with DOWhen encountered in a subroutine called by the DO command, QUIT terminates the subroutineand returns control to the command following the DO command.Behavior with XECUTEWhen encountered in a line of code that is being executed, QUIT terminates execution ofthe line and returns control to the command following the XECUTE command. No argumentis allowed.Behavior with Loop StructuresWhen encountered in a loop structure, such as a FOR loop, QUIT terminates that loop andreturns control to the next command outside the range of the loop. In the case of nested loops,QUIT affects only the loop in which it occurs and any lower level loops that might be executedas a result of that loop. Higher level loops are not terminated.To control an indefinite FOR loop, you must include either a postconditioned QUIT or anIF command that invokes a QUIT. The QUIT within the IF terminates the enclosing FORloop. Without one of these QUITs, the loop will be an infinite loop and will execute endlessly.112 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


In the following example, the FOR loop continues to execute as long as the user enters somevalue in response to the "Text =" prompt. Only when the user enters a null string (that is,just presses Return or Enter) is QUIT executed and the loop terminated.MainFOR {READ !,"Text =",var1QUIT:var1="" DO Subr1}Subr1WRITE "Thanks for the input", !QUITThis command includes two spaces between the postconditional on the QUIT command andthe following DO command. This is because <strong>Caché</strong> treats postconditionals as commandmodifiers, not as arguments.Behavior with User-Defined FunctionsWhen encountered in a user-defined function, QUIT terminates the function and returns thevalue that results from the specified expression. The expression argument is required.In their use, user-defined functions are similar to DO commands with parameter passing.They differ from such DO commands, however, in that they return the value of an expressiondirectly, rather than through a variable. To invoke a user- defined function, use the form:$$name(parameters)QUITwhere name is the name of the function. It can be specified as label, ^routine, or label^routine.parameters is a comma-separated list of parameters to be passed to the function. The labelassociated with the function must also have a parameter list. The parameter list on the invokedfunction is known as the actual parameter list. The parameter list on the function label isknown as the formal parameter list.In the following example, the FOR loop uses a READ command to first acquire the numberto be squared and store it in the num variable. (Note the two spaces after the argumentlessFOR and the postconditional QUIT.) It then uses a WRITE command to invoke the Squarestandard function, with num specified as the function parameter.The only code for the function is the QUIT command followed by an expression to calculatethe square. When it encounters the QUIT command, <strong>Caché</strong> evaluates the expression, terminatesthe function, and returns the resulting value directly to the WRITE command. The value ofnum is not changed.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 113


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsTest WRITE "Calculate the square of a number",!FOR {READ !,"Number:",num QUIT:num=""WRITE !,$$Square(num),!QUIT}Square(val)QUIT val*valClearing Levels from the Program StackEach invocation of QUIT removes a context frame from the call stack for your process. The$STACK special variable contains the current number of context frames on the call stack.You can use QUIT from the programmer prompt to clear some or all levels from the programstack. The following example clears the top two levels from the stack:QUIT 2The argumentless QUIT clears all the levels from the stack.Using QUIT for Program Readability<strong>Caché</strong> executes an implicit QUIT at the end of each routine, but you can include it explicitlyto improve program readability.See Also• DO command• DO WHILE command• FOR command• NEW command• WHILE command• XECUTE command• ZQUIT command• $QUIT special variable• $STACK special variable114 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


READREADAccepts input and stores it in a variable.READ:pc readargument,...R:pc readargument,...where readargument isfstringvariable:timeout*variable:timeoutvariable#n:timeoutArgumentspcvariablenstringftimeoutOptional — A postconditional expression.The variable to receive the input data. Can be a local variable, aprocess-private global, or a global. May be unsubscripted orsubscripted.Optional — The number of characters to accept, specified as an integer,or an expression or variable that evaluates to an integer.The preceding# symbol is mandatory.Optional — A string literal that provides a prompt or message for userinput. Enclose in quotation marks.Optional — One or more format control characters. Permitted charactersare !, #, ?, and /.Optional — The number of seconds to wait for the request to succeed,specified as an integer. The preceding colon (:) is mandatory.DescriptionThe READ command accepts input from the current device. The current device is establishedusing the OPEN and USE commands. The $IO special variable contains the device ID ofthe current device. By default, the current device is the user terminal.The READ command suspends program execution until it either receives input from thecurrent device or times out. For this reason, the READ command should not be used in programsexecuted as background (non-interactive) jobs if the current device is the user terminal.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 115


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsThe variable argument receives the input characters. READ first defines variable, if it isundefined, or clears it if it has a previous value. Therefore, if no data is input for variable(for example, if the READ times out before any characters are entered) variable is definedand contains the null string. This is also true if the only character entered is a terminatorcharacter (for example, pressing the key from the user terminal). For the effects ofan interrupt (for example, ) see below.Note that for fixed-length and variable-length reads, variable does not store the terminatorcharacter used to terminate the read operation. Single-character reads handle variable differently;for single-character read use of variable, see below.If a READ times out, those characters input before the timeout are stored in variable, eventhough the data was not entered by a terminator character, such as the key.There are three types of READ operations: variable-length read, fixed-length read, and singlecharacterread. All of these can be specified with or without a timeout argument. A singleREAD command can include multiple READ operations in any combination of these threetypes. Each read operation is executed independently in left-to-right sequence. A READcommand can also contain any number of string and format arguments.The three types of READ operations are as follows:• A variable-length read has the following format:READ variableA variable-length read accepts any number of input characters and stores them in thespecified variable. Input is concluded by a terminator character. For a terminal, this terminatoris usually supplied by pressing the key. The input characters, but notthe terminator character, are stored in variable.• A fixed-length read has the following format:READ variable#nA fixed-length read accepts a maximum of n input characters and stores them in thespecified variable. Input concludes automatically when the nth character is input, or whena terminator character is encountered. For example, entering two characters in a fourcharacterfix-length read, and then pressing the key. The input characters, butnot the terminator character (if any), are stored in variable.• A single-character read has the following format:READ *variable116 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


A single-character read accepts a single input character and stores its ASCII decimalequivalent in the specified variable. It stores the character itself in the $ZB and $KEYspecial variables. Input concludes automatically when a single character is input. A terminatorcharacter is considered a single-character input, and is stored as such. A timeoutsets variable to –1.ArgumentspcAn optional postconditional expression. <strong>Caché</strong> executes the command if the postconditionalexpression is true (evaluates to a non-zero numeric value). <strong>Caché</strong> does not execute the commandif the postconditional expression is false (evaluates to zero). For further details, referto Command Postconditional Expressions in Using <strong>Caché</strong> <strong>ObjectScript</strong>.variableThe local variable, process-private global, or global that is to receive the input data. It canbe either unsubscripted or subscripted. If a specified variable does not already exist, <strong>Caché</strong>defines it at the beginning of the READ operation. If a specified variable is defined and hasa value, <strong>Caché</strong> clears this value at the beginning of the READ operation. When you inputcharacters, they are stored in variable as they are input; therefore if a read operation is interruptedby a timeout, the characters typed up to that point are stored in variable. (However,note the behavior of variable upon a encountered a interrupt, as described below.)Non-printing characters (such as ) are stored in variable. A terminator character canbe used to conclude any type of read operation. For example, from a terminal, you press the key to conclude a read operation. This terminator character is not stored in variablefor a variable-length or fixed-length read. The terminator character is stored in variable fora single-character read.nREADA positive integer specifying the maximum number of characters to accept for a fixed-lengthread. The READ completes either when the specified number of characters is input, or whenit encounters a terminator character. This argument is optional, but if specified the preceding# symbol is required.Specifying zero or a negative number results in a error. However, leading zerosand the fractional portion of a number are ignored, and the integer portion used. You canspecify n as a variable or an expression that resolve to an integer.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 117


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsNote that READ a#1 and READ *a can both be used to input a single character. However thevalue stored in variable is different: a#1 stores the input character in variable a; *a stores theASCII numeric value for the input character in variable a; both store the input character inthe $ZB special variable. These two types of single-character input also differ in how theyhandle terminator characters and how they handle a timeout.stringA string literal that provides a prompt or message for user input with the terminal keyboard.Generally, a string argument is followed by a variable, so that the user input area follows thedisplayed literal.fAny of the following format control codes. When used with user input from the keyboard,these controls determine where a specified string or the user input area will appear on thescreen.! starts a new line. You may specify multiple exclamation points# starts a new page. On a terminal, it clears the current screen and starts at the top of the newscreen.?n positions at the nth column location, where n is a positive integer./keyword(parameters) A device control mnemonic. Performs a device-specific operation,such as positioning the cursor on a video terminal or rewinding a magnetic tape. The slashcharacter (/) is followed by a keyword, which is optionally followed by one or more parametersenclosed in parentheses. Multiple parameters are separated by commas. The keyword is anentrypoint label into the current device's mnemonic space routine.You can establish the default mnemonic space for a device type in either of the followingways:• Go to the System Management Portal, select System Configuration, select AdvancedSettings, on the pull-down Category list select IO. Select either MnemonicMagTape,MnemonicOther, MnemonicSeqFile, or MnemonicTerminal. For the desired device type,click “edit” to display and edit its mnemonic space setting.• Include the /mnemonic space parameter in the OPEN or USE command for the device.You can specify multiple format controls. For example: #!!!?20 means to start at the top ofa new page (or screen), go down three lines, and then position to column 20.118 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


READtimeoutThe number of seconds to wait for the request to succeed. This argument is optional, but ifspecified, the preceding colon is required. You must specify timeout as an integer or anexpression that evaluates to an integer. The timeout argument sets the $TEST special variableas follows:• READ with timeout argument completes successfully (does not time out): $TEST setto 1.• READ with timeout argument times out: $TEST set to 0.• READ with no timeout argument: $TEST remains set to its previous value.If the timeout period expires before the READ completes and some characters have beeninput (for a variable-length or fixed-length reads) the input characters are stored in variable.If no characters have been input (for a variable-length or fixed-length reads), <strong>Caché</strong> definesvariable (if necessary) and sets it to the null string. If no character has been input for a singlecharacterREAD, <strong>Caché</strong> defines variable (if necessary) and sets it to –1.ExamplesThe following example uses the variable-length form of READ to acquire any number ofcharacters from the user. The format control ! starts the prompt on a new line.READ !,"Enter your last name: ",lnameThe following example uses the single-character form of READ to acquire one characterfrom the user and store it as its ASCII decimal equivalent.READ !,"Enter option number (1,2,3,4): ",*optWRITE !,"ASCII value input=",optWRITE !,"Character input=",$KEYThe following example uses the fixed-length form of READ to acquire exactly three charactersfrom the user.READ !,"Enter your 3-digit area code: ",area#3The following example prompts for three parts of a name: a fixed-length given name (gname)of up to 12 characters, a fixed-length (one-character) middle initial (iname), and a familyname (fname) of any length. The gname and iname variables are coded to time out after 10seconds:READ "Given name:",gname#12:10,!,"Middle initial:",iname#1:10,!,"Family name:",fnameWRITE $TEST<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 119


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsA timeout of a read operation causes the READ command to proceed to the next read operation.The first two read operations set $TEST whether or not they time out. The third readoperation does not set $TEST, so the value of $TEST in this example reflects the result(success or timeout) of the second read operation.The following example uses indirection to dynamically change the prompt associated withthe READ command:PromptChoiceSET MESS(1)="""ENTER A NUMBER:"""SET MESS(2)="""ENTER A NAME:"""READ "Type 1 for numbers or 2 for names:",p,#!!!!SET a=1DataInputREAD !,@MESS(p),x(a)SET a=a+1GOTO DataInputThe following example sets the length of a fixed-length read based on the value of the firstnumber input:STRTLOOPNotesREAD "ENTER LARGEST NUMBER (and press return): ",val(1)IF val(1)>99 { SET ibuf=3 }ELSEIF val(1)>9 { SET ibuf=2 }ELSE { SET ibuf=1 }SET x=2READ !,"ENTER NEXT NUMBER: ",val(x)#ibufSET x=x+1GOTO LOOPREAD Uses the Current DeviceREAD inputs character-oriented data from the current I/O device. You must open a devicewith the OPEN command, then establish it as the current device with the USE command.<strong>Caché</strong> maintains the current device ID in the $IO special variable.While the most common use for READ is to acquire user input from the keyboard, you canalso use it to input characters from any byte-oriented device, such as a magnetic tape, asequential disk file, or a communications buffer.READ Terminators<strong>Caché</strong> terminates a read operation when the input string reaches the specified length (forsingle-character READ and fixed-length READ). For a variable-length READ, <strong>Caché</strong> terminatesreading if the input string reaches the maximum string length for the current process.<strong>Caché</strong> also terminates reading when it encounters certain terminator characters. The terminatorsare determined by the device type. For example, with terminals, the default terminators are120 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


RETURN (also known as the key) (ASCII 13), LINE FEED (ASCII 10), and ESCAPE(ASCII 27).You can modify the terminator default when you issue an OPEN or USE command for adevice. OPEN and USE allow you to specify a terminator parameter value. See I/O Devicesand Commands in the <strong>Caché</strong> I/O Device Guide for details about terminators based on devicetype.<strong>Caché</strong> does not store the input terminator with the input value for variable-length and fixedlengthreads; it records it in the $KEY and $ZB special variables. <strong>Caché</strong> does store the inputterminator (if specified) as the input value for a single-character read.Timeout and the $ZA, $ZB, and $TEST Special VariablesREAD<strong>Caché</strong> records the completion status of a READ in the $TEST, $ZA, and $ZB special variables,as follows:<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 121


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsType of READVariable data$TESTvalue$ZAvalue$ZB valueVariable, ended withline returninput characters (ornull string if none)10terminatorcharacterVariable, some input,then timeoutinput characters02null stringVariable, no input,timeoutnull string02null stringFixed, all charsenteredinput characters10the lastcharacterenteredFixed, line returninput characters (ornull string if none)10terminatorcharacterFixed, timed outinput characters (ornull string if none)02null stringSingle character, datainputASCII value of inputcharacter10the inputcharacterSingle character,terminator characterinputASCII value ofterminator character10,256terminatorcharacterSingle character,timed out–102null string$ZB and $KEYThe $ZB and $KEY special variables return the exact same value for every type of read,except one. When you perform a fixed-length read and input the specified number of characters,the READ completes without a terminator. In this case, $ZB contains the last characterinput (the terminating character), and $KEY contains the null string (there being no terminatorcharacter).InterruptsIf a read operation is interrupted, variable reverts to its previous state. For example, if youinput several characters for a read operation, and then issue a interrupt, variablereverts to its state prior to the read operation. That is, if it was undefined, it remains undefined;if it had a previous value, it contains the previous value. This behavior is completely different122 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


than a read operation that times out. A read timeout retains the new state of variable,including any characters input before the timeout occurred. If a READ command containsmultiple read operations, the interrupt affects only the read operation in progress. To commitor revert multiple read operations as a unit, use transaction processing.Reading from Non-Keyboard DevicesAs described earlier, READ can be used to acquire input from any character-oriented device.This includes devices such as magnetic tapes and sequential disk files, as well terminal keyboards.However, you must first establish the device to read from as the current device withthe OPEN and USE commands.With non-keyboard devices, you can use any of the three available forms (variable-length,single-character, and fixed-length). The choice of which form to use in any given case dependson the type of terminator available. With fixed-length READ, <strong>Caché</strong> treats terminatorsencountered within the input string the same as any other character.For example, if you are reading from a device that presents data in a line-oriented formatwith CARRIAGE RETURN/LINE FEED as the line terminator, you can use the variablelengthform. In this case, <strong>Caché</strong> reads each line into variable in its entirety, terminating inputonly when it reaches the Return (ASCII code 13) at the end of the line. (Remember, from theuser input examples shown previously, that is the input terminator.)On the other hand, if you are reading from a magnetic tape that presents records as a seriesof fixed-length fields, you would use the fixed-length (variable#n) form. For example, assumethat you have a mag tape that uses a record format consisting of four fields of up to 8, 12, 4,and 6 characters, respectively. You might use code similar to the following to read in thedata:READ field1#8,field2#12,field3#4,field4#6In this case, the #n value sets the input terminator for each field.READWhich terminator is used for a given device can be set by the device parameters that youspecify for that device on the OPEN or USE command.When reading block-oriented data from magnetic tape, the $ZB special variable contains thenumber of bytes remaining in the I/O buffer. Its function is entirely different than its usewhen reading character-oriented data. $ZB does not contain the read terminator character orthe last input character during block-oriented I/O. Refer to $ZB for further details.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 123


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsReading Non-Printing CharactersNon-printing characters are characters outside the standard range of ASCII printable characters.In other words, they are characters whose ASCII codes are less than ASCII 32 or greater thanASCII 127. They are characters that have no single key equivalents on a standard keyboard.The characters whose codes are less than ASCII 32 are usually used for control operations.They can be entered only in conjunction with the CTRL key. For example, ETX (ASCII 3)is entered as and is used to assert a BREAK when entered from the keyboard.The characters whose codes are greater than ASCII 127 are usually used for graphics operations.As a rule, they cannot be entered from the keyboard, but they can be read from othertypes of devices. For example, ASCII 179 produces the vertical line character.You can use the READ command to input non-printing characters as well as the standardASCII printable characters. However, you must include code to handle the escape sequenceused for each such character. An escape sequence is a sequence of characters that starts withthe ESC character (ASCII 27). For example, you can code a READ so that the user is allowedto press a function key as a valid input response. Pressing the function key produces an escapesequence that can be different for different types of terminals.<strong>Caché</strong> <strong>ObjectScript</strong> supports input of escape sequences by storing them in the $ZB and $KEYspecial variables, rather than in the specified variable. For example, for a function key press,<strong>Caché</strong> stores the ESC code (ASCII 27) in $ZB and $KEY. To handle an escape sequence,you must include code that tests the current value in $ZB or $KEY after each READ becausesubsequent reads update these special variables and overwrite any previous value. ($ZB and$KEY are very similar, but not identical; see $KEY for details.) To display a non-printingcharacter, such as an escape sequence, use the ZZDUMP command or the $ASCII function.Sequential File End-of-FileThe behavior of READ when encountering an end-of-file for a sequential file depends onthe system-wide default. Go to the System Management Portal, select System Configuration,select Advanced Settings, on the pull-down Category list select <strong>ObjectScript</strong>. View and editthe current setting of SetZEOF. This option controls the behavior when <strong>Caché</strong> encounters anunexpected end-of-file when reading a sequential file. When set to “true” , <strong>Caché</strong> sets the$ZEOF special variable to indicate that you have reached the end of the file. When set to“false” , <strong>Caché</strong> issues an error. The default is “false” .Setting $ZUTIL(69,40) overrides this default system-wide; it does not change the SystemConfiguration setting. Setting $ZUTIL(68,40) overrides the system-wide setting for thecurrent process.124 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


See Also• OPEN command• WRITE command• ZZDUMP command• USE command• $KEY special variable• $TEST special variable• $ZA special variable• $ZB special variable• $ZEOF special variable• Terminal I/O in <strong>Caché</strong> I/O Device Guide• Magnetic Tape I/O in <strong>Caché</strong> I/O Device Guide• Sequential File I/O in <strong>Caché</strong> I/O Device GuideREAD<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 125


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsSETAssigns a value to a variable.SET:pc setargument,...S:pc setargument,...where setargument can be:variable=value(variable-list)=valueArgumentspcvariablevariable-listvalueOptional — A postconditional expression.The variable to set to the corresponding value. variable can bea local variable, a process-private global, a global, or specialvariable. (Not all special variables can be set by an application;see documentation of individual special variables.)A comma-separated list, enclosed in parentheses, that consistsof one or more variable arguments. All of the variablearguments in variable-list are assigned the same value.A literal value, or any valid <strong>Caché</strong> <strong>ObjectScript</strong> expression thatevaluates to a value.126 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


DescriptionThe SET command assigns a value to a variable. It can set a single variable, or set multiplevariables using any combination of two syntactic forms. It can assign values to variables byspecifying a comma-separated list of variable=value pairs. For example:SET a=1,b=2,c=3It can assign the same value to multiple variables by specifying a comma-separated list ofvariables enclosed in parentheses. For example:SET (a,b,c)=1You can combine these two syntactic forms in any combination. For example:SET (a,b)=1,c=2,(d,e,f)=3The maximum number of assignments you can perform with a single invocation of SET is128.If a specified variable does not exist, SET creates it and assigns the value. If a specifiedvariable exists, SET replaces the previous value with the specified value.A value can be a literal or an expression that evaluates to a value.ArgumentspcAn optional postconditional expression. <strong>Caché</strong> executes the command if the postconditionalexpression is true (evaluates to a non-zero numeric value). <strong>Caché</strong> does not execute the commandif the postconditional expression is false (evaluates to zero). For further details, referto Command Postconditional Expressions in Using <strong>Caché</strong> <strong>ObjectScript</strong>.variableSETThe variable to receive the value resulting from the evaluation of value. It can be a localvariable, a process-private global, a global variable, or a special variable. A local variable,process-private global, or global variable can be either subscripted or unsubscripted. A globalvariable can be specified with extended global reference (see Global Structure in Using <strong>Caché</strong>Multi-Dimensional Storage).Local variables, process-private globals, and special variables are specific to the currentprocess; they are mapped to be accessible from all namespaces. A global variable persistsafter the process that created it terminates. A global is specific to the namespace in which it<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 127


<strong>Caché</strong> <strong>ObjectScript</strong> Commandswas created. By default, a SET assigns a global in the current namespace. You can use SETto define a global (^myglobal) in another namespace (samples) by using syntax such as thefollowing: SET ^[“samples”]myglobal="Ansel Adams”.A variable can be a piece or segment of a variable as specified in the argument of a $PIECEor $EXTRACT function.Note that you can assign values to only certain special variables. See the reference pages forindividual special variables for further details.valueA literal value or any valid <strong>Caché</strong> <strong>ObjectScript</strong> expression. Usually a value is a numeric orstring expression.• A numeric value is converted to canonical form before assignment: leading and trailingzeros, a plus sign or a trailing decimal point are removed. Any exponentiation or specifiedarithmetic operations are performed.• A string value is enclosed in quotation marks. A string is assigned unchanged, exceptthat doubled quotation marks within the string are converted to a single quotation mark.The null string ("") is a valid value.• A numeric value enclosed in quotation marks is not converted to canonical form and noarithmetic operations are performed before assignment.• If a relational or logical expression is used, <strong>Caché</strong> assigns the truth value (0 or 1) resultingfrom the expression.• Object properties and object methods that return a value are valid expressions. Use the.. syntax for assigning a property or method value to a variable.ExamplesThe following example illustrates how you can specify multiple arguments for the same SETcommand. Specifically, the command assigns values to three variables. note that argumentsare evaluated in left-to-right order.SET var1=12,var2=var1*3,var3=var1+var2WRITE "var1=",var1,!,"var2=",var2,!,"var3=",var3The following example shows the (variable-list)=value form of the SET command. Itshows how to assign the same value to multiple variables. Specifically, the command assignsthe value 0 to three variables.SET (sum,count,average)=0WRITE "sum=",sum,!,"count=",count,!,"average=",average128 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


The following example shows setting a subscripted global variable in a different namespaceusing extended global reference.ZNSPACE "user"SET ^["samples"]name(1)="fred"ZNSPACE "samples"WRITE ^name(1)SET Command with ObjectsThe following example sets x to the value of an object property:SET x=person.LastNamewhere person is the object reference, and LastName is the object property name. Note thatdot syntax is used in object expressions; a dot is placed between the object reference and theobject property name or object method name.To set a variable with an object property or object method value for the current object, usethe double-dot syntax:SET x=..LastNameFor further details, refer to Object-Specific <strong>ObjectScript</strong> Features in Using <strong>Caché</strong> Objects.When using SET with objects, do not perform multiple assignments. For example, avoidstatements such as:// Avoid this syntax:SET (a.Name,b.Name)=zInstead, issue a separate SET command for each assignment, as shown in the followingexample:SET a.Name=zSET b.Name=zThe following command sets x to the value returned by the object method TotalLines():SET x=invoice.TotalLines()A SET command for objects can take an expression with cascading dot syntax, as shown inthe following examples:SET x=patient.Doctor.Hospital.NameSETIn this example, the patient.Doctor object property references the Hospital object, whichcontains the Name property. Thus, this command sets x to the name of the hospital affiliated<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 129


<strong>Caché</strong> <strong>ObjectScript</strong> Commandswith the doctor of the specified patient. The same cascading dot syntax can be used withobject methods.A SET command for objects can be used with system-level methods, such as the followingdata type property method:SET x=patient.NameIsValid(name)In this example, the NameIsValid() property method returns its result for the current patientobject. NameIsValid() is a boolean method generated for data type validation of the Nameproperty. Thus, this command sets x to 1 if the specified name is a valid name, and sets x to0 if the specified name is not a valid name.NotesEach variable assignment can be a local variable, a process-private global, or a global, the$PIECE function, the $EXTRACT function, and certain special variables, including$DEVICE, $X, $Y, $KEY, $ECODE, and $ETRAP.If the target variable does not already exist, SET creates it and then assigns the value. If itdoes exist, SET replaces the existing value with the assigned value.SET and SubscriptsYou can set individual subscripted values (array nodes) for a local variable, process-privateglobal, or a global. You can set subscripts in any order. If the variable subscript level doesnot already exist, SET creates it and then assigns the value. Each subscript level is treated asan independent variable; only those subscript levels set are defined. For example:KILL myarraySET myarray(1,1,1)="Cambridge"WRITE !,myarray(1,1,1)SET myarray(1)="address"WRITE !,myarray(1)In this example, the variables myarray(1,1,1) and myarray(1) are defined and contain values.However, the variables myarray and myarray(1,1) are not defined, and return an error when invoked. For further information on subscripted variables, refer to GlobalStructure in Using <strong>Caché</strong> Multi-Dimensional Storage.Order of Evaluation<strong>Caché</strong> evaluates the arguments of the SET command in strict left-to-right order. For eachargument, it perform evaluation in the following sequence:130 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


1. Evaluates occurrences of indirection or subscripts to the left of the equal sign in a leftto-rightorder to determine the variable name(s). For more information, refer to Indirectionin Using <strong>Caché</strong> <strong>ObjectScript</strong>.2. Evaluates the expression to the right of the equal sign.3. Assigns the expression to the right of the equal sign to the variable name or referencesto the left of the equal sign.Defined and Undefined VariablesMost <strong>Caché</strong> commands and functions require that a variable be defined before it is referenced.Attempting to reference an undefined variable generates an error.Attempting to reference an undefined object generates a or error. Refer to $ZERROR for further details on theseerror codes.The READ command and the $INCREMENT function can reference an undefined variableand assign a value to it. The $DATA function can take an undefined or defined variable andreturn its status. The $GET function returns the value of a defined variable; optionally, it canalso assign a value to an undefined variable.SET with $PIECE and $EXTRACTYou can use the $PIECE and $EXTRACT functions with SET on either side of the equalssign. For detailed descriptions, refer to $PIECE and $EXTRACT.When used on the right side of the equals sign, $PIECE and $EXTRACT extract a substringfrom a variable and assign its value to the specified variable(s) on the left side of the equalssign. $PIECE extracts a substring using a specified delimiter, and $EXTRACT extracts asubstring using a character count.For example, assume that variable x contains the string "HELLO WORLD". The followingcommands extract the substring "HELLO" and assign it to variables y and z, respectively:SET x="HELLO WORLD"SET y=$PIECE(x," ",1)SET z=$EXTRACT(x,1,5)WRITE "x=",x,!,"y=",y,!,"z=",zSETWhen used on the left side of the equals sign, $PIECE and $EXTRACT insert the valuefrom the expression on the right side of the equals sign into the specified portion of the targetvariable. Any existing value in the specified portion of the target variable is replaced by theinserted value.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 131


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsFor example, assume that variable x contains the string "HELLO WORLD" and that variabley contains the string "HI THERE". In the command:SET x="HELLO WORLD"SET y="HI THERE"SET $PIECE(x," ",2)=$EXTRACT(y,4,9)WRITE "x=",xThe $EXTRACT function extracts the string "THERE" from variable y and the $PIECEfunction inserts it into variable x at the second field position, replacing the existing string"WORLD". Variable x now contains the string "HELLO THERE".If the target variable does not exist, <strong>Caché</strong> creates it and pads it with delimiters (in the caseof $PIECE) or with spaces (in the case of $EXTRACT) as needed.For example, assume that x contains the string "HELLO WORLD" and that y contains thestring "THERE". The following command inserts the value of y in positions 7 through 11 ofx:SET x="HELLO WORLD"SET y="THERE"SET $EXTRACT(x,7,11)=yWRITE "x=",xVariable x now contains the string "HELLO THERE".In the following example, assume that the global array ^client is structured so that the rootnode contains the client's name, with subordinate nodes containing the street address andcity. For example, ^client(2,1,1) would contain the city address for the second client storedin the array.Assume further that the city node (x,1,1) contains field values identifying the city, stateabbreviation, and ZIP code (postal code), with the comma as the field separator. For example,a typical city node value might be "Cambridge,MA,02142". The three SET commands in thefollowing code each use the $PIECE function to assign a specific portion of the array nodevalue to the appropriate local variable. Note that in each case $PIECE references the comma(",") as the string separator.ADDRESSPIECESET ^client(2,1,1)="Cambridge,MA,02142"SET city=$PIECE(^client(2,1,1),",",1)SET state=$PIECE(^client(2,1,1),",",2)SET zip=$PIECE(^client(2,1,1),",",3)WRITE "City is ",city,!,"State or Province is ",state,!,"Postal code is ",zipQUITThe $EXTRACT function could be used to perform the same operation, but only if the fieldswere fixed length and the lengths were known. For example, if the city field was known to132 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


contain only up to 9 characters and the state and ZIP fields were known to contain only 2 and5 characters, respectively, the SET commands could be coded with the $EXTRACT functionas follows:ADDRESSEXTRACTSET ^client(2,1,1)="Cambridge,MA,02142"SET city=$EXTRACT(^client(2,1,1),1,9)SET state=$EXTRACT(^client(2,1,1),11,12)SET zip=$EXTRACT(^client(2,1,1),14,18)WRITE "City is ",city,!,"State or Province is ",state,!,"Postal code is ",zipQUITNotice the gaps between 9 and 11 and 12 and 14 to accommodate the comma field separators.The following example replaces the first substring in A (originally set to 1) with the string"abc".StringPieceSET A="1^2^3^4^5^6^7^8^9"SET $PIECE(A,"^")="abc"WRITE !,"A=",AQUITA="abc^2^3^4^5^6^7^8^9"The following example uses $EXTRACT to replace the first character in A (again, a 1) withthe string "abc".StringExtractSET A="123456789"SET $EXTRACT(A)="abc"WRITE !,"A=",AQUITA="abc23456789"The following example replaces the third through sixth pieces of A with the string "abc" andreplaces the first character in the variable B with the string "abc".StringInsertSET A="1^2^3^4^5^6^7^8^9"SET B="123"SET ($PIECE(A,"^",3,6),$EXTRACT(B))="abc"WRITE !,"A=",A,!,"B=",BQUITA="1^2^abc^7^8^9"B="abc23"SET<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 133


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsThe following example sets $X, $Y, $KEY, and the fourth piece of a previously undefinedlocal variable, A, to the value of 20. It also sets the local variable K to the current value of$KEY. A includes the previous three pieces and their caret delimiter (^).SetVarsSET ($X,$Y,$KEY,$PIECE(A,"^",4))=20,X=$X,Y=$Y,K=$KEYWRITE !,"A=",A,!,"K=",K,!,"X=",X,!,"Y=",YQUITA="^^^20" K="20" X=20 Y=20The following example sets $ECODE and $ETRAP to the null string. Then, the examplesets the local variables EC and ET to the values of $ECODE and $ETRAP.SetEvarsSET ($ECODE,$ETRAP)="",EC=$ECODE,ET=$ETRAPWRITE "EC=",EC,!,"ET=",ETQUITEC=""ET=""SET with $LIST and $LISTBUILD<strong>Caché</strong> includes several functions that allow you to manipulate lists more quickly and easilythan you can with $PIECE or $EXTRACT. These functions are:• $LIST• $LISTBUILDThese functions do not use delimiters when they create or manipulate lists. Instead, theyencode the length (and type) of each element within the list itself. They then use the encodedlength specifications to extract specified list elements during list manipulation. Because the$LIST functions do not use delimiter characters, the lists created using these functions shouldnot be input to $PIECE or other character-delimiter functions.When used on the right side of the equal sign, these functions return the following:$LIST$LIST returns the specified element of the specified list.$LISTBUILD$LISTBUILD returns a list containing one element for each argument given.When used on the left side of the equal sign, in a SET argument, these functions perform thefollowing tasks:134 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$LISTReplaces the specified element with the value given on the right side of the equal sign.$LISTBUILDExtracts several elements of a list in a single operation. The arguments of $LISTBUILD arevariables, each of which receives an element of the list corresponding to their position in the$LISTBUILD parameter list. Variable names may be omitted for positions that are not ofinterest.In the following example, $LISTBUILD (on the right side of the equal sign) is first used toreturn a list. Then $LISTBUILD (on the left side of the equal sign) is used to extract twoitems from that list and set the appropriate variables.SetListBuildSET J=$LISTBUILD("red","blue","green","white")SET $LISTBUILD(A,,B)=JWRITE "A=",A,!,"B=",BIn this example, A="red" and B="green".See Also• $LIST function• $LISTBUILD function• $EXTRACT function• $PIECE function• $X special variable• $Y special variableTCOMMITTCOMMITMarks the successful completion of a transaction.TCOMMIT:pcTC:pcArgumentspcOptional — A postconditional expression.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 135


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsDescriptionTCOMMIT marks the successful end of a transaction initiated by the corresponding TSTART.TCOMMIT decrements the value of the $TLEVEL special variable. <strong>Caché</strong> terminates thetransaction only if $TLEVEL goes to 0. Usually this is when TCOMMIT has been calledas many times as TSTART. Changes made during nested transactions are not committeduntil $TLEVEL=0.Calling TCOMMIT when $TLEVEL is already 0 results in a error. Thiscan occur if you issue a TCOMMIT when no transaction is in progress, when the numberof TCOMMIT commands is larger than the number of TSTART commands, or followinga TROLLBACK command.ArgumentspcAn optional postconditional expression. <strong>Caché</strong> executes the command if the postconditionalexpression is true (evaluates to a non-zero numeric value). <strong>Caché</strong> does not execute the commandif the postconditional expression is false (evaluates to zero). For further details, referto Command Postconditional Expressions in Using <strong>Caché</strong> <strong>ObjectScript</strong>.ExamplesYou use TCOMMIT with the TROLLBACK and TSTART commands. See TROLLBACKand TSTART for examples of how to use these transaction processing commands together.NotesNested TSTART / TCOMMIT<strong>Caché</strong> supports the nesting of the TSTART/TCOMMIT commands, so that modules canissue their TSTART/TCOMMIT pairs correctly, independent of any otherTSTART/TCOMMIT issued in the modules that called them or in the modules they call.The current nesting level of the transaction is tracked by the special variable $TLEVEL. Thetransaction is committed when the outermost matching TCOMMIT is issued; that is, when$TLEVEL goes back to 0.You can roll back individual nested transactions by calling TROLLBACK 1 or roll back allcurrent transactions by calling TROLLBACK. TROLLBACK rolls back the whole transactionthat is in effect — no matter how many levels of TSTART were issued — and sets$TLEVEL to 0.136 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


TCOMMITNetwork TransactionsTo synchronize the completion of transactions over a network, use the ZSYNC command.Synchronous CommitA TCOMMIT command requests a flush of the journal data involved in that transaction todisk. Whether to wait for this disk write operation to complete is a configurable option.Go to the System Management Portal, select Configuration, then select Advanced Settings.On the pull-down Category list select Transactions. View and edit the current setting ofSynchronousCommit. When set to “true” , TCOMMIT does not complete until the journaldata write operation completes. When set to “false” , TCOMMIT does not wait for the writeoperation to complete. The default is “false” .SQL and Transactions<strong>Caché</strong> <strong>ObjectScript</strong> transaction processing, using TSTART and TCOMMIT, differs from,and is incompatible with, SQL transaction processing using the SQL statements STARTTRANSACTION and COMMIT. <strong>Caché</strong> <strong>ObjectScript</strong> transaction processing provides limitedsupport for nested transactions; SQL transaction processing supports savepoints withintransactions. An application should use one type of transaction processing throughout, andnot attempt to mix the two.See Also• TROLLBACK command• TSTART command• $TLEVEL special variable• Using <strong>ObjectScript</strong> for Transaction Processing in Using <strong>Caché</strong> <strong>ObjectScript</strong><strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 137


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsTROLLBACKRolls back an unsuccessful transaction.TROLLBACK:pcTRO:pcTROLLBACK:pc 1TRO:pc 1Argumentspc1Optional — A postconditional expression.Optional — Rolls back one level of nesting.DescriptionTROLLBACK terminates the current transaction and restores all journaled database valuesto the values they held at the start of the transaction. TROLLBACK has two forms:• TROLLBACK rolls back all transactions in progress (no matter how many levels ofTSTART were issued) and resets $TLEVEL to 0.• TROLLBACK 1 rolls back the current level of nested transactions (the one initiated bythe most recent TSTART) and decrements $TLEVEL by 1.You can determine the level of nested transactions from the $TLEVEL special variable.Calling TROLLBACK when $TLEVEL is 0 has no effect.You can use the $ZUTIL(78,21) function to search the journal file for TSTART commands,and thus identify open transactions. A TSTART increments $TLEVEL and writes a journalfile record: either a “BT” (Begin Transaction) record if $TLEVEL was zero, or a “BTL”(Begin Transaction with Level) record if $TLEVEL was greater than 0.Use the $ZUTIL(78,29) function to flush the journal buffer following a successful rollbackoperation.Transaction Rollback LoggingIf an error occurs during a roll back operation, <strong>Caché</strong> issues a error message,and logs an error message in the operator console log file.By default, the operator console log file is cconsole.log in the <strong>Caché</strong> system managementdirectory (Mgr). This default is configurable. Go to the System Management Portal, select138 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


Configuration, then select Advanced Settings. On the pull-down Category list select Miscellaneous.View and edit the current setting of ConsoleFile. By default this setting is blank,routing console messages to cconsole.log. If you change this setting, you must restart <strong>Caché</strong>for this change to take effect.SQL and Transactions<strong>Caché</strong> <strong>ObjectScript</strong> transaction processing, using TSTART and TCOMMIT orTROLLBACK, differs from, and is incompatible with, SQL transaction processing usingthe SQL statements START TRANSACTION, and COMMIT or ROLLBACK. An applicationshould use one type of transaction processing throughout, and not attempt to mix thetwo.<strong>Caché</strong> <strong>ObjectScript</strong> transaction processing provides limited support for nested transactions.SQL transaction processing supplies support for savepoints within transactions.Variables and $INCREMENTTROLLBACK rolls back all journaled operations. However, not all changes made by anapplication are journaled.• TROLLBACK rolls back changes to global variables.• TROLLBACK does not roll back $INCREMENT (or $ZINCREMENT) changes toglobal variables.• TROLLBACK does not roll back changes to local variables or process-private globals.Globals and TROLLBACK 1TROLLBACK 1 rolls back and restores all globals changed within its nested transaction.However, if globals are changed that are mapped to a remote system that does not supportnested transactions, these changes are treated as occurring at the outermost nested level. Suchglobals are only rolled back when a rollback resets $TLEVEL to 0, either by callingTROLLBACK or by calling TROLLBACK 1 when $TLEVEL=1.Locks and TROLLBACK 1TROLLBACKTROLLBACK 1 restores all locks to their state prior to the corresponding TSTART. Thatis, it releases all locks created during its nested transaction, and restores all pre-existing locksto their state prior to its nested transaction. A TCOMMIT of a nested transaction does notrelease the corresponding locks, so a subsequent TROLLBACK can effect locks in a committedsub-transaction.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 139


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsArgumentspcAn optional postconditional expression. <strong>Caché</strong> executes the command if the postconditionalexpression is true (evaluates to a non-zero numeric value). <strong>Caché</strong> does not execute the commandif the postconditional expression is false (evaluates to zero). For further details, referto Command Postconditional Expressions in Using <strong>Caché</strong> <strong>ObjectScript</strong>.ExamplesThe following example shows the effects of TROLLBACK on nested transactions. EachTSTART increments $TLEVEL and sets a global. Issuing a TCOMMIT on the inner nestedtransaction decrements $TLEVEL, but the commitment of changes made in a nested transactionis deferred. In this case, the subsequent TROLLBACK on the outer transaction rollsback all changes made, including those in the inner “committed” nested transaction.SET ^a(1)="[- - -]",^b(1)="[- - -]"WRITE !,"level:",$TLEVEL," ",^a(1)," ",^b(1)TSTARTLOCK +^a(1)SET ^a(1)="hello"WRITE !,"level:",$TLEVEL," ",^a(1)," ",^b(1)TSTARTLOCK +^b(1)SET ^b(1)="world"WRITE !,"level:",$TLEVEL," ",^a(1)," ",^b(1)TCOMMITWRITE !,"After TCOMMIT"WRITE !,"level:",$TLEVEL," ",^a(1)," ",^b(1)TROLLBACKWRITE !,"After TROLLBACK"WRITE !,"level:",$TLEVEL," ",^a(1)," ",^b(1)QUITThe following example shows how TROLLBACK rolls back global variables, but not localvariables:140 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


TROLLBACKSET x="default",^y="default"WRITE !,"level:",$TLEVELWRITE !,"local:",x," global:",^yTSTARTSET x="first",^y="first"WRITE !,"TSTART level:",$TLEVELWRITE !,"local:",x," global:",^yTSTARTSET x=x_" second",^y=^y_" second"WRITE !,"TSTART level:",$TLEVELWRITE !,"local:",x," global:",^yTSTARTSET x=x_" third",^y=^y_" third"WRITE !,"TSTART level:",$TLEVELWRITE !,"local:",x," global:",^yTROLLBACKWRITE !!,"After Rollback:"WRITE !,"TROLLBACK level:",$TLEVELWRITE !,"local:",x," global:",^yThe following example shows how $INCREMENT changes to a global are not rolled back.SET ^x=-1,^y=0WRITE !,"level:",$TLEVELWRITE !,"Increment:",$INCREMENT(^x)," Add:",^yTSTARTSET ^y=^y+1WRITE !,"level:",$TLEVELWRITE !,"Increment:",$INCREMENT(^x)," Add:",^yTSTARTSET ^y=^y+1,^z=^z_" second"WRITE !,"level:",$TLEVELWRITE !,"Increment:",$INCREMENT(^x)," Add:",^yTSTARTSET ^y=^y+1,^z=^z_" third"WRITE !,"level:",$TLEVELWRITE !,"Increment:",$INCREMENT(^x)," Add:",^yTROLLBACKWRITE !!,"After Rollback"WRITE !,"level:",$TLEVELWRITE !,"Increment:",^x," Add:",^yThe following example transfers money from one account to another as a transaction usingprimitive error checking:Transfer(from,to,amount)// Transfer funds from one account to anotherIF ('$Data(^ACCOUNT(from,"Balance"))) {QUIT "FROM account does not exist."}TSTARTSET ^ACCOUNT(from,"Balance")=^ACCOUNT(from,"Balance")-amountIF ('$Data(^ACCOUNT(from,"Balance"))) {TROLLBACKQUIT "TO account does not exist."}SET ^ACCOUNT(to,"Balance")=^ACCOUNT(to,"Balance")+amountTCOMMITQUIT 1<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 141


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsSee Also• TCOMMIT command• TSTART command• $TLEVEL special variable• Using <strong>ObjectScript</strong> for Transaction Processing in Using <strong>Caché</strong> <strong>ObjectScript</strong>TSTARTMarks the beginning of a transaction.TSTART:pcTS:pcArgumentspcOptional — A postconditional expression.DescriptionTSTART marks the beginning of a transaction. Following TSTART, database operationsare journaled to enable a subsequent TCOMMIT or TROLLBACK command.TSTART increments the value of the $TLEVEL special variable.Any locks issued within a transaction will be held until the end of the transaction even if thelock is released, unless the lock is specified as short-term. Refer to the LOCK command formore details.Nested TSTART / TCOMMIT<strong>Caché</strong> supports the nesting of the TSTART/TCOMMIT commands, so that modules canissue their TSTART/TCOMMIT pairs correctly, independent of any otherTSTART/TCOMMIT issued in the modules that called them or in the modules they call.The current nesting level of the transaction is tracked by the special variable $TLEVEL.Issuing a TCOMMIT for a nested transaction decrements $TLEVEL, but the actual commitmentof the nested transaction is deferred. A transaction is committed when the outermostmatching TCOMMIT is issued; that is, when $TLEVEL goes back to 0.142 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


You can issue a TROLLBACK 1 command to roll back the current level of nested transaction.You can issue a TROLLBACK to roll back the whole transaction, no matter how manylevels of TSTART were issued.You can use the $ZUTIL(78,21) function to search the journal file for TSTART commands,and thus identify open transactions. A TSTART writes either a “BT” (Begin Transaction)journal file record if $TLEVEL was zero, or a “BTL” (Begin Transaction with Level) journalfile record if $TLEVEL was greater than 0.The maximum number of levels of nested transactions is 255. Attempting to exceed thisnesting levels limit results in a error.SQL and Transactions<strong>Caché</strong> <strong>ObjectScript</strong> transaction processing, using TSTART and TCOMMIT, differs from,and is incompatible with, SQL transaction processing using the SQL statements STARTTRANSACTION and COMMIT. <strong>Caché</strong> <strong>ObjectScript</strong> transaction processing provides limitedsupport for nested transactions; SQL transaction processing does not support nested transactions.An application should use one type of transaction processing throughout, and not attemptto mix the two.ArgumentspcAn optional postconditional expression. <strong>Caché</strong> executes the TSTART command if the postconditionalexpression is true and does not execute the TSTART command if the postconditionalexpression is false. For further details, refer to Command Postconditional Expressionsin Using <strong>Caché</strong> <strong>ObjectScript</strong>.ExamplesTSTARTThe following example shows nested pairs of TSTART/TCOMMIT amd the effects ofTROLLBACK on nested transactions. Each TSTART increments $TLEVEL and sets a global.Issuing a TCOMMIT on the inner nested transaction decrements $TLEVEL, but the commitmentof changes made in a nested transaction is deferred. In this case, the subsequentTROLLBACK on the outer transaction rolls back all changes made, including those in theinner “committed” nested transaction.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 143


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsSET ^a(1)="[- - -]",^b(1)="[- - -]"WRITE !,"level:",$TLEVEL," ",^a(1)," ",^b(1)TSTARTLOCK +^a(1)SET ^a(1)="hello"WRITE !,"level:",$TLEVEL," ",^a(1)," ",^b(1)TSTARTLOCK +^b(1)SET ^b(1)="world"WRITE !,"level:",$TLEVEL," ",^a(1)," ",^b(1)TCOMMITWRITE !,"After TCOMMIT"WRITE !,"level:",$TLEVEL," ",^a(1)," ",^b(1)TROLLBACKWRITE !,"After TROLLBACK"WRITE !,"level:",$TLEVEL," ",^a(1)," ",^b(1)QUITThe following example transfers money from one account to another as a transaction:// Transfer funds from one account to anotherTransfer(from,to,amount) {TSTARTSET ^ACCOUNT(from,"Balance") = ^ACCOUNT(from,"Balance") - amountSET ^ACCOUNT(to,"Balance") = ^ACCOUNT(to,"Balance") + amountTCOMMITQUIT}See Also• TCOMMIT command• TROLLBACK command• $TLEVEL special variable• Using <strong>ObjectScript</strong> for Transaction Processing in Using <strong>Caché</strong> <strong>ObjectScript</strong>144 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


USEUSEEstablishes a device as the current device.USE:pc useargument,...U:pc useargument,...where useargument can bedevice:(parameters):"mnespace"ArgumentspcdeviceparametersmnespaceOptional — A postconditional expression.The device to be selected as the current device, specified by adevice ID or a device alias. A device ID can be an integer (a devicenumber), a device name, or the pathname of a sequential file. If astring, it must be enclosed with quotation marks.Optional — The list of parameters used to set device characteristics.The parameter list is enclosed in parentheses, and the parametersin the list are separated by colons. Parameters can either bepositional (specified in a fixed order in the parameter list) or keyword(specified in any order). A mix of positional and keyword parametersis permitted. The individual parameters and their positions andkeywords are highly device-dependent.Optional — The name of the mnemonic space that contains thecontrol mnemonics to use with this device, specified as a quotedstring.DescriptionUSE device establishes the specified device as the current device. The process must havealready established ownership of the device with the OPEN command.The current device remains current until you issue another USE command to select anotherowned device as the current device or until the process terminates.The USE command can establish as the current device such devices as terminal devices,magnetic tape devices, spool devices, TCP bindings, interprocess pipes, named pipes, andinter-job communications. The USE command can also be used to open a sequential file. Thedevice argument specifies the file pathname as a quoted string.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 145


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsThe parameters available with the USE command are highly device-dependent. In manycases the available parameters are the same as those available with the OPEN command;however, some device parameters can only be set using the OPEN command, and other canonly be set using the USE command.The USE command can specify more than one useargument, separated by commas. However,you can only have one current device at a time. If you specify more than one useargument,the device specified in the last useargument becomes the current device. This form of USEmay be used to set parameters for several devices, and then establish the last-named deviceas the current device.ArgumentspcAn optional postconditional expression. <strong>Caché</strong> executes the command if the postconditionalexpression is true (evaluates to a non-zero numeric value). <strong>Caché</strong> does not execute the commandif the postconditional expression is false (evaluates to zero). For further details, referto Command Postconditional Expressions in Using <strong>Caché</strong> <strong>ObjectScript</strong>.deviceThe device to be selected as the current device. Specify the same device ID (or other deviceidentifier) as you specified in the corresponding OPEN command. For more information onspecifying devices, refer to the OPEN command.parametersThe list of parameters used to set operating characteristics of the device to be used as thecurrent device. The enclosing parentheses are required if there is more than one parameter.(It's good programming practice to always use parentheses when you specify a parameter.)Note the required colon before the left parenthesis. Within the parentheses, colons are usedto separate multiple parameters.The parameters for a device can be specified using either positional parameters or keywordparameters. You can also mix positional parameters and keyword parameters within the sameparameter list.In most cases, specifying contradictory, duplicate, or invalid parameter values does not resultin an error. Wherever possible, <strong>Caché</strong> ignores inappropriate parameter values and takesappropriate defaults.The available parameters are, in many cases, the same as those supported for the OPENcommand. For sequential files, TCP devices, and interprocess communication pipes some146 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


parameters can only be set with the OPEN command; for sequential files some parameterscan only be set with the USE command. USE parameters are specific to the type of devicethat is being selected and to the particular implementation. The USE command keywordparameters are listed by device type in I/O Devices and Commands in the <strong>Caché</strong> I/O DeviceGuide.If you do not specify a list of USE parameters, <strong>Caché</strong> uses the device's default OPENparameters. The default parameters for a device are configurable. Go to the System ManagementPortal, select System Configuration, select Advanced Settings, on the pull-down Categorylist select Devices. Click “contents” to display the current list of devices. For the desireddevice, click “edit” to display its Open Parameter: option. Specify this value in the sameway you specify the OPEN command parameters, including the enclosing parentheses. Forexample, ("AVL":0:2048).Positional ParametersPositional parameters must be specified in a fixed sequence in the parameter list. You canomit a positional parameter (and receive the default value), but you must retain the colon toindicate the position of the omitted positional parameter. Trailing colons are not required;excess colons are ignored. The individual parameters and their positions are highly devicedependent.There are two types of positional parameters: values and letter code strings.A value can be an integer (for example, record size), a string (for example, host name), or avariable or expression that evaluates to a value.A letter code string uses individual letters to specify device characteristics for the openoperation. For most devices, this letter code string is one of the positional parameters. Youcan specify any number of letters in the string, and specify the letters in any order. Lettercodes are not case sensitive. A letter code string is enclosed in quotation marks; no spacesor other punctuation is allowed within a letter code string (exception: K and Y may be followedby a name delimited by backslashes: thus: K\name\). For example, when opening a sequentialfile, you might specify a letter code string of “ANDFW” (append to existing file, create newfile, delete file, fix-length records, write access.) The position of the letter code stringparameter, and the meanings of individual letters is highly device-dependent.Keyword ParametersUSEKeyword parameters can be specified in any sequence in the parameter list. A parameter listcan consist entirely of keyword parameters, or it can contain a mix of positional and keywordparameters. (Commonly, the positional parameters are specified first (in their correct positions)followed by the keyword parameters.) You must separate all parameters (positional or key-<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 147


<strong>Caché</strong> <strong>ObjectScript</strong> Commandsword) with a colon (:). A parameter list of keyword parameters has the following generalsyntax:USEdevice:(/KEYWORD1=value1:/KEYWORD2=value2:.../KEYWORDn=valuen):"mnespace"The individual parameters and their positions are highly device-dependent. As a general rule,you can specify the same parameters and values using either a positional parameter or akeyword parameter. You can specify a letter code string as a keyword parameter by usingthe /PARAMS keyword.mnespaceThe name of the mnemonic space that contains the device control mnemonics used by thisdevice. By default, <strong>Caché</strong> provides two mnemonic spaces: ^%XMAG for magnetic tapedevices, and ^%X364 (ANSI X3.64 compatible) for all other devices and sequential files.Default mnemonic spaces are assigned by device type.Go to the System Management Portal, select System Configuration, select Advanced Settings,on the pull-down Category list select IO. Select either MnemonicMagTape, MnemonicOther,MnemonicSeqFile, or MnemonicTerminal. For the desired device type, click “edit” to displayand edit its mnemonic space setting.A mnemonic space is a routine that contains entrypoints for the device control mnemonicsused by READ and WRITE commands. The READ and WRITE commands invoke thesedevice control mnemonics using the /mnemonic(params) syntax. These device controlmnemonics perform operations such a moving the cursor to a specified screen location orrewinding a magnetic tape.Use the mnespace argument to override the default mnemonic space assignment. Specify a<strong>Caché</strong> <strong>ObjectScript</strong> routine that contains the control mnemonics entrypoints used with thisdevice. The enclosing double quotes are required. Specify this option only if you plan to usedevice control mnemonics with the READ or WRITE command. If the mnemonic spacedoes not exist, <strong>Caché</strong> issues a error. For further details on mnemonic spaces,see I/O Devices and Commands in the <strong>Caché</strong> I/O Device Guide.ExamplesIn this example, the USE command sets the sequential file "STUDENTS" as the currentdevice and sets the file pointer so that subsequent reads begin at offset 256 from the start ofthe file.USE "STUDENTS":256148 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


USENote:Sequential file seeking with the USE command, such as that shown in the aboveexample, is not supported on OpenVMS systems.NotesDevice OwnershipDevice ownership is established with the OPEN command. The only exception is the principaldevice, which is assigned to the process and is usually the terminal at which you sign on. Ifthe device specified in the USE command is not owned by the process, <strong>Caché</strong> issues a error message.The Current DeviceThe current device is the device used for I/O operations by the READ and WRITE commands.The READ command acquires input from the current device and the WRITE commandsends output to the current device.<strong>Caché</strong> maintains the ID of the current device in the $IO special variable. If the USE requestis successful, <strong>Caché</strong> sets $IO to the ID of the specified device. The $ZUTIL(96,14) functionreturns the device type of the current device.The Principal DeviceThe special device number 0 (zero) refers to the principal device. Each process has oneprincipal device. <strong>Caché</strong> maintains the ID of the principal device in the $PRINCIPAL specialvariable. The principal device is automatically opened when you start up <strong>Caché</strong>. Initially, theprincipal device ($PRINCIPAL) and the current device ($IO) are the same.After you issue a USE command, your current device ($IO) is normally the one named inthe last USE command you executed.While many processes can have the same principal device, only one at a time can own it.After a process successfully issues an OPEN command for a device, no other process canissue OPEN for that device until the first process releases it, either by explicitly issuing aCLOSE command, by halting, or because that user ends the session.Although you can issue OPEN and USE for a device other than your principal device fromthe programmer prompt, each time <strong>Caché</strong> returns to the > prompt, it implicitly issues USE0. To continue using a device other than 0, you must issue a USE command in each line youenter at the > prompt.Your principal device automatically becomes your current device when you do any of thefollowing:<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 149


<strong>Caché</strong> <strong>ObjectScript</strong> Commands• Log on.• Issue a USE 0 command.• Cause an error when an error trap is not set.• Close the current device.• Return to programmer mode.• Exit <strong>Caché</strong> by issuing a HALT command.USE 0 implies an OPEN command to the principal device. If another process owns the device,this process hangs on the implicit OPEN as it does when it encounters any OPEN.Although USE 0 implies OPEN 0 for the principal device, issuing a USE command for anyother device that the process does not own (due to a previous OPEN command) produces a error.Note:While most <strong>Caché</strong> platforms allow you to close your principal input device, <strong>Caché</strong>for UNIX does not. Therefore, when a job that is the child of another job tries toperform I/O on your login terminal, it hangs until you log off <strong>Caché</strong>. At that time,the output may or may not appear.Using the Null Device (UNIX and OpenVMS)When you issue an OPEN and USE command to the null device (/dev/null on UNIX or NL:on OpenVMS), <strong>Caché</strong> treats the null device as a dummy device. Subsequent READ commandsimmediately return a null string (""). Subsequent WRITE commands immediately returnsuccess. No actual data is read or written. On UNIX-based systems, the device /dev/nullbypasses the UNIX open, write, and read system calls entirely.Processes started by other processes with the JOB command have a principal device of/dev/null or NL: by default.If you open /dev/null other than within <strong>Caché</strong> for example, by redirecting <strong>Caché</strong> output to/dev/null from the UNIX shell the UNIX system calls operate as they do for any other device.See Also• OPEN command• CLOSE command• $IO special variable• $PRINCIPAL special variable150 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


VIEW• $ZUTIL(96,14) Return current device type function• I/O Devices and Commands in <strong>Caché</strong> I/O Device Guide• Terminal I/O in <strong>Caché</strong> I/O Device Guide• Magnetic Tape I/O in <strong>Caché</strong> I/O Device Guide• Sequential File I/O in <strong>Caché</strong> I/O Device Guide• The Spool Device in <strong>Caché</strong> I/O Device GuideVIEWReads and writes blocks directly to disk storage and writes locations in memory.VIEW:pc viewargumentV:pc viewargumentwhere viewargument is:blockoffset:mode:length:newvalueArgumentspcblockoffsetmodelengthnewvalueOptional — An optional postconditional expression.A block location, specified as an integer.An offset, in bytes, from a base address within the memory regionspecified by mode.The memory region whose base address will be used to calculate thedata to be modified.The length of the data to be modified.The replacement value to be stored at the memory location.DescriptionThe VIEW command reads and writes blocks directly to disk storage and writes locationsin memory. VIEW has three argument forms:• VIEW block transfers data between the <strong>Caché</strong> database and memory.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 151


<strong>Caché</strong> <strong>ObjectScript</strong> Commands• VIEW offset:mode:length:newvalue places newvalue in the memory location identifiedby offset, mode, and length.You can examine data in memory with the $VIEW function.Note:<strong>InterSystems</strong> recommends that you avoid use of the VIEW command. When usedin any environment, it can corrupt memory structures.ArgumentspcAn optional postconditional expression. <strong>Caché</strong> executes the command if the postconditionalexpression is true (evaluates to a non-zero numeric value). <strong>Caché</strong> does not execute the commandif the postconditional expression is false (evaluates to zero). For further details, referto Command Postconditional Expressions in Using <strong>Caché</strong> <strong>ObjectScript</strong>.blockA block location, specified as an integer. If block is a positive integer, VIEW reads thatnumber block into the view buffer. If block is a negative integer, VIEW writes the blockcurrently in the view buffer to that block address. The block and theoffset:mode:length:newvalue arguments are mutually exclusive.offsetAn offset, in bytes, from a base address within the memory region specified by mode.modeThe memory region whose base address will be used to calculate the data to be modified. SeeModifying Data in Memory for a description of the possible values.lengthThe length of the data to be modified.Specify the number of bytes as an integer from 1-4. You can also use the letter C to indicatea four-byte address or the letter P to indicate a four byte word address). You must specifyboth the P or C and the positive integer in double quotes.If newvalue defines a string, specify the number of bytes as a negative integer from 1 through510. If the length of newvalue exceeds this number, <strong>Caché</strong> ignores the extraneous characters.If the length of newvalue is less than this number, <strong>Caché</strong> stores the supplied characters andleaves the rest of the memory location unchanged.152 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


VIEWTo store a byte value in reverse order (low-order byte at lowest address) append the letter Oto the length number and enclose both in double quotes.Note:On a 2-byte or 4-byte machine, you can precede C, P, or O with the digit 2 or 4 toindicate your computer's standard word length.The <strong>Caché</strong> addressing scheme used on your system can affect the calculation of length.newvalueThe replacement value to be stored at the memory location.ExamplesThis command reads the sixth block from the <strong>Caché</strong> database into the View Buffer.VIEW 6This command writes the view buffer back to the sixth block of the <strong>Caché</strong> database, presumablyafter the data has been modified.VIEW -6This command copies the string "WXYZ" into four bytes starting at absolute location ADDR.The expression $VIEW(0,ADDR,-4) would then result in the value "WXYZ" .VIEW 0:ADDR:-4:"WXYZ"NotesUse VIEW with CautionUse the VIEW command with caution. It is usually used for debugging and repair of <strong>Caché</strong>databases and <strong>Caché</strong> system information. It is easy to corrupt memory or your <strong>Caché</strong> databaseby using VIEW incorrectly.The View BufferWhen used to read and write database buffers, the VIEW command works with the viewbuffer (device 63). The view buffer is a special memory area that you must opened beforeyou can perform any VIEW operations.When you open the view buffer (with the OPEN command), you indicate the <strong>Caché</strong> database(CACHE.DAT) to be associated with the view buffer. Using the VIEW command, you canthen read individual blocks from the <strong>Caché</strong> database into the view buffer.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 153


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsAfter reading a block into the view buffer, you can use the $VIEW function to examine thedata. Or, you can use the VIEW command to modify the data. If you modify the data, youcan use the VIEW command again to write the modified block back to the <strong>Caché</strong> database.Reading and Writing Data in a <strong>Caché</strong> DatabaseBefore you can read and write data blocks in a <strong>Caché</strong> database with VIEW, you must firstuse the OPEN command to open the view buffer.1. Open the view buffer. The view buffer is designated as device number 63. Hence thecommand is:OPEN 63:locationwhere location is the namespace that contains the CACHE.DAT to be associated withthe view buffer. The location is implementation specific. The OPEN 63 command createsthe view buffer by allocating a region of system memory whose size is equal to the blocksize used by the <strong>Caché</strong> database.2. Use the VIEW block form to read in a block from the associated <strong>Caché</strong> database. Specifyblock as a positive integer. For example:VIEW 4This example reads the fourth block from the <strong>Caché</strong> database into the view buffer. Becausethe size of the view buffer equals the block size used in the <strong>Caché</strong> database, the viewbuffer can contain only one block at any given time. As you read in subsequent blocks,each new block overwrites the current block. To determine which blocks to read in fromthe <strong>Caché</strong> database, you should be familiar with the structure of the file.3. Read the data in the block with $VIEW function or modify it with the VIEW command.4. If you changed any of the data in the view buffer, write it back to the <strong>Caché</strong> database.To write data, use the VIEW block form but specify a negative integer for block. Theblock number usually matches the number of the current block in the view buffer, but itdoes not have to. The specified block number identifies which block in the file will bereplaced (overwritten) by the block in the view buffer. For example: VIEW 5 Thisexample replaces the fifth block in the <strong>Caché</strong> database with the current block in the viewbuffer.5. Close the view buffer. CLOSE 63154 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


Transferring a Block between <strong>Caché</strong> DatabasesWhen you open the view buffer, <strong>Caché</strong> does not automatically clear the existing block. Thisallows you to transfer a block of data from one <strong>Caché</strong> database to another using the followingsequence:1. Use OPEN 63 and specify the namespace that contains the first <strong>Caché</strong> database.2. Use VIEW to read the desired block from the file into the view buffer.3. If necessary, use VIEW to modify the data in the view buffer.4. Use OPEN 63 again and specify the namespace that contains the second <strong>Caché</strong> database.5. Use VIEW to write the block from the view buffer to the second <strong>Caché</strong> database.6. Close the view buffer with a CLOSE 63 command.Modifying Data in MemoryIn addition to reading and writing data from a <strong>Caché</strong> database, the VIEW command allowsyou to modify data in memory either in the view buffer or in other system memory areas.To modify data, use the following form:VIEW offset:mode:length:newvalueAll four arguments are required.You modify data by storing a new value into a memory location, which is specified as a byteoffset from the base address indicated by mode. You specify the amount of memory affectedin the length argument.The possible values for mode are shown in the following table.VIEW<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 155


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsModen >00-1-2-3-6-7Memory Management RegionVirtual address space of jobbed process n, where n is the value of $JOB for thatjobbed process.The view bufferThe process's partitionThe system tableThe process's virtual address spaceReserved for <strong>InterSystems</strong>' useUsed only by the integrity checking utilityBase Address0Beginning of view bufferBeginning of partitionBeginning of system table0Special. See the <strong>Caché</strong> HighAvailability Guide.See Also• OPEN command• CLOSE command• $VIEW function• Error Handling in Using <strong>Caché</strong> <strong>ObjectScript</strong>WHILEExecutes code while a condition is true.WHILE expression,... {;. . .}ArgumentsexpressionA test condition. You can specify one or more comma-separatedtest conditions, all of which must be TRUE for execution of thecode block.156 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


DescriptionWHILE tests expression and then executes the block of code (one or more commands)between the opening and closing curly braces repeatedly, as long as expression evaluates toTRUE. If expression is not TRUE, block of code within the curly braces is not executed, andthe next command following the closing curly brace ( } ) is executed.The block of code within the curly braces can consist of one or more <strong>Caché</strong> Objectscriptcommands and function calls. This block of code may span several lines. Indents, line returns,and blank spaces are permitted within the block of code. Commands within this code blockand arguments within commands may be separated by one or more blank spaces and linereturns. However, each command keyword must be separated from its first argument byexactly one space.ArgumentsexpressionA test condition. It can take the form of a single expression or a comma separated list ofexpressions. For an expression list, <strong>Caché</strong> evaluates the individual expressions in left to rightorder. It stops evaluation if it encounters an expression that is FALSE. If all expressionsevaluate to TRUE, <strong>Caché</strong> executes the code commands. WHILE executes repeatedly, testingexpression for each loop. If any expression evaluates to FALSE, <strong>Caché</strong> ignores any remainingexpressions, and does not execute the code commands. It executes the next command afterthe code commands.ExampleMainloopSET x=1WHILE x < 10 {WRITE !," Looping",xSET x=x+1}WRITE !,"DONE"QUITreturns: “Looping1” through “Looping9”, then writes “DONE”.NotesWHILE and DO WHILEWHILEThe WHILE command tests expression before executing the loop. The DO WHILE commandexecutes the loop once and then tests expression.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 157


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsQUIT and GOTOThe QUIT command within the block of code ends the WHILE loop and returns executionto the command following the closing curly brace, as shown in the following example:MainloopSET x=1WHILE x < 10{WRITE !,"looping "SET x=x+1WRITE " x=",xQUIT}WRITE " done"returns: looping x=2 doneA GOTO command within the block of code may direct execution to a tag outside the loop,terminating the loop. A GOTO command within the block of code may direct execution toa tag within the same block of code; this tag may be in a nested code block. A GOTO commandwithin the block of code may not direct execution to a tag within another code block.The following forms of GOTO are legal:mainloop ; Example of a GOTO to outside of the code blockWHILE 1=1 {WRITE !,"In an infinite WHILE loop"GOTO tagWRITE !,"This should not display"}WRITE !,"This should not display"tagWRITE !,"Went to tag and quit"QUITmainloop ; Example of a GOTO to within the code blockSET x=1WHILE x


WHILEmainloop ; Example of a GOTO from a nested code blockSET x=1WHILE x


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsWRITEDisplays output.WRITE:pc writeargument,...W:pc writeargument,...where writeargument can befexpression*integer-expressionArgumentspcfexpression*integer-expressionOptional — A postconditional expression.Optional — One or more format control code charactersthat position the output on the target device. Formatcontrol characters include !, #, ?, and /.Optional — The value to write to the output device. Anyvalid <strong>Caché</strong> <strong>ObjectScript</strong> expression, including literals,variables, object methods, and object properties thatevaluates to either a numeric or a quoted string.Optional — The decimal code for a character to writeto the output device. For ASCII, integers in the range0 to 255; for Unicode, integers in the range 0 to 65534.Any valid <strong>Caché</strong> <strong>ObjectScript</strong> expression that evaluatesto an integer in the appropriate range. The asterisk ismandatory.DescriptionThe WRITE command displays the specified output on the current I/O device. (To set thecurrent I/O device, use the USE command, which sets the value of the $IO special variable.)WRITE has two forms:• WRITE without an argument• WRITE with arguments160 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


WRITEWRITE without an ArgumentWRITE without an argument lists the names and values of all defined variables in the localenvironment. It presents these variables as follows:varname1=value1varname2=value2Note that an argumentless WRITE automatically provides formatting to separate the listedvariables. It lists string values enclosed in double quotation marks.A postconditional expression can be specified with an argumentless WRITE. An argumentlessWRITE must be separated by at least two blank spaces from a command following it on thesame line.WRITE with ArgumentsWRITE expression displays the sequence of characters identified by the expression.Expression can evaluate to a number or a quoted string.WRITE *integer-expression displays the character represented by the integer expression.A WRITE command can take any combination of expression, *integer-expression, and farguments. WRITE arguments are separated by commas.You must use the f argument and blank spaces within strings to provide any desired outputformatting; WRITE with arguments provides no automatic formatting to separate argumentvalues or indicate strings. For example:WRITE "numbers",1,2,3WRITE "letters","ABC"displays as numbers123lettersABC.ArgumentspcAn optional postconditional expression. <strong>Caché</strong> executes the command if the postconditionalexpression is true (evaluates to a non-zero numeric value). <strong>Caché</strong> does not execute the commandif the postconditional expression is false (evaluates to zero). You can specify a postconditionalexpression for an argumentless WRITE or a WRITE with arguments. For furtherdetails, refer to Command Postconditional Expressions in Using <strong>Caché</strong> <strong>ObjectScript</strong>.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 161


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsfA format control to position the output on the target device. You can specify any combinationof format control characters without intervening commas, but you must use a comma to separatea format control from an expression. For example, when you issue the following WRITEto a terminal:WRITE #!!!?6,"Hello",!,"world!"The format controls position to the top of a new screen (#), then issue three line returns (!!!),then indent six columns (?6). The WRITE then displays the string Hello, issues a line return,then displays the string world!. Note that the line return repositions to column 1; thus in thisexample, Hello is displayed indented, but world! is not.Format control characters cannot be used with an argumentless WRITE.For further details, see Using Format Controls with WRITE .expressionThe value you wish to output. Most commonly this is either a quoted string or a numeric.However, expression can be any valid <strong>Caché</strong> <strong>ObjectScript</strong> expression, including literals,variables, object methods, and object properties. For more information on expressions, seeUsing <strong>Caché</strong> <strong>ObjectScript</strong>.*integer-expressionAny valid <strong>Caché</strong> <strong>ObjectScript</strong> expression that evaluates to an integer that corresponds to acharacter. An integer-expression in the range of 0 through 255 evaluates to the corresponding8-bit ASCII character. An integer-expression in the range of 256 through 65534 evaluates tothe corresponding 16-bit Unicode character. Integer expressions can be used to displayaccented characters. For example to display the word “<strong>Caché</strong>” you can use:WRITE "Cach",*233To write the name of the composer Anton Dvorak with the proper Czech accent marks, use:WRITE "Anton Dvo",*345,*225,"k"Integer expressions can also be used to insert control characters (such as the line feed: *12)which govern the appearance of the display, or special characters such as *7, which rings thebell on a terminal.162 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


WRITENote:An integer expression does not change the $X special variable when writing to aterminal. Thus, WRITE "a" and WRITE $CHAR(97) both increment the columnnumber value contained in $X, but WRITE *97 does not increment $X. For furtherdetails, see the $X special variable, and “Terminal I/O” in <strong>Caché</strong> I/O Device Guide.ExamplesIn the following example, the WRITE command sends the current value in variable var1 tothe current output device.SET var1="hello world"WRITE var1In the following example, both WRITE commands display the Unicode character for pi. Thefirst uses an expression, the second an integer-expression:WRITE !,$CHAR(960)WRITE !,*960The following example writes first name and last name values along with an identifying textfor each. The WRITE command combines multiple arguments on the same line. It is equivalentto the two WRITE commands in the example that follows it. The ! character is a formatcontrol that produces a line break. (Note that the ! line break character is still needed whenthe text is output by two different WRITE commands.)SET fname="Bertie"SET lname="Wooster"WRITE "First name: ",fname,!,"Last name: ",lnameis equivalent to:SET fname="Bertie"SET lname="Wooster"WRITE "First name: ",fname,!WRITE "Last name: ",lnameIn the following example, assume that the current device is the user's terminal. The READcommand prompts the user for first name and last name and stores the input values in variablesfname and lname, respectively. The WRITE command displays the values in fname andlname for the user's confirmation. The string containing a space character (" ") is included toseparate the output names.TestREAD !,"First name: ",fnameREAD !,"Last name: ",lnameWRITE !,fname," ",lnameREAD !,"Is this correct? (Y or N) ",check#1IF "Nn"[check {GOTO Test}<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 163


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsThe following example writes the current values in the ^client(1,n) nodes.SET ^client(1,1)="Mary Smith"SET ^client(1,2)="123 Primrose Path"SET ^client(1,3)="Johnson City"SET ^client(1,4)="TN"SET n=1ElementsIF $DATA(^client(1,n)) {WRITE ^client(1,n),!SET n=n+1GOTO Elements}ELSE { QUIT }The following command writes the current value of an object property:WRITE person.LastNamewhere person is the object reference, and LastName is the object property name. Note thatdot syntax is used in object expressions; a dot is placed between the object reference and theobject property name or object method name.The following command writes the value returned by the object method TotalLines():WRITE invoice.TotalLines()A write command for objects can take an expression with cascading dot syntax, as shown inthe following example:WRITE patient.Doctor.Hospital.NameIn this example, the patient.Doctor object property references the Hospital object, which containsthe Name property. Thus, this command writes the name of the hospital affiliated with thedoctor of the specified patient. The same cascading dot syntax can be used with objectmethods.A write command for objects can be used with system-level methods, such as the followingdata type property method:WRITE patient.AdmitDateIsValid(date)In this example, the AdmitDateIsValid() property method returns its result for the currentpatient object. AdmitDateIsValid() is a boolean method for data type validation of theAdmitDate property. Thus, this command writes a 1 if the specified date is a valid date, andwrites 0 if the specified date is not a valid date.Note that any object expression can be further specified by declaring the class or superclassto which the object reference refers. Thus, the above examples could also be written:WRITE ##class(Patient)patient.Doctor.Hospital.Name164 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


WRITEWRITE ##class(Patient)patient.AdmitDateIsValid(date)NotesWRITE with $X and $YA WRITE displays the characters resulting from the expression evaluation one at a time inleft-to-right order. <strong>Caché</strong> records the current output position in the $X and $Y special variables,with $X defining the current column position and $Y defining the current row position. Aseach character is displayed, $X is incremented by one.In the following example, the WRITE command gives the column position after writing the11–character string Hello world.WRITE "Hello world"," "_$X," is the column number"Note that writing a blank space between the displayed string and the $X value (," ",$X)would cause that blank space to increment $X before it is evaluated; but concatenating ablank space to $X (," "_$X) displays the blank space, but does not increment the value of$X before it is evaluated.Even using a concatenated blank, the display from $X or $Y does, of course, increment $X,as shown in the following example:WRITE $Y," "_$XWRITE $X," "_$YIn the first WRITE, the value of $X is incremented by the number of digits in the $Y value(which is probably not what you wanted). In the second WRITE, the value of $X is 0.With $X you can display the current column position during a WRITE command. To controlthe column position during a WRITE command, you can use the ? format control character.The ? format character is only meaningful when $X is at column 0. In the following WRITEcommands, the ? performing indenting:WRITE !?5,"Hello world"WRITE "Hello",!?5,"world"WRITE with Integer ExpressionsThe *integer-expression form allows you to write an integer code to the current device. Notethat integer-expression can specify an arithmetic expression or variable name (local variable,process-private global, or global). The only requirement is that the resulting value be a positiveinteger. Integers in the range 0 to 255 correspond to the ASCII character set. Integers in therange 0 to 65534 correspond to the Unicode character set.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 165


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsThe following examples all return the word “<strong>Caché</strong>”:WRITE !,"Cach",*233WRITE !,*67,*97,*99,*104,*233SET accent=233WRITE !,"Cach",*accent ; variables are evaluatedWRITE !,"Cach",*232+1 ; arithmetic operations are evaluatedWRITE !,"Cach",*00233.999 ; numbers are evaluated to integersThe integer resulting from the expression evaluation may correspond to a control character.Such characters are interpreted according to the target device. For example, if the currentdevice is a terminal, the integer is interpreted as ASCII control characters. The followingcommands send ASCII codes 7 and 12 to the terminal.WRITE *7 ; Sounds the bellWRITE *12 ; Form feed (blank line)Here's an example using the form feed character:WRITE "stepping",*12,"down",*12,"the",*12,"stairs"Using Format Controls with WRITEThe f argument allows you to include any of the following format control characters. Whenused with output to the terminal, these controls determine where the output data appears onthe screen. You can specify any combination of format control characters.! Format Control CharacterAdvances one line and positions to column 0 ($Y is incremented by 1 and $X is set to 0).The actual control code sequence is device-dependent; it generally either ASCII 13 (RETURN),or ASCII 13 and ASCII 10 (LINE FEED).<strong>Caché</strong> does not perform an implicit new line sequence for WRITE with arguments. Whenwriting to a terminal it is a good general practice to begin (or end) every WRITE commandwith a ! format control character.You can specify multiple ! format controls. For example, to advance five lines, WRITE !!!!!.You can combine ! format controls with other format controls. However, note that the followingcombinations, though permitted, are not in most cases meaningful: !# or !,# (advance oneline, then advance to the top of a new screen, resetting $Y to 0) and ?5,! (indent by 5, thenadvance one line, undoing the increment). The combination ?5! is not legal.If the current device is a TCP device, ! does not output a RETURN and LINE FEED. Instead,it flushes any characters that remain in the buffer and sends them across the network to thetarget system.166 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


# Format Control CharacterOutputs a FORM FEED (ASCII 12) character. On a terminal, it clears the current screen andstarts at the top of the new screen in column 0. ($Y and $X are reset to 0.)You can combine # format controls with other format controls. However, note that the followingcombinations, though permitted, are not in most cases meaningful: !# or !,# (advance oneline, then advance to the top of a new screen, resetting $Y to 0) and ?5,# (indent by 5, thenadvance to the top of a new screen, undoing the increment). The combination ?5# is not legal.?n Format Control CharacterThis format control consists of a question mark (?) followed by an integer, or an expressionthat evaluates to an integer. It positions output at the nth column location (counting fromcolumn 0) and resets $X. If this integer is less than or equal to the current column location(n


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsMnemonic/IC(n)/DC(n)/EC(n)DescriptionInserts spaces for n characters at the current cursor location, movingthe rest of the line to the rightDeletes n characters to the right of the cursor and collapses the lineErases n characters to the right of the cursor, leaving blanks in theirsteadFor further details on mnemonics, see the <strong>Caché</strong> I/O Device Guide.Specifying a Sequence of Format Controls<strong>Caché</strong> allows you to specify a sequence of format controls and to intersperse format controlsand expressions. When specifying a sequence of format controls it is not necessary to includethe comma separator between them (though commas are permitted.) A comma separator isrequired to separate format controls from expressions.In the following example, the WRITE command advances the output by two lines and positionsthe first output character at the column location established by the input for the READcommand.READ !,"Enter the number: ",numSET col=$XSET ans=num*num*numWRITE !!,"Its cube is: ",?col,ansThus, the output column varies depending on the number of characters input for the READ.Escape Sequences with WRITEThe WRITE command, like the READ command, provides support for escape sequences.Escape sequences are typically used in format and control operations. Their interpretation isspecific to the current device type.To output an escape sequence, use the form:WRITE *27,"char"where *27 is the ASCII code for the escape character, and char is a literal string consistingof one or more control characters. The enclosing double quotes are required.For example, if the current device is a VT-100 compatible terminal, the following commanderases all characters from the current cursor position to the end of the line.WRITE *27,"[2J"168 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


To provide device independence for a program that can run on multiple platforms, use theSET command at the start of the program to assign the necessary escape sequences to variables.In your program code, you can then reference the variables instead of the actual escapesequences. To adapt the program for a different platform, simply make the necessary changesto the escape sequences defined with the SET command.Device Controls<strong>Caché</strong> supports the use of negative integer expressions as device controls. For example, inVMS, the following command rewinds and unloads the tape on the current magnetic tapedevice.WRITE *-13The following sections describe these controls for terminal and magnetic tape devices.Terminal Devices<strong>Caché</strong> implementations support the *-1 control for terminal devices. This control clears theinput buffer of any characters that have not been input by previous READ commands.An input buffer holds characters as they arrive from the keyboard, even those the user typesbefore the routine executes a READ command. In this way, the user can answer questionseven before they appear on the screen. When the READ command takes characters from thebuffer, <strong>Caché</strong> echoes them to the terminal so that questions and answers appear together.When a routine detects errors it may cancel these answers. For further details, see TerminalI/O in the <strong>Caché</strong> I/O Device Guide.Magnetic Tape DevicesWRITE<strong>Caché</strong> platforms support a number of controls for magnetic tape devices. The following tablelists these controls and their functions. For further details, see Magnetic Tape I/O in the <strong>Caché</strong>I/O Device Guide.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 169


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsCode-1-2-3-4-5-6-7-8-9-13FunctionBackspaceForward SpaceWrite Tape MarkWrite BlockRewindRead BlockRead LabelWrite HeaderLabelWrite EOF LabelRewind andUnloadEffectBackspaces tape one block. (Not supported for cartridgetape.)Advances tape one block (skipping labels) so that WRITE* 2 at the beginning of the tape (BOT) skips volume andheader labels as well as the first data block. (Notsupported for cartridge tape.)Writes a tape mark. If the buffer contains unwritten data,that data is written out first.Writes out the current buffer. If the format specifies labelsand the tape is at BOT, header labels of the appropriateformat are written before the data block.Rewinds the tape. Any unwritten data (in addition to trailerlabels and tape marks required by the format) is writtenbefore rewinding occurs.Reads the next block. If the tape is at BOT, skips headerlabels before reading.Reads the next block whether or not it is a label. (Notsupported for cartridge tape.)If the format specifies labels, writes header labels. If thetape is at BOT, writes a volume label before the headerlabels. (Not supported for cartridge tape.)Writes any unwritten data. If the format specifies labels,writes the appropriate trailer label. Writes two tape marksand backspaces over the second. (Not supported forcartridge tape.)For OpenVMS only: performs all the function WRITE *-5,then unloads the tape. This control lets you create anoutput set that spans more than one tape volume.When writing block-oriented data to magnetic tape, the $ZB special variable contains thenumber of bytes remaining in the I/O buffer. Refer to $ZB for further details.See Also• USE command170 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


XECUTE• READ command• $X special variable• $Y special variable• Writing escape sequences for Terminal I/O and Interprocess Communications in the<strong>Caché</strong> I/O Device Guide• Terminal I/O in <strong>Caché</strong> I/O Device Guide• Magnetic Tape I/O in <strong>Caché</strong> I/O Device Guide• Sequential File I/O in <strong>Caché</strong> I/O Device Guide• The Spool Device in <strong>Caché</strong> I/O Device GuideXECUTEExecutes specified commands.XECUTE:pc xecuteargument,...X:pc xecuteargument,...where xecuteargument isexpression:pcArgumentspcexpressionOptional — A postconditional expression.One or more valid <strong>Caché</strong> <strong>ObjectScript</strong> commands.DescriptionXECUTE executes <strong>Caché</strong> <strong>ObjectScript</strong> commands that result from the process of expressionevaluation of the specified argument. Each XECUTE argument must evaluate to a stringcontaining <strong>Caché</strong> <strong>ObjectScript</strong> commands. The string must not contain a tab character at thebeginning or a at the end. The string must be no longer than a valid <strong>Caché</strong><strong>ObjectScript</strong> program line.In effect, each XECUTE argument is like a one-line subroutine called by a DO commandand terminated when the end of the argument is reached or a QUIT command is encountered.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 171


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsAfter <strong>Caché</strong> executes the argument, it returns control to the point immediately after theXECUTE argument.Each invocation of XECUTE places a new context frame on the call stack for your process.The $STACK special variable contains the current number of context frames on the callstack.ArgumentspcAn optional postconditional expression. If the postconditional expression is appended to thecommand, <strong>Caché</strong> executes the XECUTE command if the postconditional expression is true(evaluates to a non-zero numeric value). <strong>Caché</strong> does not execute the XECUTE command ifthe postconditional expression is false (evaluates to zero). If the postconditional expressionis appended to an argument, <strong>Caché</strong> evaluates the argument only if the postconditionalexpression is true (evaluates to a non-zero numeric value). If the postconditional expressionis false, <strong>Caché</strong> that argument and evaluates the next argument (if one exists) or the nextcommand. For further details, refer to Command Postconditional Expressions in Using <strong>Caché</strong><strong>ObjectScript</strong>.expressionA single expression or a comma separated list of expressions. Each expression must containat least one valid <strong>Caché</strong> <strong>ObjectScript</strong> command. The expression can evaluate to a null string(""). In this case, <strong>Caché</strong> performs no action and continues execution with the next XECUTEargument or the next command.ExamplesIn this example, the XECUTE command references the local variables x and y. x and y eachcontain a string literal consisting of three separate <strong>Caché</strong> <strong>ObjectScript</strong> commands thatXECUTE invokes.SET x="SET id=ans QUIT:ans="""" DO Idcheck"SET y="SET acct=num QUIT:acct="""" DO Actcheck"XECUTE x,yThe following example uses XECUTE with a $SELECT construction.XECUTE "SET A=$SELECT(A>100:B,1:D)"The following example executes the subroutine that is the value of A.SET A="WRITE ! FOR I=1:1:5 { WRITE ?I*5,I+1 }"XECUTE A172 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


XECUTE2 3 4 5 6NotesXECUTE and ObjectsYou can use XECUTE to call object methods and properties and execute the returned value,as shown in the following examples:XECUTE patient.NameXECUTE "WRITE patient.Name"XECUTE and FORIf an XECUTE argument contains a FOR command, the scope of the FOR is the remainderof the argument. When the outermost FOR in an XECUTE argument is terminated, theXECUTE argument is also terminated.XECUTE and DOIf an XECUTE command contains a DO command, <strong>Caché</strong> executes the routine or routinesspecified in the DO argument or arguments. When it encounters a QUIT, it returns controlto the point immediately following the DO argument.For example, in the following commands, <strong>Caché</strong> executes the routine ROUT and returns tothe point immediately following the DO argument to write the string “DONE”.XECUTE "DO ^ROUT WRITE !,""DONE"""XECUTE and GOTOIf an XECUTE argument contains a GOTO command, <strong>Caché</strong> transfers control to the pointspecified in the GOTO argument. When it encounters a QUIT, it does not return to the pointimmediately following the GOTO argument that caused the transfer. Instead, <strong>Caché</strong> returnscontrol to the point immediately following the XECUTE argument that contained the GOTO.In the following example, <strong>Caché</strong> transfers control to the routine ROUT and returns controlto the point immediately following the XECUTE argument to write the string “FINISH”. Itnever writes the string “DONE”.XECUTE "GOTO ^ROUT WRITE !,""DONE""" WRITE !,"FINISH"XECUTE and QUITThere is an implied QUIT at the end of each XECUTE argument.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 173


<strong>Caché</strong> <strong>ObjectScript</strong> CommandsXECUTE with $TEXTIf you include a $TEXT function within an expression, it designates lines of code in theroutine that contains the XECUTE. For example, in the following program, the $TEXTfunction retrieves and executes a line.ASET H="WRITE !!,$PIECE($TEXT(HELP+1),"","",3)"XECUTE HQUITHELP;; ENTER A NUMBER FROM 1 TO 5Running routine A extracts and writes “ENTER A NUMBER FROM 1 TO 5”.Nested Invocation of XECUTE<strong>Caché</strong> <strong>ObjectScript</strong> supports the use of XECUTE within an XECUTE argument. However,you should use nested invocation of XECUTE with caution because it can be difficult todetermine the exact flow of processing at execution time.Execution Time for Commands Called by XECUTEThe execution time for code called within XECUTE can be slower than the execution timefor the same code encountered in the body of a routine. This is because <strong>Caché</strong> compiles sourcecode that is specified with the XECUTE command or that is contained in a referenced globalvariable each time it processes the XECUTE.Implementing Generalized OperationsA typical use for XECUTE is to implement generalized operations within an application.For example, assume that you want to implement an inline mathematical calculator that wouldallow the user to perform mathematical operations on any two numbers and/or variables. Tomake the calculator available from any point in the application, you might use a specificfunction key (say, F1) to trigger the calculator subroutine.A simplified version of the code to implement such a calculator might appear as follows.174 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


XECUTEStart SET ops=$CHAR(27,21)READ !,"Total amount (or F1 for Calculator): ",amtIF $ZB=ops { DO Calc; . . .}Calc READ !,"Calculator"READ !,"Math operation on two numbers and/or variables."READ !,"First number or variable name: ",inp1READ !,"Mathematical operator (+,,*,/): ",opREAD !,"Second number or variable name: ",inp2SET doit="SET ans="_inp1_op_inp2XECUTE doitWRITE !,"Answer (ans) is: ",ansREAD !,"Repeat? (Y or N) ",inpIF (inp="Y")!(inp="y") { GOTO Calc+2 }QUITWhen executed, the Calc routine accepts the user inputs for the numbers and/or variablesand the desired operation and stores them as a string literal defining the appropriate SETcommand in variable doit. The XECUTE command references doit and executes the commandstring that it contains. This code sequence can be called from any number of points in theapplication, with the user supplying different inputs each time. The XECUTE performs theSET command each time, using the supplied inputs.XECUTE and ZINSERTYou use the XECUTE command to define and insert a single line of executable code fromwithin a routine. You can use the ZINSERT command from the programmer prompt to defineand insert by line position a single line of executable code into the current routine. You canuse the ZREMOVE command from the programmer prompt to delete by line position oneor more lines of executable code from the current routine.An XECUTE command cannot be used to define a new label. Therefore, XECUTE doesnot require an initial blank space before the first command in its code line. ZINSERT canbe used to define a new label. Therefore, ZINSERT does require an initial blank space (orthe name of a new label) before the first command in its command line.See Also• DO command• GOTO command• QUIT command• ZINSERT command• $TEXT function• $STACK special variable<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 175


<strong>Caché</strong> <strong>ObjectScript</strong> FunctionsA function performs an operation and returns a value. This value may be the result of theoperation, or an indicator that the operation completed successfully or failed. By convention,<strong>Caché</strong> functions that set a variable to a value set the variable, then return the value of thatvariable prior to the operation.This document describes <strong>Caché</strong>-supplied (intrinsic) functions. These functions are identifiedby a $ character prefix to the name and parentheses following the name. You can supplementthese functions by creating user-defined (extrinsic) functions (identified by a $$ prefix). Inthis manual, <strong>Caché</strong> <strong>ObjectScript</strong> intrinsic functions are divided into four groups:• General Functions.• Math and Time/Date Functions (the names of which begin with “$Z”.).• System and Other Functions (the names of which begin with “$Z”, and include the$ZUTIL functions.)• Legacy (obsolete) Functions.The names of <strong>Caché</strong> <strong>ObjectScript</strong> special variables also begin with a $ character, but specialvariables have no parentheses.For more information on <strong>Caché</strong> <strong>ObjectScript</strong> functions generally, see the Functions chapterof Using <strong>Caché</strong> <strong>ObjectScript</strong>; for more information on defining your own functions, see User-Defined Code in Using <strong>Caché</strong> <strong>ObjectScript</strong>.To invoke an intrinsic function, use the form:$name(parameters)<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 177


<strong>Caché</strong> <strong>ObjectScript</strong> FunctionsnameparametersThe name of the function. The preceding dollar sign ($) is required.Function names are shown here in all uppercase letters, but theyare, in fact, case-insensitive. You can abbreviate most functionnames. In the Synopsis for each function, the full name syntax isfirst presented, and below it is shown the abbreviated name (if oneexists).One or more values to be passed to the function. Function arguments,or parameters, are always enclosed in parentheses and follow thefunction name. The parentheses are mandatory, even if the functionhas no parameters.Multiple parameters are separated from each other by commas.Theparameters are positional and must match the order of the parametersexpected by the function. Missing parameters in this sequencecan be indicated by supplying the appropriate number of commas;no trailing commas are required for parameters missing from theend of the parameter list.Spaces are permitted anywhere in the parameter list. No spaces arepermitted between name and the open parenthesis character.The Synopsis for each function contains only literal syntactical punctuation. The Synopsisdoes not include punctuation for format conventions, such as what parameters of the syntaxare optional. This information is provided in the table of parameters immediately followingthe Synopsis.The one exception is the ellipsis (...). An ellipsis following a comma indicates that theparameter (or parameter group) preceding the comma can be repeated multiple times as acomma-separated list.Any platform-specific function is marked with the name of the platform that supports it. Anyfunction that is not marked with a platform abbreviation is supported by all <strong>Caché</strong> platforms.178 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ASCII$ASCIIReturns the character code value for an expression.$ASCII(expression,position)$A(expression,position)ParametersexpressionpositionThe character to be converted.Optional — The position of a character within a character string.Description$ASCII returns the character code value for a single character specified in expression. Thischaracter can be an 8-bit (ASCII) character or a 16-bit (Unicode) character.The expression may evaluate to a single character or to a string of characters. If expressionevaluates to a character string, you include the optional position parameter to indicate whichcharacter you want to convert.ParametersexpressionThe expression can be specified as the name of a variable, a numeric value, a string literal,or any valid <strong>Caché</strong> <strong>ObjectScript</strong> expression. If expression yields more than one character,use position to select the desired character. If you omit position for a character string, $ASCIIreturns the numeric code for the first character. $ASCII returns -1 if the expression evaluatesto a null string.positionThe position must be specified as a non-zero positive integer. It may be signed or unsigned.You can use a non-integer numeric value in position; however, <strong>Caché</strong> ignores the decimalportion and only considers the integer portion of the numeric value. If you do not includeposition, $ASCII returns the numeric value of the first character in expression. $ASCIIreturns -1 if the integer value of position is larger than the number of characters in expressionor less than 1.ExamplesThe following example returns 87, the ASCII decimal value of the character W.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 179


<strong>Caché</strong> <strong>ObjectScript</strong> FunctionsWRITE $ASCII("W")The following example returns 960, the decimal equivalent for the Unicode character "pi".WRITE $ASCII($CHAR(959+1))The following example returns 84, the decimal equivalent of the ASCII value for the firstcharacter in the variable Z.SET Z="TEST"WRITE $ASCII(Z)The following example returns 83, the decimal equivalent of the ASCII value for the thirdcharacter in the variable Z.SET Z="TEST"WRITE $ASCII(Z,3)The following example returns a -1 because the second argument specifies a position greaterthan the number of characters in the string.SET Z="TEST"WRITE $ASCII(Z,5)The following example uses $ASCII in a FOR loop to convert all of the characters in variablex to their ASCII decimal equivalents. The $ASCII reference includes the position parameter,which is updated for each execution of the loop. When position reaches a number that isgreater than the number of characters in x, $ASCII returns a value of -1, which terminatesthe loop.SET x="abcdefghijklmnopqrstuvwxyz"FOR i=1:1 {QUIT:$ASCII(x,i)=-1WRITE !,$ASCII(x,i)}QUITThe following example generates a simple checksum for the string X. When $CHAR(CS) isconcatenated with the string, the checksum of the new string is always zero. Therefore, validationis simplified.CXSUMSET x="Now is the time for all good men to come to the aid of their party"SET CS=0FOR i=1:1:$LENGTH(x) {SET CS=CS+$ASCII(x,i)WRITE !,"Checksum is:",CS}SET CS=128-CS#128WRITE !,"Final checksum is:",CSThe following example converts a lowercase or mixed-case alphabetic string to all uppercase.180 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ASCIISTSET String="ThIs Is a MiXeDCAse stRiNg"WRITE !,"Input: ",StringSET Len=$LENGTH(String),Nstring=" "FOR i=1:1:Len { DO CNVT }QUITCNVTSET Char=$EXTRACT(String,i),Asc=$ASCII(Char)IF Asc>96,Asc


<strong>Caché</strong> <strong>ObjectScript</strong> Functions• $ZLASCII function• $ZWASCII function$BITReturns and or sets the bit value of a specified position in a bitstring.$BIT(bitstring,position)SET $BIT(bitstring,position) = bitvalueParametersbitstringpositionbitvalueThe name of a bitstring. Can be a local variable, a process-privateglobal, or a global.The bit position of the returned value.Optional — The value to which the indicated position in the bitstringis set.DescriptionThere are several forms of the $BIT function. For general information on $BIT and otherbitstring functions, see below.$BIT(bitstring,position) returns the bit value (0 or 1) at the specified position, position, inthe given bitstring expression bitstring. If bitstring is a null string or if position is less than1 or greater than the length of the bitstring, the function returns 0.SET $BIT(bitstring,position) = bitvalue performs an atomic bit set on the bitstring specifiedby bitstring. If bitvalue is true, then the bit at position position is set. If bitvalue is false, thebit is cleared. If the bitstring is shorter than the specified position, it is padded with 0 bits tothe specified position.ExampleIf bitstring=[0,0,1,1], then the result of $BIT(bitstring,2) would be 0.182 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$BIT// Set a to [0,0,1,1]SET $BIT(a,1) = 0SET $BIT(a,2) = 0SET $BIT(a,3) = 1SET $BIT(a,4) = 1// Test bit 2 within aWRITE !,$BIT(a,2)// Write the bitstringWRITE !,$BIT(a,1),$BIT(a,2),$BIT(a,3),$BIT(a,4)General Information on Bitstring FunctionsBitstring functions manipulate encoded bit-based data. Although a bitstring can be used withany <strong>Caché</strong> <strong>ObjectScript</strong> command or function, it is generally meaningful only within thecontext of the bit functions.The $BIT bitstring functions perform atomic operations. Therefore, no locking is requiredwhen performing bitstring operations.The $BIT bitstring functions perform internal compression of bitstrings. Therefore, the actualdata length of a bitstring and its physical space allocation may differ. $BIT bitstring functionsuse the data length of bitstrings. In most circumstances, the physical space allocation shouldbe invisible to the user. bitstring compression is invisible to users of the $BIT functions.However, because this compressed binary representation is optimized for each bitstring, onecannot assume that two "identical" bitstrings (which were created differently) have identicalinternal representations. <strong>Caché</strong> selects from four separate bitstring internal representationsto optimize for both sparse bitstrings and non-sparse bitstrings. Therefore, while matchingoperations on individual bits yield predictable results, comparisons of entire bitstrings maynot.$BIT bitstring functions support a maximum bitstring length of 262,104 bits (32763 x 8) for<strong>Caché</strong>. (Unlike with certain <strong>InterSystems</strong> legacy products, it is not an error in <strong>Caché</strong> to performan operation on a bit that is beyond the bitstring length.)Bits in a bitstring are numbered with the first (leftmost) bit as position 1. All bitstring comparisonsare performed left-to-right.In the examples, bitstrings are shown within matching square brackets ([...]), with the bitsdelimited by commas. For example, a bitstring of four 1 bits is shown as [1,1,1,1], with theleast significant bits to the right.In all the bitstring functions, variables named bitstring are bitstrings that can be specified asvalues, variables, or expressions.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 183


<strong>Caché</strong> <strong>ObjectScript</strong> FunctionsNote:The $BIT functions replace the earlier $ZBIT functions. New code should only usethe $BIT functions; the $ZBIT functions will continue to be supported for legacyapplications. The $BIT functions and the $ZBIT functions are incompatible; $BITfunctions compress bitstrings, $ZBIT functions do not. Therefore, the two types ofbitstring functions should not be used on the same bitstring.See Also• $BITCOUNT function• $BITFIND function• $BITLOGIC function• $FACTOR function$BITCOUNTReturns the number of bits in a bitstring.$BITCOUNT(bitstring,bitvalue)ParametersbitstringbitvalueThe name of a bitstring. Can be a local variable, a process-privateglobal, or a global.Optional — The value (0 or 1) to count within the bitstring.DescriptionThe $BITCOUNT function counts the number of bits within a bitstring. A bitstring is a stringwhich is interpreted by the system as a series of bits. You can create a bitstring using $BITor $BITLOGIC. There is also general information on bitstring functions available.$BITCOUNT(bitstring) returns the number of bits in bitstring.$BITCOUNT(bitstring, bitvalue) returns the number of bits of type bitvalue (0 or 1) inbitstring.The maximum bitstring length is 262,104 bits (32763 x 8).184 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


ExamplesIf bitstring= [0,0,1,1,0], then the result of $BITCOUNT(bitstring) is 5:$BITCOUNTSET $BIT(a,1) = 0SET $BIT(a,2) = 0SET $BIT(a,3) = 1SET $BIT(a,4) = 1SET $BIT(a,5) = 0WRITE !,$BITCOUNT(a)If bitstring = [0,0,1,1,0], then the result of $BITCOUNT(bitstring,0) would be 3.SET $BIT(a,1) = 0SET $BIT(a,2) = 0SET $BIT(a,3) = 1SET $BIT(a,4) = 1SET $BIT(a,5) = 0WRITE !,"number of zero bits:",$BITCOUNT(a,0)WRITE !,"number of one bits: ",$BITCOUNT(a,1)See Also• $BIT function• $BITFIND function• $BITLOGIC function• $FACTOR function<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 185


<strong>Caché</strong> <strong>ObjectScript</strong> Functions$BITFINDReturns the position of the specified bit value within a bitstring.$BITFIND(bitstring,bitvalue,position,direction)ParametersbitstringbitvaluepositiondirectionThe name of a bitstring. Can be a local variable, a process-privateglobal, or a global.The value (0 or 1) to search for within the bitstring.Optional — The bit position from which the search begins. Search isinclusive of this position.Optional — A direction flag. Available values are 1 and -1. 1 = Searchforward (left to right) from the beginning of the bitstring (or fromposition) towards the end (this is the default). -1 = Search backwardfrom the end of the bitstring (or from position) towards the beginning.Description$BITFIND(bitstring,bitvalue) returns the position of the first occurrence of the specifiedbitvalue (0 or 1) within the bitstring bitstring.$BITFIND(bitstring,bitvalue,position) returns the position of the first occurrence at or afterposition of the specified bitvalue in bitstring.If the desired bit value is not found, or if position is greater than the number of bits withinthe bitstring, the return value is 0.There is also general information on bitstring functions available.ExamplesIf bitstring = [0,0,1,1,0], then the result of $BITFIND(bitstring,1) would be 3.// Set a to [0,0,1,1,0]SET $BIT(a,1) = 0SET $BIT(a,2) = 0SET $BIT(a,3) = 1SET $BIT(a,4) = 1SET $BIT(a,5) = 0// Find first 1 bit within aWRITE !,$BITFIND(a,1)186 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


If bitstring = [0,0,1,1,0], when searching from position 3, the first 1 bit is bit-3 (becausesearch is inclusive of the position bit) and the first 0 bit is bit-5.// Set a to [0,0,1,1,0]SET $BIT(a,1) = 0SET $BIT(a,2) = 0SET $BIT(a,3) = 1SET $BIT(a,4) = 1SET $BIT(a,5) = 0// Find first 1 bit from position 3WRITE !,"found 1 bit at position:",$BITFIND(a,1,3)// Find first 0 bit from position 3WRITE !,"found 0 bit at position:",$BITFIND(a,0,3)See Also• $BIT function• $BITCOUNT function• $BITLOGIC function• $FACTOR function$BITLOGIC$BITLOGICPerforms bit-wise operations on bitstrings.$BITLOGIC(bitstring_expression,length)Parametersbitstring_expressionlengthA bitstring expression consisting of one or morebitstrings and the logical operators &, |, and ~. Abitstring can be specified as a local variable, aprocess-private global, a global, or the constant "".Thenull string ("") has a bitstring length of 0.Optional — The length, in bits, of the resulting bitstring.If length is not specified it defaults to the length of thelongest bitstring in bitstring_expression.Description$BITLOGIC evaluates a bit-wise operation on one or more bitstring values, as specified bybitstring_expression, and returns the resulting bitstring.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 187


<strong>Caché</strong> <strong>ObjectScript</strong> FunctionsA bitstring is an encoded (compressed) string which is interpreted as a series of bits. Onlybitstrings created using $BIT, $FACTOR, or $BITLOGIC, or the null string (""), shouldbe supplied to the $BITLOGIC function. Typically, bitstrings are used for index operations.Refer to general information on bitstring functions in $BIT for further details.$BITLOGIC is incompatible with any of the legacy $ZBIT bitstring functions, and shouldnot be used in combination with them.Bitstring OptimizationThe most basic $BITLOGIC operation is $BITLOGIC(a). Seemingly, this operation doesn'tdo anything: bitstring a is input and the same bitstring a is output. However, $BITLOGICperforms bitstring compression which it optimizes by selecting from several compressionalgorithms. Therefore, if bitstring a has undergone substantial changes since its creation,passing it through $BITLOGIC can result in re-optimization of the bitstring. Refer to $BITfor further details.For example, following a large number of delete operations an index bitstring may havebecome a sparse bitstring, consisting wholly or mainly of zeros. Passing this index bitstringthrough $BITLOGIC may result in substantial performance improvements.Bitstring Logical Operators$BITLOGIC can evaluate only the bitstring operators listed in the following table:Operator&|~MeaningANDORNOT (one's complement)The bitstring_expression can contain a single bitstring (~A), two bitstrings (A&B), or morethan two bitstrings (A&B|C), up to the current maximum of 31 bitstrings. Evaluation is performedleft-to-right. Logical operations may be grouped by parentheses within thebitstring_expression, following standard <strong>Caché</strong> <strong>ObjectScript</strong> order of operations. If a variableused within $BITLOGIC is undefined, it is treated as a null string ("").$BITLOGIC treats a null string as a bitstring of indefinite length, in which all bits are setto 0's.188 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$BITLOGICNote:When $BITLOGIC is supplied more than two bitstring operands, it must createbitstring temporaries to hold the intermediate results. Under some extreme circumstances(many bitstrings and/or extremely large bitstrings), it can exhaust the spaceallocated to hold such temporaries. Bitstring pair operations do not have this limitation,and are thus preferable for large bitstring operations.The NOT (~) operator can be used as a unary operator (for example, ~A), or can be used incombination with other operators (for example, A&~B). It performs the one's complementoperation on a string, turning all 1's to 0's and all 0's to 1's. Multiple NOT operators can beused (for example, ~~~A).The length ArgumentIf length is not specified, it defaults to the length of the longest bitstring in bitstring_expression.If length is specified, it specifies the logical length of the resulting bitstring.• If length is larger than one or more of the bitstrings in bitstring_expression, those bitstringsare zero-filled to that length before bitstring logic operations are performed.• If length is smaller than one or more of the bitstrings in bitstring_expression, those bitstringsare truncated to that length before bitstring logic operations are performed.• If length is 0, a bitstring of length 0 (a null string) is returned.ExamplesThe following example creates some simple bitstrings and demonstrates the use of$BITLOGIC on them:// Set a to [1,1]SET $BIT(a,1) = 1SET $BIT(a,2) = 1// Set b to [0,1]SET $BIT(b,1) = 0SET $BIT(b,2) = 1WRITE !,"bitstring a=",$BIT(a,1),$BIT(a,2)WRITE !,"bitstring b=",$BIT(b,1),$BIT(b,2)SET c = $BITLOGIC(~b)WRITE !,"The one's complement of b=",$BIT(c,1),$BIT(c,2)// Find the intersection (AND) of a and bSET c = $BITLOGIC(a&b) // c should be [0,1]WRITE !,"The AND of a and b=",$BIT(c,1),$BIT(c,2)SET c = $BITLOGIC(a&~b) // c should be [1,0]WRITE !,"The AND of a and ~b=",$BIT(c,1),$BIT(c,2)// Find the union (OR) of a and bSET c = $BITLOGIC(a|b) // c should be [1,1]WRITE !,"The OR of a and b=",$BIT(c,1),$BIT(c,2)QUIT<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 189


<strong>Caché</strong> <strong>ObjectScript</strong> FunctionsThe following example shows the results of specifying a length greater than the input bitstring.The string is zero-filled before the logic operation is performed.// Set a to [1,1]SET $BIT(a,1) = 1SET $BIT(a,2) = 1WRITE !,"bitstring a=",$BIT(a,1),$BIT(a,2)SET c = $BITLOGIC(~a,7)WRITE !,"~a (length 7)="WRITE $BIT(c,1),$BIT(c,2),$BIT(c,3),$BIT(c,4)WRITE $BIT(c,5),$BIT(c,6),$BIT(c,7),$BIT(c,8)Here the one's complement (~) of 11 is 0011111. Bits 3 through 7 were set to zero beforethe ~ operation was performed. This example also displays an eighth bit, which is beyondthe specified string length and thus unaffected by the $BITLOGIC operation. It is, of course,displayed as 0.The following example shows the results of specifying a length less than the input bitstring.The bitstring is truncated to the specified length before logical operations are performed. Allbits beyond the specified length default to 0.// Set a to [1,1,1]SET $BIT(a,1) = 1SET $BIT(a,2) = 1SET $BIT(a,3) = 1WRITE !,"bitstring a=",$BIT(a,1),$BIT(a,2),$BIT(a,3)SET c = $BITLOGIC(a,2)WRITE !," a (length 2)="WRITE $BIT(c,1),$BIT(c,2),$BIT(c,3),$BIT(c,4)SET c = $BITLOGIC(~a,2)WRITE !,"~a (length 2)="WRITE $BIT(c,1),$BIT(c,2),$BIT(c,3),$BIT(c,4)The following example shows that when length is not specified, it defaults to the length ofthe longest bitstring. Shorter bitstrings are zero-filled before the logical operation is performed.// Set a to [1,1,1]SET $BIT(a,1) = 1SET $BIT(a,2) = 1SET $BIT(a,3) = 1// Set b to [1,1]SET $BIT(b,1) = 1SET $BIT(b,2) = 1SET c = $BITLOGIC(a&~b)WRITE !," a&~b="WRITE $BIT(c,1),$BIT(c,2),$BIT(c,3)SET c = $BITLOGIC(a&~b,3)WRITE !,"a&~b,3="WRITE $BIT(c,1),$BIT(c,2),$BIT(c,3)Here the two $BITLOGIC operations (with and without a length argument) both return thesame value: 001.190 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


See Also• $BIT function• $BITCOUNT function• $BITFIND function• $FACTOR function• Operators in Using <strong>Caché</strong> <strong>ObjectScript</strong>$CASE$CASECompares expressions and returns the value of the first matching case.$CASE(target,case:value,case:value,...,:default)ParameterstargetcasevaluedefaultA literal or expression the value of which is to be matched against cases.A literal or expression the value of which is to be matched with the resultsof the evaluation of target.The value to be returned upon a successful match of the correspondingcase.Optional — The value to be returned if no case matches target.DescriptionThe $CASE function compares target to a list of cases (literals or expressions), and returnsthe value of the first matching case. An unlimited number of case:value pairs can be specified.Cases are matched in the order specified (left-to-right); matching stops when the first exactmatch is encountered.If there is no matching case, default is returned. If there is no matching case and no defaultis specified, <strong>Caché</strong> issues an error.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 191


<strong>Caché</strong> <strong>ObjectScript</strong> FunctionsParameterstarget$CASE evaluates this expression once, then matches the result to each case in left-to-rightorder.caseA case can be a literal or an expression; matching of literals is substantially more efficientthan matching expressions, because literals can be evaluated at compile time. Each case mustbe paired with a value. An unlimited number of case and value pairs may be specified.valueA value can be a literal or an expression. Using $CASE as an argument of a GOTO commandor a DO command restricts value as follows:• When using a $CASE statement with a GOTO command, each value must be a validtag. It cannot be an expression.• When using a $CASE statement with a DO command, each value must be a valid DOargument. These DO arguments can include parameters.defaultThe default is specified like a case:value pair, except that there is no case specified betweenthe comma (used to separate pairs) and the colon (used to pair items). The default is alwaysthe final parameter specified in a $CASE function. The default value follows the same GOTOand DO restrictions as the value parameter.If there is no matching case and no default is specified, <strong>Caché</strong> issues an error.ExampleThe following example takes a number and returns corresponding name for a day of the week.Note that a default value “entry error” is provided:SET daynum=3WRITE $CASE(daynum,1:"Sunday",2:"Monday",3:"Tuesday",4:"Wednesday",5:"Thursday",6:"Friday",7:"Saturday",:"entry error")The following example takes a numeric input and writes out the appropriate explanatorystring:192 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$CHARREAD "Input a number 1-3: ",xSET multi=$CASE(x,1:"single",2:"double",3:"triple",:"input error")WRITE multiThe following example tests whether the character input is a letter or some other character:READ "Input a letter: ",xSET chartype=$CASE(x?1A,1:"letter",:"other")WRITE chartypeSee Also• DO command• GOTO command• IF command• $SELECT function$CHARConverts the integer value of an expression to the corresponding ASCII or Unicode character.$CHAR(expression,...)$C(expression,...)ParameterexpressionThe integer value to be converted.Description$CHAR returns the character that corresponds to the integer value specified by expression.This character can be an 8-bit (ASCII) character, or a 16-bit (Unicode) character. For 8-bitcharacters, the value in expression must evaluate to a positive integer in the range 0 to 255.For 16-bit characters, specify integers in the range 256 through 65534.You can specify expression as a comma-separated list, in which case $CHAR returns thecorresponding character for each expression in the list.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 193


<strong>Caché</strong> <strong>ObjectScript</strong> FunctionsParameterexpressionThe expression can be an integer value, the name of a variable that contains an integer value,or any valid <strong>Caché</strong> <strong>ObjectScript</strong> expression that evaluates to an integer value. To returncharacters for multiple integer values, specify a comma-separated list of expressions.ExamplesThe following example uses $CHAR in a FOR loop to output the characters for all ASCIIcodes in the range 65 to 90. These are the uppercase alphabetic characters.FOR i=65:1:90 {WRITE !,$CHAR(i) }The following two examples show the use of multiple expression values. The first returns“AB” and the second returns “AaBbCcDdEeFfGgHhIiJjKk”:WRITE $CHAR(65,66),!FOR i=65:1:75 {WRITE $CHAR(i,i+32) }The following example shows the use of a multibyte character. The character correspondingto the integer 960 is the symbol for pi:WRITE $CHAR(960)Notes$CHAR with the WRITE CommandWhen you use $CHAR to write characters with the WRITE command, the output charactersreset the positions of the special variables $X and $Y. This is true even for the NULL character(ASCII 0), which is not the same as a null string (""). As a rule, you should use $CHARwith caution when writing nonprinting characters, because such characters may produceunpredictable cursor positioning and screen behavior.Numeric Values in $CHAR ArgumentsYou can use signed numeric values for expression. <strong>Caché</strong> ignores negative numbers and onlyevaluates positive or unsigned numbers. In the following example, the $CHAR with signedintegers returns only the first and third expression, ignoring the second expression, which isa negative integer.WRITE !,$CHAR(65,66,67)WRITE !,$CHAR(+65,-66,67)194 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$CHARABCACYou can use decimal numeric values for expression. <strong>Caché</strong> ignores the decimal portion ofthe argument and only considers the integer portion. In the following example, $CHARignores the decimal portion of the number and produces the character represented by decimalASCII code 65, an uppercase A.WRITE $CHAR(65.5)Unicode Support$CHAR supports Unicode characters when represented by decimal integers.The Unicode value for a character is usually expressed as a 4-digit number in hexadecimalnotation, using the digits 0-9 and the letters A-F. However, standard functions in the <strong>Caché</strong><strong>ObjectScript</strong> language generally identify characters according to ASCII codes, which aredecimal values, not hexadecimal.Hence, the $CHAR function supports Unicode encoding by returning a character based onthe decimal Unicode value that was input, not the more standard hexadecimal value. Toconvert a decimal number to hexadecimal, use the $ZHEX function.Functions Related to $CHARThe $ASCII function is the inverse of $CHAR. You can use it to convert a character to itsequivalent decimal value. $ASCII converts all characters, including Unicode characters. Inaddition, all <strong>Caché</strong> platforms support the related functions, $ZLCHAR and $ZWCHAR.They are similar to $CHAR, but operate on a word (two bytes) or a long word (four bytes).You can use $ZISWIDE to determine if there are any multibyte (“wide”) characters in theexpression of $CHAR.See Also• READ command• WRITE command• $ASCII function• $ZHEX function• $ZLCHAR function• $ZWCHAR function<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 195


<strong>Caché</strong> <strong>ObjectScript</strong> Functions• $X special variable• $Y special variable$DATAChecks if a variable contains data.$DATA(variable,target)$D(variable,target)ParametersvariabletargetThe variable whose status is to be checked.Optional — A variable into which $DATA returns the current value ofvariable.DescriptionYou can use $DATA to test whether a variable contains data before attempting an operationon it. $DATA returns status information about the specified variable. The variable parametercan be the name of any variable (local variable, process-private global, or global), and caninclude a subscripted array element.The possible status values that may be returned are as follows:196 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$DATAStatusValue011011MeaningThe variable is undefined. Any reference would cause an error.The variable exists and contains data, but has no descendants. Note thatthe null string ("") qualifies as data.The variable identifies an array element that has descendants (contains adownward pointer to another array element) but does not contain data. Anydirect reference to such a variable will result in an error.For example, if $DATA(y) returns 10, set x=y will produce an error.The variable identifies an array element that has descendants (contains adownward pointer to another array element) and contains data. Variablesof this type can be referenced in expressions.Note:Status values 1 and 11 indicate only the presence of data, not the type of data.For more information on errors, refer to the $ZERROR special variable.ParametersvariableThe variable can be a local variable, a process-private global, or a global. It can be a subscriptedarray element within a variable, process-private global, or global. If a global variable,it can include an extended global reference. If a subscripted global variable, it can be a nakedglobal reference.targetAn optional parameter. Specify the name of a local variable, a process-private global, or aglobal. This target variable does not need to be defined. If target is specified, $DATA writesthe current data value of variable into target. If variable is undefined, the target value remainsunchanged.ExampleThis example writes a selected range of records from the ^client array, a sparse array consistingof three levels. The first level contains the client's name, the second the client's address, andthe third the client's accounts, account numbers, and balances. A client can have up to four<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 197


<strong>Caché</strong> <strong>ObjectScript</strong> Functionsseparate accounts. Because ^client is a sparse array there may be undefined elements at anyof the three levels. The contents for a typical record might appear as follows:^client(5) John Jones^client(5,1) 23 Bay Rd./Boston/MA 02049^client(5,1,1) Checking/45673/1248.00^client(5,1,2) Savings/27564/3270.00^client(5,1,3) Reserve Credit/32456/125.00^client(5,1,4) Loan/81263/460.00The code below provides a separate subroutine to handle the output for each of the three arraylevels. It uses the $DATA function at the start of each subroutine to test the current arrayelement.The $DATA=0 test in Level1, Level2, and Level3 tests whether the current array element isundefined. If TRUE, it causes the code to QUIT and revert to the previous level.The $DATA=10 test in Level1 and Level2 tests whether the current array element containsa pointer to a subordinate element, but no data. If TRUE, it causes the code to write out a“No Data” message. The code then skips to the FOR loop processing for the next lower level.There is no $DATA=10 test in Level3 because there are no elements subordinate to this level.The WRITE commands in Level2 and Level3 use the $PIECE function to extract theappropriate information from the current array element.Start Read !,"Output how many records: ",nRead !,"Start with record number: ",sFor i=s:1:s+(n1) {If $Data(^client(i)) {If $Data(^client(i))=10 {Write !," Name: No Data"}Else {Write !," Name: " ,^client(i)}If $Data(^client(i,1)) {If $Data(^client(i,1))=10 {Write !,"Address: No Data"}Else {Write !,"Address: ",$Piece(^client(i,1),"/",1)Write " , ",$Piece(^client(i,1),"/",2)Write " , ",$Piece(^client(i,1),"/",3)}}For j=1:1:4 {If $Data(^client(i,1,j)) {Write !,"Account: ",$Piece(^client(i,1,j),"/",1)Write " #: ",$Piece(^client(i,1,j),"/",2)Write " Balance: ",$Piece(^client(i,1,j),"/",3)}}}}Write !,"Finished."Quit198 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$DATAWhen executed, this code might produce output similar to the following:Output how many records: 3Start with record number: 10Name: Jane SmithAddress: 74 Hilltop Dr., Beverly, MA 01965Account: Checking #: 34218 Balance: 876.72Account: Reserve Credit #: 47821 Balance: 1200.00Name: Thomas BrownAddress: 46 Huron Ave., Medford, MA 02019Account: Checking #: 59363 Balance: 205.45Account: Savings #: 41792 Balance: 1560.80Account: Reserve Credit #: 64218 Balance: 125.52Name: Sarah CopleyAddress: No DataAccount: Checking #: 30021 Balance: 762.28NotesNaked Global <strong>Reference</strong>s$DATA sets the naked indicator when used with a global variable. The naked indicator isset even if the specified global variable in not defined (Status Value = 0).Subsequent references to the same global variable can use a naked global reference, as shownin the following example:IF $DATA(^A(1,2,3))#2 {SET x=^(3) }For further details on using $DATA with global variables and naked global references, seeUsing Multi-Dimensional Storage (Globals) in Using <strong>Caché</strong> Multi-Dimensional Storage.Global <strong>Reference</strong>s in a Networked EnvironmentUsing $DATA to repeatedly reference a global variable that is not defined (for example,$DATA(^x(1)) where ^x is not defined) always requires a network operation to test if theglobal is defined on the ECP server.Using $DATA to repeatedly reference undefined nodes within a defined global variable (forexample, $DATA(^x(1)) where any other node in ^x is defined) does not require a networkoperation once the relevant portion of the global (^x) is in the client cache.For further details, refer to Developing Distributed Applications in the <strong>Caché</strong> DistributedData Management Guide.Functions Related to $DATAFor related information, see $GET and $ORDER. Since $ORDER selects the next elementin an array that contains data, it avoids the need to perform $DATA tests when loopingthrough array subscripts.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 199


<strong>Caché</strong> <strong>ObjectScript</strong> FunctionsSee Also• KILL command• SET command• $GET function• $ORDER function• $ZUTIL(18) Undefined Variable Behavior function• Using Multi-Dimensional Storage (Globals) in Using <strong>Caché</strong> Multi-Dimensional Storage$DOUBLEReturns a number converted to a 64-bit floating point value.$DOUBLE(num)ParametersnumThe numeric value to be converted.Description$DOUBLE returns the number converted to the IEEE floating point data type. This type offloating point number can contain up to 15 digits. If num has more than 15 digits, $DOUBLErounds the decimal portion to the appropriate number of digits. If the integer portion of numis more than 15 digits, $DOUBLE rounds the integer to 15 digits and represents the additionaldigits with zeros.Note:At <strong>Caché</strong> 5.2, extremely large floating point numbers are not supported. The currentmaximum supported value for the DOUBLE data type is 1.79769e145. The minimumsupported value for the DOUBLE data type is either 2.22508e-308 (normal) or 4.9e-324 (denormalized).$DOUBLE generates floating point numeric values that accord with the IEEE floating pointstandard. It is primarily intended for interchange and compatibility with applications that usethis data type standard. In all other contexts, standard <strong>Caché</strong> decimal point numbers are moreexact, and are therefore preferable.200 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


Because numbers generated by $DOUBLE are rounded, equality comparisons should not beattempted between $DOUBLE values and standard <strong>Caché</strong> decimal point number values.The ZZDUMP command returns a different datatype value for list items that were generatedusing $DOUBLE.The <strong>Caché</strong> SQL data types DOUBLE and DOUBLE PRECISION represent IEEE floatingpoint numbers; the FLOAT data type represents standard <strong>Caché</strong> decimal point numbers.INF and NANFollowing the IEEE standard, $DOUBLE can return the strings INF (infinity) and NAN (nota number). While these are valid IEEE return values, they are not actual numbers. Therefore,the $ISVALIDNUM function returns a 0 for these values.$DOUBLE returns an INF value (or a -INF for negative numbers) when the numeric valueexceeds the available precision, as shown in the following example:SET x=$DOUBLE(1.2e300)WRITE !,"Double: ",xWRITE !,"Is number? ",$ISVALIDNUM(x)SET y= $DOUBLE(x*x)WRITE !,"Double squared: ",yWRITE !,"Is number? ",$ISVALIDNUM(y)$DOUBLE returns a NAN (not a number) value when the numeric value is invalid. Forexample, when an arithmetic expression involves two INF values, as shown in the followingexample. (An arithmetic expression involving a single INF value returns INF.)SET x=$DOUBLE(1.2e500)WRITE !,"Double: ",xWRITE !,"Is number? ",$ISVALIDNUM(x)SET y= $DOUBLE(x-x)WRITE !,"Double INF minus INF: ",yWRITE !,"Is number? ",$ISVALIDNUM(y)Integer DivideWith certain values, <strong>Caché</strong> floating point and IEEE double numbers yield a different integerdivide product. For example:WRITE !,"Divide operations:"WRITE !,"Cache /: ",4.1/.01 // 410WRITE !,"Double /: ",$DOUBLE(4.1)/.01 // 410WRITE !,"Integer divide operations:"WRITE !,"Cache \: ",4.1\.01 // 410WRITE !,"Double \: ",$DOUBLE(4.1)\.01 // 409ExamplesThe following example returns floating point numbers of 15 digits:$DOUBLE<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 201


<strong>Caché</strong> <strong>ObjectScript</strong> FunctionsWRITE !,$DOUBLE(999.12345678987654321)WRITE !,$DOUBLE(.99912345678987654321)WRITE !,$DOUBLE(999123456789876543.21)The following example returns the value of pi as a $DOUBLE value and as a standard <strong>Caché</strong>decimal value. This example shows that equality operations should not be attempted between$DOUBLE and standard <strong>Caché</strong> decimal numbers, and that the number of digits returned isgreater for standard <strong>Caché</strong> decimal numbers:SET x=$ZPISET y=$DOUBLE($ZPI)IF x=y { WRITE !,"Same" }ELSE { WRITE !,"Different"WRITE !,"standard: ",xWRITE !,"IEEE float: ",y }The following examples show that a floating point number is not necessarily equivalent to anumeric string of the same value:SET x=123.4567891234560SET y=123.4567891234567IF x=$DOUBLE(x) { WRITE !,"Same" }ELSE { WRITE !,"Different" }IF y=$DOUBLE(y) { WRITE !,"Same" }ELSE { WRITE !,"Different" }SET x=1234567891234560SET y=1234567891234567IF x=$DOUBLE(x) { WRITE !,"Same" }ELSE { WRITE !,"Different" }IF y=$DOUBLE(y) { WRITE !,"Same" }ELSE { WRITE !,"Different" }See Also• ZZDUMP command• $FNUMBER function• $NUMBER function• Data Types in the <strong>Caché</strong> SQL <strong>Reference</strong>202 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$EXTRACT$EXTRACTExtracts specified characters from a character string.$EXTRACT(string,from,to)$E(string,from,to)ParametersstringfromtoAn expression that evaluates to the target string from which the substringis to be extracted.Optional — The starting position within the target string from which to extracta character or the beginning of a range of characters. Specify either apositive integer (counting from 1), an asterisk (which specifies the lastcharacter of the string), or an asterisk followed by a negative integer. If fromis an asterisk, you cannot specify a to parameter.Optional — The end position (inclusive) for a range of characters to beextracted. Specify either a positive integer (counting from 1) or an asterisk(which specifies the last character of the string), or an asterisk followed bya negative integer (which specifies an end position counting backwardsfrom the last character of the string).Description$EXTRACT returns a substring from a specified position in string. The nature of the substringreturned depends on the parameters used.• $EXTRACT(string) extracts the first character in the string.• $EXTRACT(string,from) extracts a single character in the position specified by from.The from value can be an integer count from the beginning of the string, an asteriskspecifying the last character of the string, or an asterisk with a negative integer specifyinga count backwards from the end of the string. For example, if variable var1 contains thestring “ABCD”, the following example extracts “B” (the second character), then “D”(the final character), then “A” (3 characters before the final character):SET var1="ABCD"WRITE !,$EXTRACT(var1,2) // "B"WRITE !,$EXTRACT(var1,*) // "D"WRITE !,$EXTRACT(var1,*-3) // "A"• $EXTRACT(string,from,to) extracts the range of characters starting with the fromposition and ending with the to position. For example, if variable var2 contains the string<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 203


<strong>Caché</strong> <strong>ObjectScript</strong> Functions“1234Alabama567”, the following $EXTRACT functions both return the string“Alabama”:SET var2="1234Alabama567"WRITE !,$EXTRACT(var2,5,11)WRITE !,$EXTRACT(var2,*-9,*-3)You can also use the $EXTRACT function with the SET command to change the values ofspecified characters within a string. For example:SET var1="ABCD"SET $EXTRACT(var1,2)="Z"WRITE var1returns “AZCD”.ParametersstringThe string value can be a variable name, a numeric value, a string literal, or any valid <strong>Caché</strong><strong>ObjectScript</strong> expression.fromThe from value must be a positive integer, an asterisk (*), or an asterisk and a negativenumber. A from value with a negative number may include or omit blank spaces; all of thefollowing are permissible: *-3, * -3, * - 3.If the from integer value is greater than the number of characters in the string, $EXTRACTreturns a null string. If the from asterisk negative value is equal to or greater than the numberof characters in the string, $EXTRACT returns a null string.If from is an asterisk, attempting to specify a to value causes <strong>Caché</strong> to generate an error.If from is used with the to parameter, from identifies the start of the range to be extracted andmust be less than the value of to. If from equals to, $EXTRACT returns the single characterat the specified position. If from is greater than to, $EXTRACT returns a null string. If usedwith the to parameter, a from value less than 1 (zero, or a negative number) is treated as if itwere the number 1.toThe to parameter must be used with the from parameter. It must be a positive integer, anasterisk (*), or an asterisk followed by a negative integer. If the to value is an integer greaterthan or equal to the from value, $EXTRACT returns the specified substring. If the to value204 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


is an asterisk, $EXTRACT returns the substring beginning with the from character throughthe end of the string. If to is an integer greater than the length of the string, $EXTRACT alsoreturns the substring beginning with the from character through the end of the string. If to isless than from, $EXTRACT returns a null string.$EXTRACT ExamplesThe following example returns “D”, the fourth character in the string:SET x="ABCDEFGHIJK"WRITE $EXTRACT(x,4)The following example returns “K”, the last character in the string:SET x="ABCDEFGHIJK"WRITE $EXTRACT(x,*)In the following example, all the $EXTRACT functions return “J” the next-to-last characterin the string:SET n=-1SET m=1SET x="ABCDEFGHIJK"WRITE !,$EXTRACT(x,*-1)WRITE !,$EXTRACT(x,*-m)WRITE !,$EXTRACT(x,*+n)WRITE !,$EXTRACT(x,*-1,*-1)Note that a minus or plus sign is needed between the asterisk and the integer variable.The following example shows that the one-argument format is equivalent to the two-argumentformat when the from value is “1”. Both $EXTRACT functions return “H”.SET x="HELLO"WRITE !,$EXTRACT(x)WRITE !,$EXTRACT(x,1)The following example returns a substring “THIS IS” which is composed of the first throughseventh characters.SET x="THIS IS A TEST"WRITE $EXTRACT(x,1,7)The following example also returns the substring “THIS IS”. When the from variable containsa value less than 1, $EXTRACT treats that value as 1. Thus, the following example returnsa substring composed of the first through seventh characters.SET X="THIS IS A TEST"WRITE $EXTRACT(X,-1,7)The following example returns the last four characters of the string:$EXTRACT<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 205


<strong>Caché</strong> <strong>ObjectScript</strong> FunctionsSET X="THIS IS A TEST"WRITE $EXTRACT(X,*-3,*)$EXTRACT with SETYou can use $EXTRACT with the SET command to replace a specified character or rangeof characters with another value. The simplest form of this is a one-for-one substitution:SET foo="ABZD"SET $EXTRACT(foo,3)="C"WRITE fooyields “ABCD”.You can also extract a string and replace it with a string of a different length. For example,the following command extracts the string “Rhode Island” from foo and replaces it with thestring “Texas”, with no padding.SET foo="Deep in the heart of Rhode Island"SET $EXTRACT(foo,22,33)="Texas"WRITE fooyields "Deep in the heart of Texas".You can extract a string and set it to the null string, removing the extracted characters fromthe string:SET foo="ABCzzzzzD"SET $EXTRACT(foo,4,8)=""WRITE fooyields “ABCD”.If you specify to larger than the string, $EXTRACT pads with blank spaces:SET foo="ABCD"SET $EXTRACT(foo,8)="X"WRITE fooyields “ABCD^^^X” (here a blank space is shown using “^”).If you specify from larger than to, no replacement occurs:SET foo="ABCD"SET $EXTRACT(foo,4,3)="X"WRITE fooyields “ABCD”.SET $EXTRACT ExamplesThe following example changes the value of x from “ABCD” to “ZBCD”:206 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$EXTRACTSET x="ABCD"SET $EXTRACT(x,1)="Z"WRITE xThe following example replaces “ABCD” with “GHIJ”.SET x="ABCD"SET $EXTRACT(x,1,4)="GHIJ"WRITE xIn the following example, assume that variable x does not exist.KILL xSET $EXTRACT(x,1,4)="ABCD"WRITE xThe SET command creates variable x and assigns it the value “ABCD”.You can also use SET $EXTRACT to add or remove character positions in a target variable.To add character positions, specify a from value or a from,to range that exceeds the lengthof the target variable. For example, if x contains “ABCD,” the following $EXTRACTfunction inserts the value “Z” in the tenth position:SET x="ABCD"SET $EXTRACT(x,10)="Z"WRITE xBecause 10 exceeds the number of characters in x, SET $EXTRACT fills the intervening positions(that is, position 5 through 9) with spaces. As a result, x now contains the value“ABCD^^^^^Z” , where ^ indicates a space.The following example inserts the value “Y” in the eleventh position, but no additionalcharacters in positions 12 and 13.SET x="ABCD"SET $EXTRACT(x,11,13)="Y"WRITE xAs a result, the original x value (“ABCD”) is changed to “ABCD^^^^^^Y” and x now has alength of 11. (If the assigned value “Y” were three characters, instead of just one, positions12 and 13 would be filled as well.)To remove character positions, extract a character or range and replace it with the null string.The following results in a two-character string with the value “AD”:SET x="ABCD"SET $EXTRACT(x,2,3)=""WRITE x<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 207


<strong>Caché</strong> <strong>ObjectScript</strong> FunctionsThe following example shortens a character string by extracting a from,to range larger thanthe number of values in the replacement string.SET x="ABCDEFGH"SET $EXTRACT(x,3,6)="Z"WRITE xinserts the value “Z” in the third position and removes positions 4, 5 and 6. Variable x nowcontains the value “ABZGH” and has a length of 5.Notes$EXTRACT Compared with $PIECE and $LIST$EXTRACT returns a substring of characters by integer position from a string. $PIECE and$LIST both work on specially formatted strings.$PIECE returns a substring from an ordinary string by using special delimiter characterswithin the string.$LIST returns a sublist of elements from an encoded list by the integer position of elements(not characters). $LIST cannot be used on ordinary strings, and $EXTRACT cannot be usedon encoded lists.$EXTRACT and UnicodeThe $EXTRACT function operates on characters, not bytes. Therefore, Unicode strings arehandled the same as ASCII strings, as shown in the following example using the Unicodecharacter for “pi” ($CHAR(960)):SET a="QT PIE"SET b="QT "_$CHAR(960)SET a1=$EXTRACT(a,-33,4)SET a2=$EXTRACT(a,4,4)SET a3=$EXTRACT(a,4,99)SET b1=$EXTRACT(b,-33,4)SET b2=$EXTRACT(b,4,4)SET b3=$EXTRACT(b,4,99)WRITE !,"ASCII form returns ",!,a1,!,a2,!,a3WRITE !,"Unicode form returns ",!,b1,!,b2,!,b3See Also• SET command• $FIND function• $LENGTH function• $PIECE function208 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$FACTOR• $ZEXP function• $ZLN function$FACTORConverts integer to bitstring.$FACTOR(num,scale)ParametersnumscaleAn expression that evaluates to an integer. Fractional numbers are roundedto an integer.Optional — An integer used as a power-of-ten exponent (scientific notation)multiplier for num. The default is 0.Description$FACTOR returns the binary bitstring that corresponds to the supplied integer. If you specifya decimal number as num, $FACTOR rounds this number to an integer, and then returns thebinary bitstring that corresponds to this integer. When rounding numbers, <strong>Caché</strong> rounds thefraction .5 up to the next highest integer.The binary string returned specifies bit positions starting from position 1 (left-to-right). Thiscorresponds to the bitstrings used by the various $BIT functions.ParametersnumA number (or an expression that evaluates to a number). $FACTOR applies the scaleparameter (if supplied), converts this number to an integer by rounding, and then returns thecorresponding bitstring. num can be positive or negative. If num is zero, or rounds to zero,or is the null string (""), $FACTOR returns a null string.scaleAn integer that specifies the scientific notation exponent to apply to num. For example, ifscale is 2, then scale represents 10 exponent 2, or 100. This scale value is multiplied by num.For example, $FACTOR(7,2) returns the bitstring that corresponds to the integer 700. Thismultiplication is done before rounding num to an integer. By default, scale is 0.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 209


<strong>Caché</strong> <strong>ObjectScript</strong> FunctionsExamplesThe following example show the conversion of the integers 1 through 9 to bitstrings:SET x=1WHILE x


$FIND$FINDFinds a substring by value and returns an integer specifying its end position in the string.$FIND(string,substring,position)$F(string,substring,position)ParametersstringsubstringpositionThe target string that is to be searched. It can be a variable name, anumeric value, a string literal, or any valid <strong>Caché</strong> <strong>ObjectScript</strong>expression.The substring that is to be searched for. It can be a variable name, anumeric value, a string literal, or any valid <strong>Caché</strong> <strong>ObjectScript</strong>expression.Optional — A position within the target string at which to start thesearch. It must be a positive integer.Description$FIND returns an integer specifying the end position of a substring within a string. $FINDsearches string for substring. If substring is found, $FIND returns the integer position of thefirst character following substring. If substring is not found, $FIND returns a value of 0.You can include the position option to specify a starting position for the search. If positionis greater than the number of characters in string, $FIND returns a value of 0.ExamplesFor example, if variable var1 contains the string “ABCDEFG” and variable var2 containsthe string “BCD,” the following $FIND returns the value 5, indicating the position of thecharacter (“E”) that follows the var2 string:SET var1="ABCDEFG",var2="BCD"WRITE $FIND(var1,var2)The following example returns 4, the position of the character immediately to the right of thesubstring “FOR”.SET X="FOREST"WRITE $FIND(X,"FOR")In the following example, $FIND searches for a substring that is not in the string. It returnszero (0):<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 211


<strong>Caché</strong> <strong>ObjectScript</strong> FunctionsSET X="ENGINE",Y="Q"WRITE $FIND(X,Y)The following example returns 14, the position of the character immediately to the right ofthe first occurrence of “R” after the seventh character in X.SET X="EVERGREEN FOREST",Y="R"WRITE $FIND(X,Y,7)In the following example, $FIND begins its search after the last character in string. It returnszero (0):SET X="EVERGREEN FOREST",Y="R"WRITE $FIND(X,Y,20)The following example uses name indirection to return 6, the position of the characterimmediately to the right of the substring “THIS”:SET Y="x",x="""THIS IS A TEST"""WRITE $FIND(@Y,"THIS")For more information, refer to Indirection in Using <strong>Caché</strong> <strong>ObjectScript</strong>.Notes$FIND, $EXTRACT, $PIECE, and $LIST• $FIND locates a substring by value and returns a position.• $EXTRACT locates a substring by position and returns the substring value.• $PIECE locates a substring by a delimiter character or delimiter string, and returns thesubstring value.• $LIST operates on specially encoded strings. It locates a substring by substring countand returns the substring value.The $FIND, $EXTRACT, $LENGTH, and $PIECE functions operate on standard characterstrings. The various $LIST functions operate on encoded character strings, which areincompatible with standard character strings. The sole exception is the one-argument andtwo-argument forms of $LIST, which take an encoded character string as input, but outputa single element value as a standard character string.See Also• $EXTRACT function• $LENGTH function212 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$FNUMBER• $LIST function• $PIECE function$FNUMBERFormats a numeric value with a specified format; optionally rounds to a specified precision.$FNUMBER(inumber,format,decimal)$FN(inumber,format,decimal)ParametersinumberformatdecimalThe number that is to be formatted. It can be a numeric value, the nameof a numeric variable, or any valid <strong>Caché</strong> <strong>ObjectScript</strong> expression thatevaluates to a numeric value.A format specification of how the number is to be formatted. It is a stringconsisting of zero or more format codes described below.Optional — The number of decimal digits to be included in the returnednumber.Description$FNUMBER returns the number specified by inumber in the specified format.ParametersformatThe possible format codes are as follows. You can specify them singly or in combination.Code+-DescriptionReturns a non-negative number prefixed by the PlusSign property of the currentlocale (“+” by default). If the number is negative, it returns the number prefixedby the MinusSign property of the current locale (“-” by default).Returns a negative number without prefixing it by the MinusSign property ofthe current locale. Otherwise, it returns the number without any leading sign.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 213


<strong>Caché</strong> <strong>ObjectScript</strong> FunctionsCode,.TPDescriptionReturns the number with the value of the NumericGroupSeparator property ofthe current locale (“,” by default) inserted every NumericGroupSize (3 by default)numeral to the left of the decimal point. Combining “.” and “,” formats resultsin a error.Always returns the number using European formatting. Combining “.” and “,”formats results in a error .Returns the number with a trailing sign if a prefix sign would otherwise havebeen generated. However, it does not force a trailing sign. To produce a trailingsign for a non-negative number (positive or zero), you must also specify the“+” format code. To produce a trailing sign for a negative number, you mustnot specify the “-” format code. The trailing sign used is determined by thePlusSign and MinusSign properties of the current locale respectively. A trailingspace character, but no sign, is inserted in the case of a non-negative numberwith “+” omitted or in the case of a negative number with “-” specified.Returns a negative number in parentheses and without a leading MinusSignlocale property value. Otherwise, it returns the number without parentheses,but with a leading and trailing space character. This code cannot be used withthe “+”, “-”, or “T” format codes; attempting to do so results in a error.Some format code combinations conflict and may produce a error. For example,in the case of a negative number “TP” attempts to both insert a trailing sign and place thenumber in parentheses.The $DOUBLE function can return the values INF (infinite) and NAN (not a number). INFcan take a negative sign; format codes represent INF as if it were a number. For example:+INF, INF-, (INF). NAN does not take a negative sign; format codes represent NAN as ifit were a positive number. For example: +NAN (“+” format), NAN+ (“+T” format), NAN (“P”format, which adds a leading and trailing space).decimalRounding is performed before the number is truncated or zero filled. It can be specified as apositive integer value, the name of an integer variable, or any valid <strong>Caché</strong> <strong>ObjectScript</strong>expression that evaluates to a positive integer. If the decimal parameter is 0, the number isreturned as an integer, with no decimal point. If the decimal parameter is greater than thenumber of decimal digits in the number, the remaining positions are zero filled. If the numberitself is less than 1, $FNUMBER inserts a leading zero before the decimal point.214 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


You can include the decimal option to control the number of fractional digits returned, afterrounding is performed. The decimal parameter must evaluate to an integer. For example,assume that variable c contains the number 6.25198.SET c="6.25198"SET x=$FNUMBER(c,"+",3)SET y=$FNUMBER(c,"+",8)WRITE !,x,!,yThe first $FNUMBER returns +6.252 and the second returns +6.25198000. Zero fill is performedif the decimal parameter exceeds the number of fractional digits in the number.ExamplesThe following examples show how the different formatting designations can affect thebehavior of $FNUMBER. These examples assume that the current locale is the default locale.The following example returns +124329; $FNUMBER forces a plus sign on the value of Abecause A is non-negative:SET A=124329WRITE $FNUMBER(A,"+")The following example returns 30.567; $FNUMBER removes the negative sign from thevalue of B.SET B=-30.567WRITE $FNUMBER(B,"-")The following example returns 1,234,567.81; $FNUMBER inserts a comma every 3numerals to the left of the decimal point of C.SET C=1234567.81WRITE $FNUMBER(C,",")The following example returns 1.234.567,81; $FNUMBER inserts European formatting toC.SET D=1234567.81WRITE $FNUMBER(D,".")The following example returns 124,329.00; $FNUMBER inserts a comma and adds a decimalpoint and two zeros to the value of C.SET C=124329WRITE $FNUMBER(C,",",2)$FNUMBERThe following example shows how $FNUMBER inserts the trailing character after variables:<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 215


<strong>Caché</strong> <strong>ObjectScript</strong> Functions123+123–SET A=123SET B=-123SET x=$FNUMBER(A,"T+")SET y=$FNUMBER(B,"T")SET z=$FNUMBER(A,"T")WRITE !,x,!,yWRITE !,z,"space after var z"123 space after var zThe following example returns (30.567); $FNUMBER places the value of B in parenthesesand removes the minus sign.SET B=-30.567WRITE $FNUMBER(B,"P")NotesDecimal Delimiter$FNUMBER will use the value of the DecimalSeparator property of the current locale asthe delimiter between the whole part and fractional part of a number (unless the “.” formatcode is used). The default value of DecimalSeparator is “.” and all documentation uses thisdelimiter.See Also• $JUSTIFY function• $INUMBER function• $ISVALIDNUM function• $NORMALIZE function• $NUMBER function• More information on locales in Customized National Language Translations216 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$GET$GETReturns the data value of a specified variable.$GET(variable,default)$G(variable,default)ParametersvariabledefaultA local or global variable, subscripted or unsubscripted. The variablemay be undefined.Optional — The value to be returned if the variable is undefined. If avariable, it must be defined.Description$GET returns the data value of a specified variable. The handling of undefined variablesdepends on whether you specify a default parameter.• $GET(variable) returns the value of the specified variable, or the null string if the variableis undefined. The variable parameter value can be the name of any variable, including asubscripted array element (either local or global).• $GET(variable,default) provides a default value to return if the variable is undefined. Ifthe variable is defined, $GET returns its value.ParametersvariableThe variable whose data value is to be returned. It can be a local variable or a global variable,either subscripted or unsubscripted. The variable does not need to be a defined variable. Thevariable can be defined and set to the null string (""). If a global variable, it can contain anextended global reference. If a subscripted global variable, it can be specified using a nakedglobal reference. Even when referencing an undefined subscripted global variable, variableresets the naked indicator, affecting future naked global references, as described below.defaultThe data value to be returned if variable is undefined. It can any expression, including a localvariable or a global variable, either subscripted or unsubscripted. If a variable, it must bedefined variable; if default is an undefined variable, $GET issues an error,<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 217


<strong>Caché</strong> <strong>ObjectScript</strong> Functionseven when variable is defined. If a global variable, it can contain an extended global reference.If a subscripted global variable, it can be specified using a naked global reference. If present,default resets the naked indicator, affecting future naked global references, as describedbelow.ExamplesIn the following example, the variable test is defined and the variable xtest is undefined. (TheZWRITE command is used because it explicitly returns a null string value.)KILL xtestSET test="banana"SET tdef=$GET(test),tundef=$GET(xtest)ZWRITE tdef ; $GET returned value of testZWRITE tundef ; $GET returned null string for xtestWRITE !,$GET(xtest,"none"); $GET returns default of "none" for undefined variableNotes$GET Compared to $DATA$GET provides an alternative to $DATA tests for both undefined variables ($DATA=0) andarray nodes that are downward pointers without data ($DATA=10). If the variable is eitherundefined or a pointer array node without data, $GET returns a null string ("") without anundefined error. For example, you can recode the following lines:as:IF $DATA(^client(i))=10 {WRITE !!,"Name: No Data"GOTO Level1+3}IF $GET(^client(i))="" {WRITE !!,"Name: No Data"GOTO Level1+3}Note that $DATA tests are more specific than $GET tests because they allow you to distinguishbetween undefined elements and elements that are downward pointers only. Forexample, the lines:IF $DATA(^client(i))=0 { QUIT }ELSEIF $DATA(^client(i))=10 {WRITE !!,"Name: No Data"GOTO Level1+3}could not be recoded as:218 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$GETIF $GET(^client(i))="" { QUIT }ELSEIF $GET(^client(i))="" {WRITE !!,"Name: No Data"GOTO Level1+3}The two lines perform different actions depending on whether the array element is undefinedor a downward pointer without data. If $GET were used here, only the first action (QUIT)would ever be performed. You could use $DATA for the first test and $GET for the second,but not the reverse ($GET for the first test and $DATA for the second).Defaults with $GET and $SELECT$GET(variable,default) allows you to return a default value when a specified variable isundefined. The same operation can be performed using a $SELECT function.However, unlike $SELECT, the second argument in $GET is always evaluated.The fact that $GET always evaluates both of its arguments is significant if variable anddefault both make subscripted global references and thus both modify the naked indicator.Because the arguments are evaluated in left-to-right sequence, the naked indicator is set tothe default global reference, regardless of the whether $GET returns the default value. Forfurther details on using $GET with global variables and the naked indicator, see Using Multi-Dimensional Storage (Globals) in Using <strong>Caché</strong> Multi-Dimensional Storage.Handling Undefined Variables$GET defines handling behavior if a specified variable is undefined. The basic form of $GETreturns a null string ("") if the specified variable is undefined.$DATA tests if a specified variable is defined. It returns 0 if the variable is undefined.The $ZUTIL(18) function defines handling behavior for all undefined variables for the currentprocess. The $ZUTIL(69,0) function defines handling behavior for all undefined variablessystem-wide. Setting $ZUTIL(18) or $ZUTIL(69,0) has no effect on $GET or $DATAhandling of specified variables.See Also• $DATA function• $SELECT function• $ZUTIL(18) Set Undefined Variable Handling function• $ZUTIL(69,0) Set Undefined Variable Handling System-wide function• Using Multi-Dimensional Storage (Globals) in Using <strong>Caché</strong> Multi-Dimensional Storage<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 219


<strong>Caché</strong> <strong>ObjectScript</strong> Functions$INCREMENTAdds a specified increment to the existing value of a local or global variable.$INCREMENT(variable,num)$I(variable,num)ParametersvariablenumThe variable whose value is to be incremented. It can specify a localvariable, a process private global, or a global variable and can be eithersubscripted or unsubscripted. The variable need not be defined. If thevariable is not defined, or is set to the null string (""), $INCREMENTtreats it as having an initial value of zero and increments accordingly.Only variables may be specified; a literal value cannot be specifiedhere.Optional — The numeric increment you want to add to variable. Thevalue can be a number (integer or decimal, positive or negative), astring containing a number, or any expression which evaluates to anumber. Leading and trailing blanks and multiple signs are evaluated.A string is evaluated until the first nonnumeric character is encountered.The null string ("") is evaluated as zero.If you do not specify num for the second argument, <strong>Caché</strong> defaults toincrementing variable by 1.Description$INCREMENT resets the value of a variable by adding a specified increment to the existingvalue of the variable and returning the incremented value. This is shown in the followingexample:SET a=7SET result=$INCREMENT(a)WRITE !,result /* result is 8 (a+1) */WRITE !,a /* variable a is also now 8 */The variable parameter can be a local variable, a process private global, or a global variable.It can be subscripted or unsubscripted. It cannot be a literal. If this variable is not defined, orset to a null string, it is treated as having a value of zero.220 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


The num parameter can be a positive number, incrementing the value of the variable, or anegative number, decrementing the value of the variable. If you do not specify an increment,<strong>Caché</strong> uses the default increment of one (1).You can use the $GET function to return the current value of a variable.$INCREMENT performs this increment as an atomic operation, which does not require theuse of the LOCK command.If multiple processes simultaneously increment the same global through $INCREMENT,each process receives a unique, increasing number (or decreasing number if num is negative).In some situations, certain numbers may be skipped due to timing issues. For further detailson using $INCREMENT with global variables, see Using Multi-Dimensional Storage(Globals) in Using <strong>Caché</strong> Multi-Dimensional Storage.<strong>Caché</strong> does not restore the original, non-incremented value if $INCREMENT is in a transactionthat is rolled back.Incrementing Strings$INCREMENT is generally used for incrementing a variable containing a numeric value.However, it does accept a variable containing a string. The following rules apply when using$INCREMENT on a string:• A null string ("") is treated as having a value of zero.• A numeric string ("123" or "+0012.30") is treated as having that numeric value. Thestring is converted to canonical form: leading and trailing zeros and the plus sign areremoved.• A mixed numeric/nonnumeric string ("12AB" or "1,000") is treated as the numeric valueup to the first nonnumeric character and then truncated at that point. (Note that a commais a nonnumeric character.) The resulting numeric substring is converted to canonicalform: leading and trailing zeros and the plus sign are removed.• A nonnumeric string ("ABC" or "$12") is treated as having a value of zero.$INCREMENT• Exponent operations are performed. For example, if strvar="3E2", $INCREMENT treatsit as having a value of 300.• Arithmetic operations are not performed. For example, if strvar="3+7", $INCREMENTwill truncate the string at the plus sign (treating it as a nonnumeric character) and incrementstrvar to 4.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 221


<strong>Caché</strong> <strong>ObjectScript</strong> Functions• Multiple uses of a string variable in a single $INCREMENT statement should be avoided.For example, avoid concatenating a string variable to the increment of that variable:strvar_$INCREMENT(strvar). This returns unpredictable results.ExamplesThe following example increments the value of myvar by n. Note that myvar does not haveto be a prior defined variable:SET n=4KILL myvarSET VAL=$INCREMENT(myvar,n) ; returns 4WRITE !,myvarSET VAL=$INCREMENT(myvar,n) ; returns 8WRITE !,myvarSET VAL=$INCREMENT(myvar,n) ; returns 12WRITE !,myvarThe following example adds incremental values to the process private variable ^||xyz using$INCREMENT. The one-argument form of $INCREMENT increments by 1; the twoargumentform increments by the value specified in the second argument. In this case, thesecond argument is a floating point number.KILL ^||xyzWRITE !,$INCREMENT(^||xyz) ; returns 1WRITE !,$INCREMENT(^||xyz) ; returns 2WRITE !,$INCREMENT(^||xyz) ; returns 3WRITE !,$INCREMENT(^||xyz,3.14) ; returns 6.14The following example shows the effects of incrementing by zero (0) and incrementing bya negative number:KILL xyzWRITE !,$INCREMENT(xyz,0) ; initialized as zeroWRITE !,$INCREMENT(xyz,0) ; still zeroWRITE !,$INCREMENT(xyz) ; increments by 1 (default)WRITE !,$INCREMENT(xyz) ; increments by 1 (=2)WRITE !,$INCREMENT(xyz,-1) ; decrements by -1 (=1)WRITE !,$INCREMENT(xyz,-1) ; decrements by -1 (=0)WRITE !,$INCREMENT(xyz,-1) ; decrements by -1 (=-1)The following example shows the effects of incrementing using mixed (numeric and nonnumeric)num strings and the null string:222 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$INCREMENTKILL xyzWRITE !,$INCREMENT(xyz,""); null string initializes to 0WRITE !,$INCREMENT(xyz,2); increments by 2WRITE !,$INCREMENT(xyz,""); null string increments by 0 (xyz=2)WRITE !,$INCREMENT(xyz,"3A4"); increments by 3 (rest of string ignored)WRITE !,$INCREMENT(xyz,"A4"); nonnumeric string evaluates as zero (xyz=5)WRITE !,$INCREMENT(xyz,"1E2"); increments by 100 (exponential notation)Notes$INCREMENT and $ZINCREMENT$INCREMENT and $ZINCREMENT have the same syntax and effects. You can use$ZINCREMENT in any situation in which you would use $INCREMENT.$INCREMENT and Global VariablesYou can use $INCREMENT on a global variable or a subscript node of a global variable.You can access a global variable mapped to another namespace using an extended globalreference. You can access a subscripted global variable using a naked global reference.<strong>Caché</strong> evaluates parameters in left-to-right order. If num (the amount to increment) is a subscriptedglobal, <strong>Caché</strong> uses this global reference to set the naked indicator, affecting all subsequentnaked global references.Locking and Simultaneous Global Increments$INCREMENT and $ZINCREMENT do not perform a lock operation when they incrementvariable nor does using the LOCK command on variable prevent $INCREMENT fromincrementing or decrementing its value. For example, suppose process 1 executes a lock on^COUNTER:LOCK ^COUNTERThen suppose, process 2 increments ^COUNTER:SET x=$INCREMENT(^COUNTER,VAL)Process 2 is not prevented from incrementing ^COUNTER by the lock held by process 1.The two processes are not guaranteed their own unique ^COUNTER values unless both areusing $INCREMENT.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 223


<strong>Caché</strong> <strong>ObjectScript</strong> Functions$INCREMENT and Transaction ProcessingThe common usage for $INCREMENT is to increment a counter before adding a new entryto a database. $INCREMENT provides a way to do this very quickly, avoiding the use ofthe LOCK command and, in distributed environments, avoiding synchronous network trips.The trade-off for this is that the counter is not locked. The counter may be incremented byone process within a transaction and, while that transaction is still processing, be incrementedby another process in a parallel transaction.In the event either transaction (or any other transaction that uses $INCREMENT) must berolled back (with the TROLLBACK command), counter increments are ignored. The countervariables are not decremented since it is not clear whether the resulting counter value wouldbe valid. In all likelihood, such a rollback would be disastrous for other transactions.See Also• TROLLBACK command• $GET function• $ZINCREMENT function• Using <strong>ObjectScript</strong> for Transaction Processing in Using <strong>Caché</strong> <strong>ObjectScript</strong>$INUMBERValidates a numeric value and converts it to internal format.$INUMBER(fnumber,format,erropt)$IN(fnumber,format,erropt)ParametersfnumberformaterroptThe numeric value to be converted to the internal format. It can be anumeric or string value, a variable name, or any valid <strong>Caché</strong> <strong>ObjectScript</strong>expression.A format specification indicating which external numeric formats are validrepresentations of numbers. It is a string consisting of one or more validformat codes described below.Optional — The expression returned if fnumber is considered invalidbased on format.224 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


DescriptionThe $INUMBER function validates the numeric value fnumber using the formats specifiedin format. It then converts it to the internal <strong>Caché</strong> format.If fnumber does not correspond to the specified format and you have not specified erropt,<strong>Caché</strong> generates an error. If you have specified erropt, an invalidnumeric value returns the erropt string.Parametersformat$INUMBERThe possible format codes are as follows. You can specify them singly or in combination toinstruct $INUMBER to adhere strictly to the format rules. If no format codes are entered,$INUMBER will be as flexible as possible in validating fnumber (see Null Format ProvidesMaximum Flexibility for more information).Code+-PLT,.DescriptionMandatory sign. It can be either leading or trailing unless restricted by eitheran “L” or a “T” format code.Unsigned. No sign may be present in fnumber.Negative numbers must be enclosed in parentheses. Non-negative numbersmust be unsigned, and may have or omit leading and trailing spaces.Leading sign. Sign, if present, must precede the numerical portion of fnumber.Parentheses are not permitted.Trailing sign. Sign, if present, must follow the numerical portion of fnumber.Parentheses are not permitted.Expects fnumber to use the format specified by properties in the currentlocale. The NumericGroupSeparator (“,” by default) may or may not appearin fnumber, but if present, it must consistently appear every NumericGroupSize(3 by default) digits to the left of the decimal point.Requires European numeric group separators (“.”) and European decimalsymbols (“,”) regardless of the current locale. It also requires the use of thePlusSign and MinusSign from the default locale (“+” and “-” respectively).Periods are optional, but if present must consistently appear every three digits(the value of the NumericGroupSeparator property of the default locale) tothe left of the decimal comma.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 225


<strong>Caché</strong> <strong>ObjectScript</strong> FunctionsWhen “+”, “-” and “P” Format Codes are AbsentWhen format does not include any of the “+”, “-”, or “P” codes, then fnumber may containany one of the following:• No sign or parentheses.• Either the PlusSign locale property (“+” by default) or the MinusSign locale property (“-” by default) but not both. The position of this sign is determined by the “L” or the “T”format code if specified.• Leading and trailing parentheses.When “L”, “T” and “P” Format Codes are AbsentWhen format does not include any of the “L”, “T”, or “P” format codes, any sign present infnumber may be either leading or trailing (but not both).When “,” and “.” Format Codes are AbsentWhen format does not include either the “,” or “.” format codes, fnumber may optionallyhave NumericGroupSeparator symbols appear anywhere to the left or right of the DecimalSeparator,if any. However, each NumericGroupSeparator must have at least one digit to itsimmediate left and one to its immediate right.Mutually Exclusive Format CodesSome format codes conflict with each other. Each of the following pairs of format codes aremutually exclusive and result in an error:• “-+” results in a error• “-P” or “+P” result in a error• “TP” or “LP” result in a error• “TL” results in a error• “,.” results in a errorA error is also generated if you specify an invalid format code character.Null Format Provides Maximum FlexibilityYou can specify format as a null string. This is called a null format. When a null format isspecified, $INUMBER accepts a fnumber value with any one of the following sign conventions:226 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$INUMBER• No sign or parentheses.• Either a leading or trailing MinusSign, but not both.• Either a leading or trailing PlusSign, but not both.• Leading and trailing parentheses.When a null format is specified, fnumber may optionally have NumericGroupSeparatorsymbols appear anywhere to the left or right of the DecimalSeparator, if any. However, eachNumericGroupSeparator must have at least one digit to its immediate left and one to itsimmediate right. Sign rules are flexible, and leading and trailing blanks and zeros are ignored.Thus, the following two commands:WRITE !,$INUMBER("+1,23,456,7.8,9,100","")WRITE !,$INUMBER("0012,3456,7.891+","")are both valid and return the same number, formatted according to the default locale. However,WRITE $INUMBER("1,23,,345,7.,8,9,","")is invalid because of the adjacent commas, the adjacent period and comma, and the trailingcomma. It generates an error.Behavior Common to All FormatsRegardless of the specified format codes, $INUMBER always ignores leading and trailingblank spaces or zeros, but considers fnumber to be invalid if it has any of the followingcharacteristics:• Both a PlusSign and a MinusSign• More than one PlusSign or MinusSign• Parentheses and a PlusSign• Parentheses and a MinusSign• More than one DecimalSeparator• Embedded Spaces• The $DOUBLE values INF or NAN• Any characters other than the following:- Numeric digits- “(“<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 227


<strong>Caché</strong> <strong>ObjectScript</strong> Functions- “)”- Leading or trailing spaces- The DecimalSeparator specified by the current locale (if format doesn't include “.”)- The NumericGroupSeparator specified by the current locale (if format doesn't include“.”)- The PlusSign property specified by the current locale (if format doesn't include “.”)- The MinusSign property specified by the current locale (if format doesn't include“.”)- “.” (if format includes “.”)- “,” (if format includes “.”)- “+” (if format includes “.”)- “-” (if format includes “ .”)ExamplesThese examples illustrate how different formats affect the behavior of $INUMBER. All ofthese examples assume the current locale is the default locale.In the following example, $INUMBER accepts a leading minus sign because of the “L”format code and returns -123456789.12345678:WRITE $INUMBER("-123,4,56,789.1234,5678","L")In the following example, $INUMBER generates an error becausethe sign is leading but the “T” format code specifies that trailing signs must be used:WRITE $INUMBER("-123,4,56,789.1234,5678","T")In the following example, the first $INUMBER succeeds and returns a negative number.The second $INUMBER generates an error because fnumber includesa sign but the “P” format code specifies that negative numbers must be enclosed in parenthesesrather than signed:WRITE !,$INUMBER("(123,4,56,789.1234,5678)","P")WRITE !,$INUMBER("-123,4,56,789.1234,5678","P")In the following example, $INUMBER generates an error because asign is present but the “-” format code specifies that numbers must be unsigned:WRITE $INUMBER("-123,4,56,789.1234,5678","-")228 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


In the following example, $INUMBER fails but does not generate an error due to the illegaluse of a sign, but instead returns as its value the string “ERR” specified as the erropt:WRITE $INUMBER("-123,4,56,789.1234,5678","-","ERR")The following example returns -23456789.123456789; $INUMBER accepts the specifiedfnumber as valid because the leading sign follows the formatting specified by “L” and thestrict spacing of commas every three digits to the left of the decimal place with no commasto its right follows the strict formatting specified by the “,” code:WRITE $INUMBER("-23,456,789.123456789","L,")NotesDifferences between $INUMBER and $FNUMBERMost format codes have similar meanings in the $INUMBER and $FNUMBER functions,but the exact behavior triggered by each code differs by function because of the nature of thevalidations and conversions being performed.In particular, the “-” and “+” format codes don't have quite the same meaning for $INUMBERas they do for $FNUMBER. With $FNUMBER, “-” and “+” are not mutually exclusive,and “-” only affects the MinusSign (by suppressing it), and “+” only affects the PlusSign (byinserting it). With $INUMBER, “-” and “+” are mutually exclusive. “-” means no sign ispermitted, and “+” means there must be a sign.In addition, $INUMBER supports the “L” format code, while $FNUMBER does not.Decimal Delimiter$INUMBER will use the value of the DecimalSeparator property of the current locale as thedelimiter between the whole part and fractional part of a number (unless the format code is“.”). The default value of DecimalSeparator is “.” and all documentation uses this delimiter.Numeric Group Delimiter$INUMBER will use the value of the NumericGroupSeparator property of the current locale(“,” by default) as the delimiter between groups of digits in the whole part of fnumber. Thesize of these groups is determined by the NumericGroupSize property of the current locale.When the “.” format code is specified, this delimiter is a “.” and appears every three digitsregardless of the current locale.See Also• $FNUMBER function$INUMBER<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 229


<strong>Caché</strong> <strong>ObjectScript</strong> Functions• $ISVALIDNUM function• $NORMALIZE function• $NUMBER function• More information on locales in Customized National Language Translations$ISOBJECTReturns whether an expression is an object reference.$ISOBJECT(expr)ParametersexprA <strong>Caché</strong> <strong>ObjectScript</strong> expression.Description$ISOBJECT returns 1 if expr is an object reference. $ISOBJECT returns 0 if expr is notan object reference.$ISOBJECT returns –1 if expr is a reference to an invalid object. Invalid objects should notoccur in normal operations; an invalid object could be caused, for example, by recompilingthe class while instances of the class are active.To remove an object reference, set the variable to the null string (""). The obsolete %Close()method cannot be used to remove an object reference. %Close() performs no operation andalways returns successful completion. Do not use %Close() when writing new code.ParametersexprAny <strong>Caché</strong> <strong>ObjectScript</strong> expression.ExamplesThe following example shows the values returned by $ISOBJECT for an object referenceand a non-object reference (in this case, a string reference):230 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ISVALIDNUMSET a="certainly not an object"SET o=##class(%Library.ResultSet).%New()WRITE !,"nonobject: ",$ISOBJECT(a)WRITE !,"objref o: ",$ISOBJECT(o)The following example shows how to remove an object reference. The %Close() methoddoes not change the object reference. Setting an object reference to the null string deletes theobject reference:SET o=##class(%Library.ResultSet).%New()WRITE !,"objref o: ",$ISOBJECT(o)DO o.%Close() ; this is a no-opWRITE !,"objref o: ",$ISOBJECT(o)SET o=""WRITE !,"objref o: ",$ISOBJECT(o)See Also• $SYSTEM special variable$ISVALIDNUMValidates a numeric value and returns a boolean; optionally provides range checking.$ISVALIDNUM(num,scale,min,max)ParametersnumscaleminmaxThe numeric value to be validated. It can be a numeric or string value, avariable name, or any valid <strong>Caché</strong> <strong>ObjectScript</strong> expression.Optional — The number of significant decimal digits for min and max rangecomparisons.Optional — The minimum permitted numeric value.Optional — The maximum permitted numeric value.DescriptionThe $ISVALIDNUM function validates num and returns a boolean value. It optionally performsa range check using min and max values. The scale parameter is used during rangechecking to specify how many decimal digits to compare. A boolean value of 1 means thatnum is a properly-formed number and passes the range check, if one is specified.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 231


<strong>Caché</strong> <strong>ObjectScript</strong> FunctionsParametersnumThe number to be validated may be an integer, a decimal number, an exponential number(with the letter “E” or “e”). It may be a string, expression, or variable that resolves to anumber. It may be signed or unsigned, and may contain leading or trailing zeros. Validationfails ($ISVALIDNUM returns 0) if:• num contains any characters other than the digits 0–9, a leading + or – sign, a decimalpoint (.), and the letter “E” or “e” indicating an exponent.• num contains more than one + or – sign, decimal point, or letter “E” or “e”.• The optional + or – sign is not the first character of num.• The letter “E” or “e” indicating an exponent is not followed by an integer in a numericstring. With a number, “E” not followed by an integer results in a error.• num is the null string.• num is the INF or NAN value returned by $DOUBLE.The scale parameter value causes evaluation using rounded or truncated versions of the numvalue. The actual value of the num variable is not changed by $ISVALIDNUM processing.scaleThe scale parameter is used during range checking to specify how many decimal digits tocompare. Specify an integer value for scale; decimal digits in the scale value are ignored.You can specify a scale value larger than the number of decimal digits specified in the otherparameters. You can specify a scale value of –1; all other negative scale values result in a error.A non-negative scale value causes num to be rounded to that number of decimal digits beforeperforming min and max range checking. A scale value of 0 causes num to be rounded to aninteger value (3.9 = 4) before performing range checking. A scale value of –1 causes num tobe truncated to an integer value (3.9 = 3) before performing range checking. To compare allspecified digits without rounding or truncating, omit the scale parameter. A scale value whichis non-numeric or the null string is equivalent to a scale value of 0.Rounding is performed for all scale values except –1. A value of 5 or greater is always roundedup.If you omit the scale parameter, retain the comma as a place holder.232 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ISVALIDNUMmin and maxYou can specify a minimum allowed value, a maximum allowed value, neither, or both. Ifspecified, the num value (after the scale operation) must be greater than or equal to the minvalue, and less than or equal to the max value. A null string as a min or max value is equal tozero. If a value does not meet these criteria, $ISVALIDNUM returns 0.If you omit a parameter, retain the comma as a place holder. For example, when omittingscale and specifying min or max, or when omitting min and specifying max. Trailing commasare ignored.ExamplesIn the following example, each invocation of $ISVALIDNUM returns 1 (valid number):WRITE !,$ISVALIDNUM(0) ; All integers OKWRITE !,$ISVALIDNUM(4.567) ; Decimal numbers OKWRITE !,$ISVALIDNUM("4.567") ; Numeric strings OKWRITE !,$ISVALIDNUM(-.0) ; Signed numbers OKWRITE !,$ISVALIDNUM(+004.500) ; Leading/trailing zeroes OKWRITE !,$ISVALIDNUM(4E2) ; Exponents OKIn the following example, each invocation of $ISVALIDNUM returns 0 (invalid number):WRITE !,$ISVALIDNUM("") ; Null string is invalidWRITE !,$ISVALIDNUM("4,567") ; Commas are not permittedWRITE !,$ISVALIDNUM("4A") ; Invalid characterThe following example shows the use of the min and max parameters. All of the followingreturn 1 (number is valid and also passes the range check):WRITE !,$ISVALIDNUM(4,,3,5) ; scale can be omittedWRITE !,$ISVALIDNUM(4,2,3,5) ; scale can be larger than; number of decimal digitsWRITE !,$ISVALIDNUM(4,0,,5) ; min or max can be omittedWRITE !,$ISVALIDNUM(4,0,4,4) ; min and max are inclusiveWRITE !,$ISVALIDNUM(-4,0,-5,5) ; negative numbersWRITE !,$ISVALIDNUM(4.00,2,04,05) ; leading/trailing zerosWRITE !,$ISVALIDNUM(.4E3,0,3E2,400) ; exponents expandedThe following example shows the use of the scale parameter with min and max. All of thefollowing return 1 (number is valid and also passes the range check):<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 233


<strong>Caché</strong> <strong>ObjectScript</strong> FunctionsWRITE !,$ISVALIDNUM(4.55,,4.54,4.551); When scale is omitted, all digits of num are checked.WRITE !,$ISVALIDNUM(4.1,0,4,4.01); When scale=0, num is rounded to an integer value; (0 decimal digits) before min & max check.WRITE !,$ISVALIDNUM(3.85,1,3.9,5); num is rounded to 1 decimal digit,; (with values of 5 or greater rounded up); before min check.WRITE !,$ISVALIDNUM(4.01,17,3,5); scale can be larger than number of decimal digits.WRITE !,$ISVALIDNUM(3.9,-1,2,3); When scale=-1, num is truncated to an integer valueNotes$ISVALIDNUM, $NORMALIZE, and $NUMBER ComparedThe $ISVALIDNUM, $NORMALIZE, and $NUMBER functions all validate numbers.$ISVALIDNUM returns a boolean value (0 or 1). $NORMALIZE and $NUMBER returna validated version of the specified number.These three functions offer different validation criteria. Select the one that best meets yourneeds.• All three functions parse signed and unsigned integers (including –0), exponential numbers(with “E” or “e”), and decimal numbers. However, $NUMBER can be set (using the “I”format) to reject decimal numbers (including negative exponents that result in decimalnumbers). All three functions parse both numbers (123.45) and numeric strings (“123.45”).• Leading and trailing zeroes are stripped out by all three functions. The decimal characteris stripped out unless followed by a non-zero value.• Numeric strings containing a NumericGroupSeparator: $NUMBER parses Numeric-GroupSeparator characters (American format: comma (,); European format: period (.) orapostrophe (')) and the decimal character (American format: period (.) or European format:comma (,)) based on its format parameter (or the default for the current locale). It acceptsand strips out any number of NumericGroupSeparator characters. For example, inAmerican format it validate “123,,4,56.99” as the number 123456.99. $NORMALIZEdoes not recognize NumericGroupSeparator characters. It validates character-by-characteruntil it encounters a non-numeric character; for example, it validates “123,456.99” as thenumber 123. $ISVALIDNUM rejects the string “123,456” as an invalid number.• Multiple leading signs (+ and –) are interpreted by all three functions for numbers.However, only $NORMALIZE accepts multiple leading signs in a quoted numeric string.• Trailing + and – signs: All of the three functions reject trailing signs in numbers. However,in a quoted numeric string $NUMBER parses one (and only one) trailing sign,234 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$NORMALIZE parses multiple trailing signs, and $ISVALIDNUM rejects any stringcontaining a trailing sign as an invalid number.• Parentheses: $NUMBER parses parentheses surrounding an unsigned number in a quotedstring as indicating a negative number. $NORMALIZE and $ISVALIDNUM rejectparentheses.• Numeric strings containing multiple decimal characters: $NORMALIZE validatescharacter-by-character until it encounters the second decimal character. For example, inAmerican format it validates “123.4.56” as the number 123.4. $NUMBER and$ISVALIDNUM reject any string containing more than one decimal character as aninvalid number.Numeric strings containing other non-numeric characters: $NORMALIZE validatescharacter-by-character until it encounters an alphabetic character. It validates “123A456”as the number 123. $NUMBER and $ISVALIDNUM validate the entire string, theyreject “123A456” as an invalid number.• The null string: $NORMALIZE parses the null string as zero (0). $NUMBER and$ISVALIDNUM reject the null string.The $ISVALIDNUM and $NUMBER functions provide optional min/max range checking.$ISVALIDNUM, $NORMALIZE, and $NUMBER all provide rounding of decimal numbersto a specified number of decimal digits. $ISVALIDNUM and $NORMALIZE can rounddecimal digits, and round or truncate a decimal number to return an integer. For example,$NORMALIZE can round 488.65 to 488.7 or 489, or truncate it to 488. $NUMBER canround decimal numbers or integers. For example, $NUMBER can round 488.65 to 488.7,489, 490 or 500.See Also• $FNUMBER function• $INUMBER function• $NORMALIZE function• $NUMBER function• More information on locales in Customized National Language Translations$ISVALIDNUM<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 235


<strong>Caché</strong> <strong>ObjectScript</strong> Functions$JUSTIFYReturns the value of an expression right-aligned within the specified width.$JUSTIFY(expression,width,decimal)$J(expression,width,decimal)ParametersexpressionwidthdecimalThe value that is to be right-aligned. It can be a numeric value, astring literal, the name of a variable, or any valid <strong>Caché</strong> <strong>ObjectScript</strong>expression.The number of characters within which expression is to beright-aligned. It can be a positive integer value, the name of aninteger variable, or any valid <strong>Caché</strong> <strong>ObjectScript</strong> expression thatevaluates to a positive integer.Optional — The position at which to place the decimal point withinthe width. It can be a positive integer value, the name of an integervariable, or any valid <strong>Caché</strong> <strong>ObjectScript</strong> expression that evaluatesto a positive integer.Description$JUSTIFY returns the value specified by expression right-aligned within the specified width.You can include the decimal parameter to decimal-align numbers within width. If you omitthe decimal option, $JUSTIFY truncates all trailing zeroes for decimal numbers.$JUSTIFY is especially useful for outputting formatted values with the WRITE command.ParameterswidthIf the value of width is greater than the number of characters inexpression (the usual case),$JUSTIFY right aligns the value of expression by inserting the necessary number of spacecharacters to its left. If the width is equal to or less than the number of characters in the valueof expression, $JUSTIFY returns the full value of the expression with no truncation.decimalThe decimal point position is calculated as the number of digits from the end of width.$JUSTIFY zero fills any positions remaining between the end of the expression value and236 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


the end of width. If the expression value itself is less than 1, $JUSTIFY inserts a leadingzero before the decimal point. Note that decimal also causes $JUSTIFY to round theexpression value to fit the number of decimal positions.The decimal parameter is meaningful only if the expression evaluates to a number. Ifexpression evaluates to a string, $JUSTIFY replaces it with a string of zeroes starting at thedecimal position up to the end of width. Unlike string values, the $DOUBLE values INF, -INF, and NAN are returned unchanged by $JUSTIFY, regardless of the decimal value.ExamplesAssume the following variables var1=250.50 and var2=875.00. These commands:SET var1=250.50,var2= 875.00WRITE !,$JUSTIFY(var1,20,2),!,$JUSTIFY(var2,20,2)WRITE !,$JUSTIFY("_________",20)WRITE !,$JUSTIFY("TOTAL",9),$JUSTIFY(var1+var2,11,2)return the following lines:250.50875.00_______TOTAL 1125.50The starting position for width is determined by the current $X value.If this code had omitted the decimal option for the output numbers, the lines would appearas follows:250.5875_______TOTAL 1125.50See Also• $FNUMBER function• $X special variable$JUSTIFY<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 237


<strong>Caché</strong> <strong>ObjectScript</strong> Functions$LENGTHReturns the number of characters or delimited substrings in a string.$LENGTH(expression,delimiter)$L(expression,delimiter)ParametersexpressiondelimiterThe target string. It can be a numeric value, a string literal, the nameof any variable, or any valid expression.Optional — A string that demarcates separate substrings in the targetstring. It must be a string literal, but can be of any length. Theenclosing quotation marks are required.Description$LENGTH returns the number of characters in a specified string or the number of delimitedsubstrings in a specified string, depending on the parameters used. Note that length countsthe number of characters; an 8-bit character and a 16-bit wide character are both counted asone character.• $LENGTH(expression) returns the number of characters in the string. If the expressionis a null string, $LENGTH returns a 0. If expression is a numeric expression, it is convertedto canonical form before determining its length. If expression is a string numericexpression, no conversion is performed. If expression is the $DOUBLE values INF, -INF, or NAN, the lengths returned are 3, 4, and 3, respectively.• $LENGTH(expression,delimiter) returns the number of substrings within the string.$LENGTH returns the number of substrings separated from one another by the indicateddelimiter. This number is always equal to the number of delimiters in the string, plus one.If the delimiter is the null string, $LENGTH returns a 0. If the delimiter is any othervalid string literal and the string is a null string, $LENGTH returns a 1.ExamplesIn the following example, both $LENGTH functions return 4, the number of characters inthe string.SET roman="test"WRITE !,$LENGTH(roman)," characters in: ",romanSET greek=$CHAR(964,949,963,964)WRITE !,$LENGTH(greek)," characters in: ",greek238 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


In the following example, the first $LENGTH returns 5. This is the length of 74000, thecanonical version of the specified number. The second $LENGTH returns 8, the length ofthe string “+007.4e4”.WRITE !,$LENGTH(+007.4e4)WRITE !,$LENGTH("+007.4e4")In the following example, the first WRITE returns 11 the number of characters in var1(including, of course, the space character). The second WRITE returns 2, the number ofsubstrings in var1 using the space character as the substring delimiter.SET var1="HELLO WORLD"WRITE !,$LENGTH(var1)WRITE !,$LENGTH(var1," ")The following example returns 3, the number of substrings within the string, as delimited bythe dollar sign ($) character.SET STR="ABC$DEF$EFG",DELIM="$"WRITE $LENGTH(STR,DELIM)If the specified delimiter is not found in the string $LENGTH returns 1, because the onlysubstring is the string itself.The following example returns a 0 because the string tested is the null string.SET Nstring = ""WRITE $LENGTH(Nstring)The following example shows the values returned when a delimiter or its string is the nullstring.SET String = "ABC"SET Nstring = ""SET Delim = "$"SET Ndelim = ""WRITE !,$LENGTH(String,Delim) ; returns 1WRITE !,$LENGTH(Nstring,Delim) ; returns 1WRITE !,$LENGTH(String,Ndelim) ; returns 0WRITE !,$LENGTH(Nstring,Ndelim) ; returns 0Notes$LENGTH, $PIECE, and $LIST$LENGTH• $LENGTH with one argument returns the number of characters in a string. This functioncan be used with the $EXTRACT function, which locates a substring by position andreturns the substring value.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 239


<strong>Caché</strong> <strong>ObjectScript</strong> Functions• $LENGTH with two arguments returns the number of substrings in a string, based on adelimiter. This function can be used with the $PIECE function, which locates a substringby a delimiter and returns the substring value.• $LENGTH should not be used on encoded lists created using $LISTBUILD or $LIST.Use $LISTLENGTH to determine the number of substrings (list elements) in an encodedlist string.The $LENGTH, $FIND, $EXTRACT, and $PIECE functions operate on standard characterstrings. The various $LIST functions operate on encoded character strings, which areincompatible with standard character strings. The sole exception is the one-argument andtwo-argument forms of $LIST, which take an encoded character string as input, but outputsa single element value as a standard character string.See Also• $EXTRACT function• $PIECE function$LISTReturns elements in a list.$LIST(list,position,end)$LI(list,position,end)ParameterslistpositionendAn expression that evaluates to a valid list. Because lists containencoding, list must be created using $LISTBUILD or$LISTFROMSTRING, or extracted from another list using $LIST.Optional — The starting position in the specified list. An expressionthat evaluates to an integer.Optional — The ending position in the specified list. An expression thatevaluates to an integer.Description$LIST returns elements from a list. The elements returned depend on the parameters used.240 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$LIST• $LIST(list) returns the first element string in the list.• $LIST(list,position) returns the element indicated by the specified position. The positionparameter must evaluate to an integer.• $LIST(list,position,end) returns a “sublist” (an encoded list string) containing the elementsof the list from the specified start position through the specified end position.You can also use $LISTNEXT to sequentially return elements from a list.ParameterslistAn encoded list string containing one or more elements. Lists can be created using$LISTBUILD or $LISTFROMSTRING, or extracted from another list by using the $LISTfunction. The following are valid list arguments:SET myList = $LISTBUILD("Red", "Blue", "Green", "Yellow")WRITE !,$LIST(myList,2) ; prints BlueSET subList = $LIST(myList,2,4)WRITE !,$LIST(subList,2) ; prints GreenIn the following example, subList is not a valid list argument, because it is a single elementreturned as an ordinary string, not an encoded list string:SET myList = $LISTBUILD("Red", "Blue", "Green", "Yellow")SET subList = $LIST(myList,2)WRITE $LIST(subList,1)positionThe position of a list element to return. List elements are counted from 1. If position isomitted, the first element is returned. If the value of position is 0 or greater than the numberof elements in the list, <strong>Caché</strong> issues a error. If the value of position isnegative one (–1), $LIST returns the final element in the list.If the end parameter is specified, position specifies the first element in a range of elements.Even when only one element is returned (when position and end are the same number) thisvalue is returned as an encoded list string. Thus, $LIST(x,2) is not identical to $LIST(x,2,2).endThe position of the last element in a range of elements. You must specify position to specifyend. When end is specified, the value returned is an encoded list string. Because of thisencoding, such strings should only be processed by other $LIST functions.If the value of end is:<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 241


<strong>Caché</strong> <strong>ObjectScript</strong> Functions• greater than position, an encoded string containing a list of elements is returned.• equal to position, an encoded string containing the one element is returned.• less than position, the null string ("") is returned.• greater than the number of elements in list, it is equivalent to specifying the final elementin the list.• negative one (–1), it is equivalent to specifying the final element in the list.When specifying end, you can specify a position value of zero (0). In this case, 0 is equivalentto 1.ExamplesThe following two WRITE statements both return “RED”, the first element in the list. Thefirst writes the first element by default, the second writes the first element because the positionparameter is set to 1:WRITE !,$LIST($LISTBUILD("RED","BLUE","GREEN"))WRITE !,$LIST($LISTBUILD("RED","BLUE","GREEN"),1)The following example returns “Blue”, the second element in the list:SET X=$LISTBUILD("Red","Blue","Green")WRITE $LIST(X,2)The following example returns “Red Blue”, a two-element list string beginning with the firstelement and ending with the second element in the list. ZZDUMP is used rather than WRITE,because a list string contains special (non-printing) encoding characters:SET X=$LISTBUILD("Red ","Blue ","Green ")ZZDUMP $LIST(X,1,2)The following example returns “Brown Black”, a two-element list string that begins with thethird element and ends with the last element in the list:SET X=$LISTBUILD("Green ","White ","Brown ","Black ")SET LIST2=$LIST(X,3,-1)ZZDUMP LIST2NotesInvalid Parameter ValuesIf the expression in the list parameter does not evaluate to a valid list, a error occurs.SET x=$CHAR(0,0,0,1,16,27,134,240)SET a=$LIST(x,2) // generates a error242 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


If the value of the position parameter or the end parameter is less than -1, invoking the $LISTfunction generates a error.If the value of the position parameter refers to a nonexistent list member and no end parameteris used, invoking the $LIST function generates a error.SET LIST2=$LISTBUILD("Brown","Black")ZZDUMP $LIST(LIST2,3) ; generates a NULL VALUE errorSET x=$LIST(LIST2,0) ; generates a NULL VALUE errorIf the value of the position parameter identifies an element with an undefined value, invokingthe $LIST function also generates a error.ZZDUMP $LIST("") ; generates a NULL VALUE errorSET X=$LISTBUILD("A",,"C")ZZDUMP $LIST(X,2) ; generates a NULL VALUE errorTwo-Parameter and Three-Parameter $LIST$LIST(list,1) is not equivalent to $LIST(list,1,1) because the former returns a string, whilethe latter returns a single-element list string. Furthermore, the first can receive a error, whereas the second cannot; if there are no elements to return, it returns anull string.UnicodeIf one Unicode character appears in a list element, that entire list element is represented asUnicode (wide) characters. Other elements in the list are not affected.The following example shows two lists. The y list consists of two elements which containonly ASCII characters. The z list consists of two elements: the first element contains a Unicodecharacter ($CHAR(960) = the pi symbol); the second element contains only ASCII characters.SET y=$LISTBUILD("ABC"_$CHAR(68),"XYZ")SET z=$LISTBUILD("ABC"_$CHAR(960),"XYZ")WRITE !,"The ASCII list y elements: "ZZDUMP $LIST(y,1)ZZDUMP $LIST(y,2)WRITE !,"The Unicode list z elements: "ZZDUMP $LIST(z,1)ZZDUMP $LIST(z,2)Note that <strong>Caché</strong> encodes the first element of z entirely in wide Unicode characters. The secondelement of z contains no Unicode characters, and thus <strong>Caché</strong> encodes it using narrow ASCIIcharacters.See Also• $LISTBUILD function$LIST<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 243


<strong>Caché</strong> <strong>ObjectScript</strong> Functions• $LISTDATA function• $LISTFIND function• $LISTFROMSTRING function• $LISTGET function• $LISTLENGTH function• $LISTNEXT• $LISTSAME function• $LISTTOSTRING$LISTBUILDBuilds a list of elements from the specified expressions.$LISTBUILD(element,...)$LB(element,...)ParameterelementAny expression, or comma-separated list of expressions. To include acomma within an element, make the element a quoted string.Description$LISTBUILD takes one or more expressions and returns a list with one element for eachexpression.The following functions can be used to create a list:• $LISTBUILD, which creates a list from multiple strings, one string per element.• $LISTFROMSTRING, which creates a list from a single string containing multipledelimited elements.• $LIST, which extracts a sublist from an existing list.$LISTBUILD is used with the other $LIST functions: $LISTDATA, $LISTFIND,$LISTGET, $LISTNEXT, $LISTLENGTH, $LISTSAME, and $LISTTOSTRING. The244 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$LISTBUILDresults of $LISTBUILD are often best displayed using the ZZDUMP command. SeeZZDUMP for examples of $LISTBUILD involving non-printing and Unicode characters.Note:$LISTBUILD and the other $LIST functions use an optimized binary representationto store data elements. For this reason, equivalency tests may not work as expectedwith some $LIST data. Data that might, in other contexts, be considered equivalent,may have a different internal representation. For example, $LISTBUILD(1) is notequal to $LISTBUILD(“1”).For the same reason, a list string value returned by $LISTBUILD should not beused in character search and parse functions that use a delimiter character, such as$PIECE and the two-argument form of $LENGTH. Elements in a list created by$LISTBUILD are not marked by a character delimiter, and thus can contain anycharacter.ExamplesThe following example produces the three-element list "Red,Blue,Green":SET X=$LISTBUILD("Red","Blue","Green")WRITE !,$LIST(X,1,3)NotesOmitting ParametersOmitting an element expression yields an element whose value is undefined. For example,the following $LISTBUILD statement produces a three-element list whose second elementhas an undefined value; referencing the second element with the $LIST function will producea error.WRITE $LIST($LISTBUILD("Red",,"Green"),2)However, the following produces a three-element list whose second element is a null string.No error condition exists.WRITE $LIST($LISTBUILD("Red","","Green"),2)Additionally, if a $LISTBUILD expression is undefined, the corresponding list element hasan undefined value. The following two expressions both produce the same two-element listwhose first element is "Red" and whose second element has an undefined value:WRITE !,$LISTBUILD("Red",)KILL ZWRITE !,$LISTBUILD("Red",Z)<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 245


<strong>Caché</strong> <strong>ObjectScript</strong> FunctionsProviding No ParametersInvoking the $LISTBUILD function with no parameters returns a list with one element whosedata value is undefined. This is not the same as a null string:SET x=$LISTBUILD()SET y=$LISTBUILD("")ZZDUMP x,yreturns:0000: 01 .0000: 02 01 ..Nesting ListsAn element of a list may itself be a list. For example, the following statement produces athree-element list whose third element is the two-element list, "Walnut,Pecan":SET X=$LISTBUILD("Apple","Pear",$LISTBUILD("Walnut","Pecan"))WRITE $LIST(X,3)Concatenating ListsThe result of concatenating two lists with the Binary Concatenate operator is another list. Forexample, the following two WRITE statements produce the same list, "A,B,C":WRITE !,$LIST($LISTBUILD("A","B")_$LISTBUILD("C"),0,-1)WRITE !,$LIST($LISTBUILD("A","B","C"),0,-1)For further details, see Operators in Using <strong>Caché</strong> <strong>ObjectScript</strong>.A null string ("") is an empty list. For example, the following two expressions each producethe same two-element list:WRITE !,$LISTBUILD("A","B")_""WRITE !,$LISTBUILD("A","B")However, the following two expressions each produce a three-element list:WRITE !,$LISTBUILD("A","B")_$LISTBUILD("")WRITE !,$LISTBUILD("A","B")_$LISTBUILD()UnicodeIf one or more characters in a list element is a wide (Unicode) character, all characters in thatelement are represented as wide characters. To insure compatibility across systems,$LISTBUILD always stores these bytes in little-endian order, regardless of the hardwareplatform. Wide characters are represented as byte strings. Therefore, when displayed usingZZDUMP, the ZZDUMP length reflects the number of bytes, not the number of Unicodecharacters.246 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


In the following example, ZZDUMP shows the first element as having a length of ten (0A):four characters, each two bytes long, plus the ZZDUMP's length and datatype bytes. Thedatatype byte is 02 (Unicode string). Each character is represented by two bytes in littleendianorder. The second element has a length of five (05): three characters, plus the lengthand datatype bytes. The datatype byte is 01 (Binary string).SET z=$LISTBUILD($CHAR(987)_"ABC","ABC")ZZDUMP z0000: 0A 02 DB 03 41 00 42 00 43 00 05 01 41 42 43 ..Û.A.B.C...ABCSee Also• ZZDUMP command• $LIST function• $LISTDATA function• $LISTFIND function• $LISTFROMSTRING function• $LISTGET function• $LISTLENGTH function• $LISTNEXT• $LISTSAME function• $LISTTOSTRING$LISTDATA$LISTDATAIndicates whether the specified element exists and has a data value.$LISTDATA(list,position)$LD(list,position)ParameterslistpositionAn expression that evaluates to a valid list.Optional — An expression interpreted as a position in the specified list.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 247


<strong>Caché</strong> <strong>ObjectScript</strong> FunctionsDescription$LISTDATA checks for data in the requested element in a list and returns a boolean value.$LISTDATA returns a value of 1 if the element indicated by the position parameter is in thelist and has a data value. $LISTDATA returns a value of a 0 if the element is not in the listor does not have a data value.ParameterslistA list is an encoded string containing multiple elements. A list must have been created using$LISTBUILD or $LISTFROMSTRING, or extracted from another list using $LIST.positionIf you omit the position parameter, $LISTDATA evaluates the first element. If the value ofthe position parameter is -1, it is equivalent to specifying the final element of the list. If thevalue of the position parameter refers to a nonexistent list member, then invoking the$LISTDATA function returns a 0.ExamplesThe following examples show the results of the various values of the position parameter.All of the following $LISTDATA statements return a value of 0:KILL YSET X=$LISTBUILD("Red",,Y,"","Green")WRITE !,$LISTDATA(X,2) ; second element is undefinedWRITE !,$LISTDATA(X,3) ; third element is killed variableWRITE !,$LISTDATA("") ; null stringWRITE !,$LISTDATA(X,0) ; the 0th positionWRITE !,$LISTDATA(X,6) ; 6th position in 5-element listThe following $LISTDATA statements return a value of 1 for the same five-element list:SET X=$LISTBUILD("Red",,Y,"","Green")WRITE !,$LISTDATA(X) ; first position (by default)WRITE !,$LISTDATA(X,1) ; first position specifiedWRITE !,$LISTDATA(X,4) ; fourth position value=null stringWRITE !,$LISTDATA(X,5) ; fifth positionWRITE !,$LISTDATA(X,-1) ; last (5th) positionNotesInvalid Parameter ValuesIf the expression in the list parameter does not evaluate to a valid list, a error occurs.248 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$LISTFINDSET x=$CHAR(0,0,0,1,16,27,134,240)SET a=$LISTDATA(x,1) // generates a errorIf the value of the position parameter is less than -1, invoking the $LISTDATA functiongenerates a error.See Also• $LIST function• $LISTBUILD function• $LISTFIND function• $LISTFROMSTRING function• $LISTGET function• $LISTLENGTH function• $LISTNEXT• $LISTSAME function• $LISTTOSTRING$LISTFINDSearches a specified list for the requested value.$LISTFIND(list,value,startafter)$LF(list,value,startafter)ParameterslistvaluestartafterAn expression that evaluates to a valid list. A list is an encodedstring containing one or more elements. A list must be created using$LISTBUILD or $LISTFROMSTRING, or extracted from another listusing $LIST.An expression containing the desired element value.Optional — An expression interpreted as a list position. The searchstarts with the element after this position.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 249


<strong>Caché</strong> <strong>ObjectScript</strong> FunctionsDescription$LISTFIND searches the specified list for the first instance of the requested value. The searchbegins with the element after the position indicated by the startafter parameter. If you omitthe startafter parameter, $LISTFIND assumes a startafter value of 0 and starts the searchwith the first element (element 1). If the value is found, $LISTFIND returns the position ofthe matching element. If the value is not found, $LISTFIND returns a 0. The $LISTFINDfunction will also return a 0 if the value of the startafter parameter refers to a nonexistent listmember.ExamplesThe following example returns 2, the position of the first occurrence of the requested string:SET X=$LISTBUILD("A","B","C","D")WRITE $LISTFIND(X,"B")The following example returns 0, indicating the requested string was not found:SET X=$LISTBUILD("A","B","C","D")WRITE $LISTFIND(X,"E")The following examples show the effect of using the startafter parameter. The first exampledoes not find the requested string and returns 0 because it occurs at the startafter position:SET X=$LISTBUILD("A","B","C","D")WRITE $LISTFIND(X,"B",2)The second example finds the second occurrence of the requested string and returns 4, becausethe first occurs before the startafter position:SET Y=$LISTBUILD("A","B","C","A")WRITE $LISTFIND(Y,"A",2)The $LISTFIND function only matches complete elements. Thus, the following examplereturns 0 because no element of the list is equal to the string “B”, though all of the elementscontain “B”:SET mylist = $LISTBUILD("ABC","BCD","BBB")WRITE $LISTFIND(mylist,"B")NotesInvalid Parameter ValuesIf the expression in the list parameter does not evaluate to a valid list, a error occurs.SET x=$CHAR(0,0,0,1,16,27,134,240)SET a=$LISTFIND(x,1) // generates a error250 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


If the value of the startafter parameter is less than -1, invoking the $LISTFIND functiongenerates a error.See Also• $LIST function• $LISTBUILD function• $LISTDATA function• $LISTFROMSTRING function• $LISTGET function• $LISTLENGTH function• $LISTNEXT• $LISTSAME function• $LISTTOSTRING$LISTFROMSTRING$LISTFROMSTRINGCreates a list from a string.$LISTFROMSTRING(string,delimiter)$LFS(string,delimiter)ParametersstringdelimiterA string to be converted into a <strong>Caché</strong> list. This string contains one or moreelements, separated by a delimiter. The delimiter does not become part ofthe resulting <strong>Caché</strong> list.Optional — The delimiter used to separate substrings (elements) in string.Specify delimiter as a quoted string. If no delimiter is specified, the defaultis the comma (,) character.Description$LISTFROMSTRING takes a quoted string containing delimited elements and returns alist. A list represents data in an encoded format which does not use delimiter characters. Thus<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 251


<strong>Caché</strong> <strong>ObjectScript</strong> Functionsa list can contain all possible characters, and is ideally suited for bit-string data. Lists arehandled using the <strong>Caché</strong> <strong>ObjectScript</strong> $LIST functions.ParametersstringA string literal (enclosed in quotation marks), a numeric, or a variable or expression thatevaluates to a string. This string can contain one or more substrings (elements), separated bya delimiter. The string data elements must not contain the delimiter character (or string),because the delimiter character is not included in the output list.delimiterA character (or string of characters) used to delimit substrings within the input string. It canbe a numeric or string literal (enclosed in quotation marks), the name of a variable, or anexpression that evaluates to a string.Commonly, a delimiter is a designated character which is never used within string data, butis set aside solely for use as a delimiter separating substrings. A delimiter can also be a multicharacterstring, the individual characters of which can be used within string data.If you specify no delimiter, the default delimiter is the comma (,) character. You cannotspecify a null string ("") as a delimiter; attempting to do so results in a error.ExampleThe following example takes a string of names which are separated by a blank space, andcreates a list:SET namestring="Deborah Noah Martha Bowie"SET namelist=$LISTFROMSTRING(namestring," ")WRITE !,"1st element: ",$LIST(namelist,1)WRITE !,"2nd element: ",$LIST(namelist,2)WRITE !,"3rd element: ",$LIST(namelist,3)See Also• $LISTTOSTRING function• $LISTBUILD function• $LIST function• $PIECE function• $LISTDATA function252 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$LISTGET• $LISTFIND function• $LISTGET function• $LISTLENGTH function• $LISTNEXT• $LISTSAME function$LISTGETReturns an element in a list, or a specified default value if the requested element is undefined.$LISTGET(list,position,default)$LG(list,position,default)ParameterslistpositiondefaultAn expression that evaluates to a valid list.Optional — An expression interpreted as a position in the specified list.Optional — An expression that provides the value to return if the listelement has an undefined value.Description$LISTGET returns the requested element in the specified list. If the value of the positionparameter refers to a nonexistent member or identifies an element with an undefined value,the specified default value is returned.The $LISTGET function is identical to the one- and two-argument forms of the $LISTfunction except that, under conditions that would cause $LIST to produce a error, $LISTGET returns a default value. See the description of the $LIST function for moreinformation on conditions that generate errors.ParameterspositionThe position parameter must evaluate to an integer. If it is omitted, by default, the functionexamines the first element of the list. If the value of the position parameter is -1, it is equivalentto specifying the last element of the list.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 253


<strong>Caché</strong> <strong>ObjectScript</strong> FunctionsdefaultIf you omit the default parameter, the null string ("") is assumed for the default value.ExamplesThe $LISTGET functions in the following example both return “A”, the first element in thelist:SET LIST=$LISTBUILD("A","B","C")WRITE !,$LISTGET(LIST)WRITE !,$LISTGET(LIST,1)The $LISTGET functions in the following example both return “C”, the third and last elementin the list:SET LIST=$LISTBUILD("A","B","C")WRITE !,$LISTGET(LIST,3)WRITE !,$LISTGET(LIST,-1)The $LISTGET functions in the following example both return a value upon encounteringthe undefined 2nd element in the list. The first returns a question mark (?), which the userdefined as the default value. The second returns a null string because a default value is notspecified:WRITE !,$LISTGET($LISTBUILD("A",,"C"),2,"?")WRITE !,$LISTGET($LISTBUILD("A",,"C"),2)The $LISTGET functions in the following example both specify a position greater than thelast element in the three-element list. The first returns a null string because the default valueis not specified. The second returns the user-specified default value, “ERR”:SET LIST=$LISTBUILD("A","B","C")WRITE !,$LISTGET(LIST,4)WRITE !,$LISTGET(LIST,4,"ERR")The $LISTGET functions in the following example both return a null string:SET LIST=$LISTBUILD("A","B","C")WRITE !,$LISTGET(LIST,0)WRITE !,$LISTGET("")NotesInvalid Parameter ValuesIf the expression in the list parameter does not evaluate to a valid list, a error canoccur.254 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


If the value of the position parameter is less than -1, invoking the $LISTGET function generatesa error.See Also• $LIST function• $LISTBUILD function• $LISTDATA function• $LISTFIND function• $LISTFROMSTRING function• $LISTLENGTH function• $LISTNEXT• $LISTSAME function• $LISTTOSTRING$LISTLENGTH$LISTLENGTHReturns the number of elements in a specified list.$LISTLENGTH(list)$LL(list)ParameterlistAny expression that evaluates to a list.Description$LISTLENGTH returns the number of elements in list.ExamplesThe following example returns 3, because there are 3 elements in the list:WRITE $LISTLENGTH($LISTBUILD("Red","Blue","Green"))The following example returns a 0, because a null string is a valid (zero-element) list.WRITE $LISTLENGTH("")<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 255


<strong>Caché</strong> <strong>ObjectScript</strong> FunctionsNotesError for Invalid ListsIf list is not a valid list, <strong>Caché</strong> generates a error.SET x=$CHAR(0,0,0,1,16,27,134,240)SET a=$LISTLENGTH(x) // generates a error$LISTLENGTH and Nested ListsThe following example returns 3, because $LISTLENGTH does not recognize the individualelements in nested lists:SET X=$LISTBUILD("Apple","Pear",$LISTBUILD("Walnut","Pecan"))WRITE $LISTLENGTH(X)See Also• $LIST function• $LISTBUILD function• $LISTDATA function• $LISTFIND function• $LISTFROMSTRING function• $LISTGET function• $LISTNEXT• $LISTSAME function• $LISTTOSTRING256 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$LISTNEXT$LISTNEXTRetrieves elements sequentially from a list.$LISTNEXT(list,ptr,value)ParameterslistptrvalueAny expression that evaluates to a list.A pointer to the next element in the list. Initialized to 0 to point to the beginningof a list.The data value of the element, returned as a string.Description$LISTNEXT sequentially returns elements in a list. You initialize ptr to 0 prior to the firstinvocation of $LISTNEXT. Each invocation of $LISTNEXT increments ptr and returns thelist element value to value. $LISTNEXT returns 1, indicating that a list element has beensuccessfully retrieved.When $LISTNEXT reaches the end of the list, it returns 0, resets ptr to 0, and leaves valueunchanged from the previous invocation. Because ptr has been reset to 0, the next invocationof $LISTNEXT would start at the beginning of the list.ExamplesThe following example sequentially returns all of the elements in the list:SET list=$LISTBUILD("Red","Blue","Green")SET ptr=0,count=0WHILE $LISTNEXT(list,ptr,value) {SET count=count+1WRITE !,value }WRITE !,"End of list: ",count," elements found"QUITNotesError for Invalid ListsIf list is not a valid list, you may receive a error.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 257


<strong>Caché</strong> <strong>ObjectScript</strong> Functions$LISTNEXT and Nested ListsThe following example returns three elements, because $LISTNEXT does not recognize theindividual elements in nested lists:SET list=$LISTBUILD("Apple","Pear",$LISTBUILD("Walnut","Pecan"))SET ptr=0,count=0WHILE $LISTNEXT(list,ptr,value) {SET count=count+1WRITE !,value }WRITE !,"End of list: ",count," elements found"QUITSee Also• $LIST function• $LISTBUILD function• $LISTDATA function• $LISTFIND function• $LISTFROMSTRING function• $LISTGET function• $LISTLENGTH function• $LISTSAME function• $LISTTOSTRING$LISTSAMECompares two lists and returns a boolean value.$LISTSAME(list1,list2)$LS(list1,list2)Parameterslist1list2Any expression that evaluates to a list.258 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


Description$LISTSAME compares the contents of two lists and returns 1 if the lists are identical. If thelists are not identical, $LISTSAME returns 0.A valid list can either be a list created using $LISTBUILD, or a null string (""). If list is nota valid list, you receive a error.ExamplesThe following example returns 1, because the two lists are identical:SET x = $LISTBUILD("Red","Blue","Green")SET y = $LISTBUILD("Red","Blue","Green")WRITE $LISTSAME(x,y)The following example returns 0, because the two lists are not identical:SET x = $LISTBUILD("Red","Blue","Yellow")SET y = $LISTBUILD("Red","Blue","Green")WRITE $LISTSAME(x,y)NotesIdentical Lists$LISTSAME considers two lists to be identical if the string representations of the two listsare identical. This is not the same equivalence test as the one used by other list operations,which test using the internal representation of a list. This distinction is easily seen whencomparing a number and a numeric string, as in the following example:SET x = $LISTBUILD("365")SET y = $LISTBUILD(365)IF x'=y { WRITE !,"number and numeric string lists differ" }WRITE !,$LISTSAME(x,y)," number and numeric string lists identical"The IF comparison tests the internal representations of these lists (which are not identical).$LISTSAME performs a string conversion on both lists, compares them, and finds themidentical.The following example shows two lists with various representations of numeric elements.$LISTSAME considers these two lists to be identical:SET x = $LISTBUILD("360","361","362","363","364","365","366")SET y = $LISTBUILD(00360.000,(19*19),+"362",363,364.0,+365,"3"_"66")WRITE !,$LISTSAME(x,y)," lists are identical"$LISTSAMEIn the following example, both $LISTSAME comparisons returns 0, because these lists arenot considered identical:<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 259


<strong>Caché</strong> <strong>ObjectScript</strong> FunctionsSET x=$LISTBUILD("Apple","Pear","Walnut","Pecan")SET y=$LISTBUILD("Apple","Pear",$LISTBUILD("Walnut","Pecan"))SET z=$LISTBUILD("Apple","Pear","Walnut","Pecan","")WRITE !,$LISTSAME(x,y)," nested list"WRITE !,$LISTSAME(x,z)," null string is list item"The following example returns 1, because the lists are considered identical:SET x=$LISTBUILD("Apple","Pear","Walnut","Pecan")SET y=$LISTBUILD("Apple","Pear")_$LISTBUILD("Walnut","Pecan")WRITE !,$LISTSAME(x,y)," concatenate lists"Null String and Null ListA list containing the null string (an empty string) as its sole element is a valid list. The nullstring by itself is also considered a valid list. However these two (a null string and a null list)are not considered identical, as shown in the following example:WRITE !,$LISTSAME($LISTBUILD(""),$LISTBUILD(""))," null lists"WRITE !,$LISTSAME("","")," null strings"WRITE !,$LISTSAME($LISTBUILD(""),"")," null list and null string"Normally, a string is not a valid $LISTSAME argument, and $LISTSAME issues a error. However, the following $LISTSAME comparisons complete successfully and return0. The null string and the string “abc” are compared and found not to be identical. These nullstring comparisons do not issue a error:WRITE !,$LISTSAME("","abc")WRITE !,$LISTSAME("abc","")The following $LISTSAME comparisons do issue a error, because a list (even anull list) cannot be compared with a string:SET x = $LISTBUILD("")WRITE !,$LISTSAME("abc",x)WRITE !,$LISTSAME(x,"abc")See Also• $LIST function• $LISTBUILD function• $LISTDATA function• $LISTFIND function• $LISTFROMSTRING function• $LISTGET function• $LISTLENGTH function260 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$LISTTOSTRING• $LISTNEXT• $LISTTOSTRING$LISTTOSTRINGCreates a string from a list.$LISTTOSTRING(list,delimiter)$LTS(list,delimiter)ParameterslistdelimiterA <strong>Caché</strong> list, created using $LISTBUILD or $LISTFROMSTRING, orextracted from another list using $LIST.Optional — A delimiter used to separate substrings. Specify delimiter asa quoted string. If no delimiter is specified, the default is the comma (,)character.Description$LISTTOSTRING takes a <strong>Caché</strong> list and converts it to a string. In the resulting string, theelements of the list are separated by the delimiter.A list represents data in an encoded format which does not use delimiter characters. Thus alist can contain all possible characters, and is ideally suited for bit-string data.$LISTTOSTRING converts this list to a string with delimited elements. It sets aside aspecified character (or character string) to serve as a delimiter. These delimited elements canbe handled using the $PIECE function.Note:The delimiter specified here must not occur in the source data. <strong>Caché</strong> makes no distinctionbetween a character serving as a delimiter and the same character as a datacharacter.ParameterslistA <strong>Caché</strong> list, which contains one or more elements. A list is created using $LISTBUILD orextracted from another list using $LIST.If the expression in the list parameter does not evaluate to a valid list, a error occurs.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 261


<strong>Caché</strong> <strong>ObjectScript</strong> FunctionsSET x=$CHAR(0,0,0,1,16,27,134,240)SET a=$LISTTOSTRING(x,",") // generates a errordelimiterA character (or string of characters) used to delimit substrings within the output string. It canbe a numeric or string literal (enclosed in quotation marks), the name of a variable, or anexpression that evaluates to a string.Commonly, a delimiter is a designated character which is never used within string data, butis set aside solely for use as a delimiter separating substrings. A delimiter can also be a multicharacterstring, the individual characters of which can be used within string data.If you specify no delimiter, the default delimiter is the comma (,) character. You can specifya null string ("") as a delimiter; in this case, substrings are concatenated with no delimiter.To specify a quote character as a delimiter, specify the quote character twice ("""") or use$CHAR(34).ExampleThe following example creates a list of four elements, then converts it to a string with theelements delimited by the colon (:) character:SET namelist=$LISTBUILD("Deborah","Noah","Martha","Bowie")WRITE $LISTTOSTRING(namelist,":")returns "Deborah:Noah:Martha:Bowie"See Also• $LISTFROMSTRING function• $LISTBUILD function• $LIST function• $PIECE function• $LISTDATA function• $LISTFIND function• $LISTGET function• $LISTLENGTH function• $LISTNEXT• $LISTSAME function262 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$NAME$NAMEReturns the name value of a variable or a portion of a subscript reference.$NAME(variable,integer)$NA(variable,integer)ParametersvariableintegerThe variable whose name value is to be returned. It can specify a localor global variable, which can be either subscripted or unsubscripted. Itdoes not need to be a defined variable. If variable is a subscripted global,you can specify a naked global reference.Optional — A numeric value that specifies which portion (level) of asubscript reference to return. It can be a positive integer, the name ofa variable, or an expression.When used, variable must be a subscriptedreference.Description$NAME returns a formatted form of the variable name reference supplied as variable. It doesnot check whether this variable is defined or has a data value. The value $NAME returnsdepends on the parameters used.• $NAME(variable) returns the name value of the specified variable in canonical form;that is, as a fully expanded reference.• $NAME(variable,integer) returns a portion of a subscript reference. Specifically, integercontrols the number of subscripts returned by the function.Execution of this function does not affect the naked indicator.Parametersvariablevariable can be a local or global variable, unsubscripted or subscripted. If variable is anextended global reference, $NAME returns the extended global reference as specified,without checking whether the specified namespace exists and without capitalizing thenamespace name. If variable is a naked global reference, $NAME returns the full globalreference.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 263


<strong>Caché</strong> <strong>ObjectScript</strong> FunctionsintegerThe integer parameter is used when variable is a subscripted reference. If the value of integeris 0, $NAME returns only the name of the variable. If the value of integer is less than thenumber of subscripts in variable, $NAME returns the number of subscripts indicated by thevalue of integer. If integer is greater than the number of subscripts in variable, $NAMEreturns the full subscripted reference.If variable is an unsubscripted variable, the value of integer is ignored; $NAME returns thevariable name. If integer is the null string ("") or a non-numeric string, $NAME returns thevariable name with no subscripts.The value of integer receives standard integer parsing. For example, leading zeros and theplus sign are ignored. Decimal fractions are truncated and ignored. A negative integer valueresults in a error.ExamplesIn this example, the integer parameter specifies the level to return. If the specified numberof subscripts in integer matches or exceeds the number of subscript levels (in this case, 3),then $NAME returns all defined levels, behaving as if you specified the one-parameter form.If you specify an integer level of zero (0), the null string (""), or any non-numeric string (suchas "A"), $NAME returns the name of the array (in this case “^client”)SET ^client(4)="Vermont"SET ^client(4,1)="Brattleboro"SET ^client(4,1,1)="Yankee Ingenuity"SET ^client(4,1,2)="Vermonster Systems"WRITE !,$NAME(^client(4,1,1),1) ; returns 1 levelWRITE !,$NAME(^client(4,1,1),2) ; returns 2 levelsWRITE !,$NAME(^client(4,1,1),3) ; returns 3 levelsWRITE !,$NAME(^client(4,1,1),4) ; returns all (3) levelsWRITE !,$NAME(^client(4,1,1),0) ; returns array nameWRITE !,$NAME(^client(4,1,1),"") ; returns array nameWRITE !,$NAME(^client(4,1,1)) ; returns all (3) levelsIn the following example, $NAME is used with a naked reference in a loop to output thevalues for all elements in the current (user-supplied) array level.READ !,"Array element: ",arySET x=@ary ; dummy operation to set current array and levelSET y=$ORDER(^("")) ; null string to find beginning of levelFOR i=0:0 {WRITE !,@$NAME(^(y))SET y=$ORDER(^(y))QUIT:y=""}The first SET command performs a dummy assignment to establish the user-supplied arrayand level as the basis for the subsequent naked references. The $ORDER function is used264 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


with a naked reference to return the number of the first subscript (whether negative or positive)at the current level.The WRITE command in the FOR loop uses $NAME with a naked global reference andargument indirection to output the value of the current element. The SET command uses$ORDER with a naked global reference to return the subscript of the next existing elementthat contains data. Finally, the postconditional QUIT checks the value returned by $ORDERto detect the end of the current level and terminate the loop processing.You can use the returned $NAME string value for name or subscript indirection or pass it asa parameter to a routine or user-defined function. For more information, refer to Indirectionin Using <strong>Caché</strong> <strong>ObjectScript</strong>. Consider the routine ^DESCEND that lists descendant nodesof the specified node.DESCEND(ROOT) ;List descendant nodesNEW REFSET REF=ROOTIF ROOT'["(" {FOR {SET REF=$QUERY(@REF)QUIT:REF=""WRITE REF,! }}ELSE {SET $EXTRACT(ROOT,$LENGTH(ROOT))=","FOR {SET REF=$QUERY(@REF)QUIT:REF'[ROOTWRITE REF,! }}The following example demonstrates how you can use $NAME to pass a parameter to the^DESCEND routine defined in the previous example.FOR var1="ONE","TWO","THREE" {DO ^DESCEND($NAME(^X(var1))) }^X("ONE",2,3)NotesUses for $NAMEYou typically use $NAME to return the name values of array elements for use with the$DATA and $ORDER functions.If a reference to an array element contains expressions, $NAME evaluates the expressionsbefore returning the canonical form of the name. For example:SET x=1+2SET y=$NAME(^client(4,1,x))WRITE y$NAME<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 265


<strong>Caché</strong> <strong>ObjectScript</strong> Functions$NAME evaluates the variable x and returns the value ^client(4,1,3).Naked Global <strong>Reference</strong>s$NAME also accepts a naked global reference and returns the name value in its canonicalform (that is, a full (non-naked) reference). A naked reference is specified without the arrayname and designates the most recently executed global reference. In the following example,the first SET command establishes the global reference and the second SET command usesthe $NAME function with a naked global reference.SET ^client(5,1,2)="Savings/27564/3270.00"SET y=$NAME(^(3))WRITE yIn this case, $NAME returns the value ^client(5,1,3). The supplied subscript value (3) replacesthe existing subscript value (2), at the current level.For more details, see Naked Global <strong>Reference</strong> in Using <strong>Caché</strong> Multi-Dimensional Storage.Extended Global <strong>Reference</strong>sThe $ZUTIL(68,7) and $ZUTIL(69,7) functions allow you to control whether $NAMEreturns name values in extended global reference form. For example, with extended referencemode in effect:WRITE $NAME(^["PAYROLL"]ROUTINE)The above statement returns the defined namespace PAYROLL and not just ^ROUTINE.$ZUTIL(68,7) sets the extended global reference mode switch on the process level and$ZUTIL(69,7) sets it on the system level.For a description of extended global reference syntax, see the Global Structure chapter inUsing <strong>Caché</strong> Multi-Dimensional Storage.See Also• $DATA function• $ORDER function• $GET function• $ZUTIL(68,7) Extended <strong>Reference</strong> Mode Process Switch function• $ZUTIL(69,7) Extended <strong>Reference</strong> Mode System Default function266 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$NEXT$NEXTReturns the value of the next subscript in a subscripted variable.$NEXT(variable)$N(variable)ParametersvariableThe array subscript to be used to determine the next existing subscriptvalue.Description$NEXT returns the value of the next subscript in the subscripted variable. It can be either alocal or global subscripted array element. The value of the rightmost subscript must be anumber whose value is -1 or greater. If you are using a naked global reference, the nakedindicator must be defined.$NEXT is an obsolete function that has been superseded by the $ORDER function. It isdocumented here only for completeness.Note:Do not use $NEXT in any new code. Use $ORDER in place of $NEXT to retrievesubscripts of an array.Notes$NEXT and $ORDER$NEXT is similar to $ORDER. Both return the subscripts of the next sibling in collatingorder to the specified node. However, $NEXT and $ORDER have different start and failurecodes, as follows:Starting pointFailure code$NEXT-1-1$ORDERNull stringNull StringSee Also$ORDER function<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 267


<strong>Caché</strong> <strong>ObjectScript</strong> Functions$NORMALIZEValidates and returns a numeric value; rounds to a specified precision.$NORMALIZE(num,scale)ParametersnumscaleThe numeric value to be validated. It can be a numeric or string value, avariable name, or any valid <strong>Caché</strong> <strong>ObjectScript</strong> expression.The number of significant digits to round num to as the returned value. Thisnumber can be larger or smaller than the actual number of decimal digits innum.DescriptionThe $NORMALIZE function validates num and returns the normalized form of num. Itperforms rounding (or truncation) of decimal digits using the scale parameter. You can usethe scale parameter to round a decimal number to a specified number of decimal digits, toround a decimal number to an integer, or to truncate a decimal number to an integer.ParametersnumThe number to be validated may be an integer, a decimal number, an exponential number(with the letter “E” or “e”). It may be a string, expression, or variable that resolves to anumber. It may be signed or unsigned, and may contain leading or trailing zeros.$NORMALIZE validates character-by-character. It stops validation and returns the validatedportion of the string if:• num contains any characters other than the digits 0–9, + or – signs, a decimal point (.),and the letter “E” or “e” indicating an exponent.• num contains more than decimal point, or letter “E” or “e”.• If a + or – sign is found after a numeric in num it is considered a trailing sign, and nofurther numerics are parsed.• The letter “E” or “e” indicating an exponent is not followed by an integer.268 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


The scale parameter value causes the returned value to be a rounded or truncated version ofthe num value. The actual value of the num variable is not changed by $NORMALIZE processing.scaleThe mandatory scale parameter is used to specify how many decimal digits to round to.Depending on the value specified, scale can have no effect on decimal digits, round to aspecified number of decimal digits, round to an integer, or truncate to an integer.A non-negative scale value causes num to be rounded to that number of decimal digits. Whenrounding, a value of 5 or greater is always rounded up. To avoid rounding of a decimalnumber, make scale larger than the number of possible decimal digits in num. A scale valueof 0 causes num to be rounded to an integer value (3.9 = 4). A scale value of –1 causes numto be truncated to an integer value (3.9 = 3). A scale value which is non-numeric or the nullstring is equivalent to a scale value of 0.Specify an integer value for scale; decimal digits in the scale value are ignored. You canspecify a scale value larger than the number of decimal digits specified in num. You canspecify a scale value of –1; all other negative scale values result in a error.ExamplesIn the following example, each invocation of $NORMALIZE returns the normalized versionof num with the specified rounding (or integer truncation):WRITE !,$NORMALIZE(0,0) ; All integers OKWRITE !,$NORMALIZE("",0) ; Null string is parsed as 0WRITE !,$NORMALIZE(4.567,2) ; Decimal numbers OKWRITE !,$NORMALIZE("4.567",2) ; Numeric strings OKWRITE !,$NORMALIZE(-+.0,99) ; Leading/trailing signs OKWRITE !,$NORMALIZE(+004.500,1) ; Leading/trailing 0's OKWRITE !,$NORMALIZE(4E2,-1) ; Exponents OKIn the following example, each invocation of $NORMALIZE returns a numeric subset ofnum:WRITE !,$NORMALIZE("4,567",0); NumericGroupSeparators (commas) are not recognized; here validation halts at the comma, and 4 is returned.WRITE !,$NORMALIZE("4A",0); Invalid (non-numeric) character halts validation; here 4 is returned.$NORMALIZEThe following example shows the use of the scale parameter to round (or truncate) the returnvalue:<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 269


<strong>Caché</strong> <strong>ObjectScript</strong> FunctionsWRITE !,$NORMALIZE(4.55,2); When scale is equal to the decimal digits of num,; all digits of num are returned without rounding.WRITE !,$NORMALIZE(3.85,1); num is rounded to 1 decimal digit,; (with values of 5 or greater rounded up); here 3.9 is returned.WRITE !,$NORMALIZE(4.01,17); scale can be larger than number of decimal digits,; and no rounding is peformed; here 4.01 is returned.WRITE !,$NORMALIZE(3.85,0); When scale=0, num is rounded to an integer value.; here 4 is returned.WRITE !,$NORMALIZE(3.85,-1); When scale=-1, num is truncated to an integer value.; here 3 is returned.Notes$NORMALIZE, and $NUMBER ComparedThe $NORMALIZE, and $NUMBER functions both validate numbers and return a validatedversion of the specified number.These two functions offer different validation criteria. Select the one that best meets yourneeds.• Both functions parse signed and unsigned integers (including –0), exponential numbers(with “E” or “e”), and decimal numbers. However, $NUMBER can be set (using the “I”format) to reject decimal numbers (including negative exponents that result in decimalnumbers). Both functions parse both numbers (123.45) and numeric strings (“123.45”).• Both functions strip out leading and trailing zeroes. The decimal character is stripped outunless followed by a non-zero value.• Numeric strings containing a NumericGroupSeparator: $NUMBER parses Numeric-GroupSeparator characters (American format: comma (,); European format: period (.) orapostrophe (')) and the decimal character (American format: period (.) or European format:comma (,)) based on its format parameter (or the default for the current locale). It acceptsand strips out any number of NumericGroupSeparator characters. For example, inAmerican format it validate “123,,4,56.99” as the number 123456.99. $NORMALIZEdoes not recognize NumericGroupSeparator characters. It validates character-by-characteruntil it encounters a non-numeric character; for example, it validates “123,456.99” as thenumber 123.• Multiple leading signs (+ and –) are interpreted by both functions for numbers. Only$NORMALIZE accepts multiple leading signs in a quoted numeric string.270 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


• Trailing + and – signs: Both functions reject trailing signs in numbers. In a quoted numericstring $NUMBER parses one (and only one) trailing sign. $NORMALIZE parses multipletrailing signs.• Parentheses: $NUMBER parses parentheses surrounding an unsigned number in a quotedstring as indicating a negative number. $NORMALIZE treats parentheses as non-numericcharacters.• Numeric strings containing multiple decimal characters: $NORMALIZE validatescharacter-by-character until it encounters the second decimal character. For example, inAmerican format it validates “123.4.56” as the number 123.4. $NUMBER rejects anystring containing more than one decimal character as an invalid number.Numeric strings containing other non-numeric characters: $NORMALIZE validatescharacter-by-character until it encounters an alphabetic character. It validates “123A456”as the number 123. $NUMBER validates or rejects the entire string; it reject “123A456”as an invalid number.• The null string: $NORMALIZE parses the null string as zero (0). $NUMBER rejectsthe null string.The $NUMBER function provide optional min/max range checking. This is also availableusing the $ISVALIDNUM function.$NORMALIZE, $NUMBER, and $ISVALIDNUM all provide rounding of decimal numbersto a specified number of decimal digits. $NORMALIZE can round decimal digits, and roundor truncate a decimal number to return an integer. For example, $NORMALIZE can round488.65 to 488.7 or 489, or truncate it to 488. $NUMBER can round decimal numbers orintegers. For example, $NUMBER can round 488.65 to 488.7, 489, 490 or 500.See Also• $FNUMBER function• $INUMBER function• $ISVALIDNUM function• $NUMBER function• More information on locales in Customized National Language Translations$NORMALIZE<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 271


<strong>Caché</strong> <strong>ObjectScript</strong> Functions$NUMBERValidates and returns a numeric value; optionally provides rounding and range checking.$NUMBER(num,format,min,max)$NUM(num,format,min,max)ParametersnumformatminmaxThe numeric value to be validated and then converted to <strong>Caché</strong> canonicalform. It can be a numeric or string value, a variable name, or any valid<strong>Caché</strong> <strong>ObjectScript</strong> expression.Optional — Specifies which processing options to apply to num. Theseprocessing options dictate primarily how to recognize and handle numberscontaining decimal points.Optional — The minimum acceptable numeric value.Optional — The maximum acceptable numeric value.DescriptionThe $NUMBER function converts and validates the num numeric value using the specifiedformat. It accepts numbers supplied with a variety of punctuation formats and returns numbersin <strong>Caché</strong> canonical form. If min or max are specified, the number must fall within that rangeof values.The $DOUBLE values INF, –INF, and NAN are always returned unmodified, regardless ofthe values of the format, min, or max parameters.ParametersformatThe possible format codes are as follows. These format codes may be specified in any order.A non-numeric format must be specified as a quoted string. Any or all of the following formatcodes may be omitted. If format is invalid, $NUMBER generates a error.• Decimal character: either “.” or “,” indicating whether to use the American (“.”) orEuropean (“,”) convention for validating the decimal point. You can specify either ofthese characters, or no decimal character. If you omit the decimal character, the numbertakes the DecimalSeparator of the current locale.272 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


• Rounding factor: an integer indicating how many decimal places to round to. This integercan be preceded by an optional + or - sign. If the rounding factor is positive (or unsigned)the number is rounded to the specified number of decimal digits. If the rounding factoris 0, the number is rounded to an integer. If the rounding factor is a negative integer, thenumber is rounded the indicated number of places to the left of the decimal separator.For example, a rounding factor of -2 rounds 234.45 to 200. The number “5” is alwaysrounded up; thus a rounding factor of 1 rounds 123.45 to 123.5.• Integer indicator: the letter “I” (uppercase or lowercase) which specifies that the numbermust be an integer.min and maxYou can specify a minimum allowed value, a maximum allowed value, neither, or both. Ifspecified, the num value (after rounding) must be greater than or equal to the min value, andless than or equal to the max value. A null string as a min or max value is equal to zero. If avalue does not meet these criteria, $NUMBER returns the null string.Thus in the following examples, the first is valid because num (4.0) equals max (4). Thesecond is valid because num (4.003) still equals max (4) within the format range (two decimaldigits). However, the third is not valid because $NUMBER rounds num up to a value (4.01)greater than max within the format range. It returns a null string.WRITE !,$NUMBER(4.0,2,0,4)WRITE !,$NUMBER(4.003,2,0,4)WRITE !,$NUMBER(4.006,2,0,4)You can omit parameters, retaining the commas as place holders. The first line of the followingexample sets a max value, but no format or min value. The second line sets no format value,but sets a min value of the null string, which is equivalent to zero. Thus the first line returns–7, and the second line fails the min criteria and returns the null string.SET max=10WRITE !,$NUMBER(-7,,,max)WRITE !,$NUMBER(-7,,"",max)You cannot specify trailing commas. The following results in a error:WRITE $NUMBER(mynum,,min,)$NUMBER<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 273


<strong>Caché</strong> <strong>ObjectScript</strong> FunctionsNotesOrder of Operations$NUMBER performs the following series of conversions and validations. If the number failsany validation step, $NUMBER returns a null string (""). If the number passes all validationsteps, $NUMBER returns the resulting converted <strong>Caché</strong> canonical form number.1. $NUMBER uses the decimal character format to determine which character is the groupseparator and strips out all group separator characters (regardless of location in thenumber). It uses the following rule: If the decimal character specified in format is a period(.), then the group separator is a comma (,) or apostrophe ('). If the decimal characterspecified in format is a comma (,), then the group separator is a period (.) or apostrophe('). If no decimal character is specified in format, the group separator is the Numeric-GroupSeparator property of the current locale.2. $NUMBER validates that the number is well-formed. A well-formed number can containany of the following:• Numbers• An optional decimal indicator character, as defined above (one or none, but not morethan one).• An optional plus (+) or minus (-) sign character (leading or trailing, but not morethan one).• Optional parentheses enclosing the number to indicate a negative value (debit). Thenumber within the parentheses cannot have a sign character.• An optional exponent, indicated by an “E” (uppercase or lowercase) followed by aninteger. If “E” is specified, an exponent integer must be present. The exponent integermay be preceded by a sign character.3. If the integer indicator is present in format, $NUMBER checks for integers. An integercannot contain a decimal indicator character. Numeric strings (“123.45”) and numbers(123.45) are parsed differently. Numeric strings fail this integer test even if there are nodigits following the decimal indicator character, or if expansion of the exponent orrounding would eliminate the decimal digits. Numbers pass these validation tests. If anumber fails the integer indicator check, $NUMBER returns the null string ("").4. $NUMBER converts the number to a <strong>Caché</strong> canonical form number. It expands exponentialnotation, replaces enclosing parentheses with a negative sign character, strips off274 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


leading and trailing zeros, and deletes a decimal indicator character if it is not followedby any non-zero digits.5. $NUMBER uses the rounding factor (if present) to round the number the specifiednumber of digits. It then strips off any leading or trailing zeros and the decimal indicatorcharacter if it is not followed by any digits.6. $NUMBER validates the number against the minimum value, if specified.7. $NUMBER validates the number against the maximum value, if specified.8. $NUMBER returns the resulting number.European and American Decimal Separators$NUMBER returns a number in canonical form, removing all numeric group separators andincludes at most one decimal separator character. You can use the format values “,” or “.” toidentify the decimal separator used in num; by specifying the decimal separator, you are alsoimplicitly specifying the numeric group separator. In following examples, a comma is specifiedas the decimal separator:SET num="123,456"WRITE !,$NUMBER(num,",")// converts to the decimal number "123.456"// (comma is identified as decimal separator)SET num="123,45,6"WRITE !,$NUMBER(num,",")// returns the null string// (invalid number, too many decimal separators)SET num="123.456"WRITE !,$NUMBER(num,",")// converts to the integer "123456"// removing group separator// (if comma is decimal, then period is group separator)SET num="123.4.56"WRITE !,$NUMBER(num,",")// converts to the integer "123456"// removing group separators// (number and placement of group separators ignored)See Also• $FNUMBER function• $INUMBER function• $ISVALIDNUM function• $NORMALIZE function• More information on locales in Customized National Language Translations$NUMBER<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 275


<strong>Caché</strong> <strong>ObjectScript</strong> Functions$ORDERReturns the next local variable or the subscript of a local or global variable.$ORDER(variable,direction,target)$O(variable,direction,target)ParametersvariabledirectiontargetEither a local variable or a subscripted local or global variable. If anarray, the subscript is required. You cannot specify just the arrayname.Optional — The subscript order in which to traverse the target array.Values for subscripted variables can be: 1 = ascending subscriptorder (the default) or –1 = descending subscript order. Forunsubscripted local variables, 1 (the default) is the only permittedvalue.Optional — Returns the current data value of the next or previousnode of variable. Whether it is the next or previous depends on thesetting of direction. You must specify a direction value to specify atarget. For unsubscripted local variables, direction must be set to 1.If variable is undefined, the target value remains unchanged. Thetarget parameter cannot be used with structured system variables(SSVNs) such as ^$ROUTINE.DescriptionThe value $ORDER returns depends on the parameters used.• $ORDER(variable) returns the number of the next defined subscript if variable is asubscripted variable. The returned subscript is at the same level as that specified for thevariable. For example, $ORDER(^client(4,1,2) returns the next subscript (3), assumingthat ^client(4,1,3) exists.$ORDER(variable) returns the name of the next defined local variable in alphabeticcollating sequence, if variable is an unsubscripted local variable. For example, $ORDERwould return the following defined local variables in the following sequence: a, a0a, a1,a1a, aa, b, bb, c.• $ORDER(variable,direction) returns either the next or the previous subscript for thevariable. You can specify direction as 1 (next, the default) or –1 (previous).276 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


For unsubscripted local variables, $ORDER returns variables in direction 1 (next) orderonly; you cannot specify a direction of –1 (previous).• $ORDER(variable,direction,target) returns the subscript for the variable, and sets targetto its current data value. This can be either the next or the previous subscript for a subscriptedvariable, depending on the direction setting. For an unsubscripted local variable,direction must be set to 1 to return the current data value to target. The target parametercannot be used with structured system variables (SSVNs) such as ^$ROUTINE.ExamplesThe following example lists the name and value of the next defined local variables aftervariable a1:SET a="best",a1="prime",aa="choice",b="good",c="utility grade"WRITE !,$ORDER(a1,1,target),!,targetThe following example returns 1, the first subscript in ^X. It sets the naked indicator to thefirst level.SET ^X(1,2,3)="1", ^X(2)="2"WRITE $ORDER(^X(-1))The following example returns 2, the next subscript on the single subscripted level. (The nodeyou specify in the argument need not exist.) The naked indicator is still set to the first level.SET ^X(1,2,3)="1",^X(2)="2"WRITE $ORDER(^X(1))The following example returns 2, the first subscript on the two-subscript level. The nakedindicator is now set at the second level.SET ^X(1,2,3)="1",^X(2)="2"WRITE $ORDER(^X(1,-1))The following example uses $ORDER to list all of the primary subscripts in the ^data global:SET ^data(1)="a",^data(3)="c",^data(7)="g"// Get first subscriptSET key=$ORDER(^data(""))WHILE (key'="") {WRITE key,!// Get next subscriptSET key = $ORDER(^data(key))}$ORDER<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 277


<strong>Caché</strong> <strong>ObjectScript</strong> FunctionsNotesUses for $ORDER$ORDER is typically used with loop processing to traverse the nodes in a sparse array. Asparse array is an array that may contain undefined nodes on any given level. Unlike the$DATA function, $ORDER simply skips over undefined nodes to return the subscript of thenext existing node. For example:SET struct=""FOR {SET struct=$ORDER(^client(struct))QUIT:struct=""WRITE !,^client(struct)}The above routine writes the values for all the top-level nodes in the ^client global array.$ORDER skips over undefined nodes, but not nodes that contain no data. Such nodes includeboth pointer nodes and terminal nodes. If you use $ORDER in a loop to feed a command(such as WRITE) that expects data, you must include a $DATA check for dataless nodes.For example, you could specify the WRITE command in the previous example with a postconditionaltest, as follows:WRITE:(1=$DATA(^client(struct)))!(11=$DATA(^client(struct))) !,^client(struct)This test covers the case of both a dataless pointer node and a dataless terminal node. If yourcode becomes too cumbersome for a simple FOR loop, you can relegate part of it to a blockstructuredDO.Start and End for a SearchTo start a search from the beginning of the current level, specify a null string ("") for thesubscript. This technique is required if the level may contain negative as well as positivesubscripts. The following example returns the first subscript on the array level:SET s=$ORDER(^client(""))WRITE sWhen $ORDER reaches the end of the subscripts for the given level, it returns a null string(""). If you use $ORDER in a loop, your code should always include a test for this value. Ina previous example, QUIT:struct="" is used to detect the end of the level and terminate theloop.278 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ORDER$ORDER Uses Naked Global <strong>Reference</strong>Like the $NAME and $QUERY functions, $ORDER can be used with a naked global reference,which is specified without the array name and designates the most recently executedglobal reference. For example:SET var1=^client(4,5)SET var2=$ORDER(^(""))WRITE "var1=",var1,!,"var2=",var2The first SET command establishes the current global reference, including the subscript levelfor the reference. The $ORDER function uses a naked global reference to return the firstsubscript for this level. For example, it might return the value 1, indicating ^client(4,1).For more details, see Naked Global <strong>Reference</strong> in Using <strong>Caché</strong> Multi-Dimensional Storage.$ORDER and $NEXT$ORDER is similar to $NEXT. Both functions return the subscripts of the next sibling incollating order to the specified node. However, $ORDER and $NEXT have different startand failure codes, as follows:Starting pointFailure code$NEXT-1-1$ORDERNull stringNull StringBecause $ORDER starts and fails on the null string, it correctly returns nodes having bothnegative and positive subscripts.See Also• $NEXT function• $QUERY function• $ZPREVIOUS function• Global Structure chapter in Using <strong>Caché</strong> Multi-Dimensional Storage<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 279


<strong>Caché</strong> <strong>ObjectScript</strong> Functions$PIECEReturns the specified substring, based on a delimiter.$PIECE(plist,delimiter,from,to)$P(plist,delimiter,from,to)ParametersplistdelimiterfromtoThe target string from which a substring is to be returned.A delimiter used to identify substrings.Optional — An integer that specifies the substring, or beginning of arange of substrings, to return from the target string. Substrings areseparated by a delimiter, and counted from 1. If omitted, the firstsubstring is returned.Optional — An integer that specifies the ending substring for a rangeof substrings to return from the target string. Must be used with from.Description$PIECE returns the specified substring (piece) from plist. The substring returned dependson the parameters used:• $PIECE(plist,delimiter) returns the first substring in plist. If delimiter occurs in plist,this is the substring that precedes the first occurrence of delimiter. If delimiter does notoccur in plist, the returned substring is plist.• $PIECE(plist,delimiter,from) returns the substring which is the nth piece of plist, wherethe integer n is specified by the from parameter, and pieces are separated by a delimiter.The delimiter is not returned.• $PIECE(plist,delimiter,from,to) returns a range of substrings including the substringspecified in from through the substring specified in to. This four-argument form of$PIECE returns a string that includes any intermediate occurrences of delimiter thatoccur between the from and to substrings. If to is greater than the number of substrings,the returned substring includes all substrings to the end of the plist string.280 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


ParametersplistThe target string from which the substring is to be returned. It can be a string literal, a variablename, or any valid <strong>Caché</strong> <strong>ObjectScript</strong> expression that evaluates to a string. If you specify anull string ("") as the target string, $PIECE returns the null string.A target string usually contains instances of a character (or character string) which are usedas delimiters. This character or string cannot also be used as a data value within plist.When $PIECE is used with SET on the left hand side of the equals sign, plist must evaluateto a valid variable name.delimiterThe search string to be used to delimit substrings within plist. It can be a numeric or stringliteral (enclosed in quotation marks), the name of a variable, or an expression that evaluatesto a string.Commonly, a delimiter is a designated character which is never used within string data, butis set aside solely for use as a delimiter separating substrings. A delimiter can also be a multicharactersearch string, the individual characters of which can be used within string data.If you specify a null string ("") as the delimiter, $PIECE returns the null string.from$PIECEThe number of a substring within plist, counting from 1. It must be a positive integer, thename of an integer variable, or an expression that evaluates to a positive integer. Substringsare separated by delimiters.• If the from parameter is omitted or set to 1, $PIECE returns the first substring of plist.If plist does not contain the specified delimiter, a from value of 1 returns plist.• If the from parameter identifies by count the last substring in plist, this substring isreturned, regardless of whether it is followed by a delimiter.• If the value of from is the null string (""), zero, a negative number, or greater than thenumber of substrings in plist, $PIECE returns a null string.If the from parameter is used with the to parameter, it identifies the start of a range of substringsto be returned as a string, and should be less than the value of to.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 281


<strong>Caché</strong> <strong>ObjectScript</strong> FunctionstoThe number of the substring within plist that ends the range initiated by the from parameter.The returned string includes both the from and to substrings, as well as any intermediatesubstrings and the delimiters separating them. The to argument must be a positive integer,the name of an integer variable, or an expression that evaluates to a positive integer. The toparameter must be used with from and should be greater than the value of from.• If from is less than to, $PIECE returns a string consisting of all of the delimited substringswithin this range, including the from and to substrings. This returned string contains thesubstrings and the delimiters within this range.• If to is greater than the number of delimited substrings, the returned string contains allthe string data (substrings and delimiters) beginning with the from substring and continuingto the end of the plist string.• If from is equal to to, the from substring is returned.• If from is greater than to, $PIECE returns a null string.• If to is the null string (""), $PIECE returns a null string.ExamplesThe following example returns "Red", the first substring as identified by the "," delimiter:SET colorlist="Red,Green,Blue,Yellow,Orange,Black"SET extract=$PIECE(colorlist,",")WRITE extractThe following example returns "Blue”, the third substring as identified by the "," delimiters:SET colorlist="Red,Green,Blue,Yellow,Orange,Black"SET extract=$PIECE(colorlist,",",3)WRITE extractThe following example returns "Blue,Yellow,Orange", the third through fifth substrings incolorlist, as delimited by ",":SET colorlist="Red,Green,Blue,Yellow,Orange,Black"SET extract=$PIECE(colorlist,",",3,5)WRITE extractThe following WRITE statements all return the first substring “123”, showing that theseformats are equivalent when from and to have a value of 1:SET numlist="123#456#789"WRITE !,"2-arg=",$PIECE(numlist,"#")WRITE !,"3-arg=",$PIECE(numlist,"#",1)WRITE !,"4-arg=",$PIECE(numlist,"#",1,1)282 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


In the following example, both $PIECE functions returns the entire plist string, because thereare no occurrences of delimiter in the plist string:SET colorlist="Red,Green,Blue,Yellow,Orange,Black"SET extract1=$PIECE(colorlist,"#")SET extract2=$PIECE(colorlist,"#",1,4)WRITE "# =",extract1,!,"#,1,4=",extract2The following two examples use more complex delimiters.This example uses a delimiter string “#-#” to return three substrings of the string numlist.Here, the component characters of the delimiter string, “#” and “-”, can be used as data values;only the specified sequence of characters (#-#) is set aside:SET numlist="1#2-3#-#45##6#-#789"WRITE !,$PIECE(numlist,"#-#",1)WRITE !,$PIECE(numlist,"#-#",2)WRITE !,$PIECE(numlist,"#-#",3)The following example uses a non-keyboard delimiter character (in this case, the Unicodecharacter for pi), specified using the $CHAR function, and inserted into the plist string byusing the concatenate operator (_):SET a = $CHAR(960)SET colorlist="Red"_a_"Green"_a_"Blue"SET extract1=$PIECE(colorlist,a)SET extract2=$PIECE(colorlist,a,2)SET extract3=$PIECE(colorlist,a,2,3)WRITE extract1,!,extract2,!,extract3NotesUsing $PIECE to Unpack Data Values$PIECE is typically used to "unpack" data values that contain multiple fields delimited bya separator character. Typical delimiter characters include the slash (/), the comma (,), thespace ( ), and the semicolon (;). The following sample values are good candidates for usewith $PIECE:"John Jones/29 River St./Boston MA, 02095""Mumps;Measles;Chicken Pox;Diptheria""45.23,52.76,89.05,48.27"$PIECE and $LENGTH$PIECEThe two-argument form of $LENGTH returns the number of substrings in a string, basedon a delimiter. Use $LENGTH to determine the number of substrings in a string, and thenuse $PIECE to extract individual substrings, as shown in the following example:<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 283


<strong>Caché</strong> <strong>ObjectScript</strong> FunctionsSET sentence="The quick brown fox jumped over the lazy dog's back."SET delim=" "SET countdown=$LENGTH(sentence,delim)SET countup=1FOR reps=countdown:-1:1 {SET extract=$PIECE(sentence,delim,countup)WRITE !,countup," ",extractSET countup=countup+1}WRITE !,"All done!"$PIECE and $LISTThe data storage methods used by $PIECE and the $LIST functions are incompatible andshould not be combined. For example, attempted to use $PIECE on a list created using$LISTBUILD yields unpredictable results and should be avoided.The $LIST functions specify substrings without using a designated delimiter. If setting asidea delimiter character or character sequence is not appropriate to the type of data (for example,bitstring data), you should use the $LISTBUILD and $LIST functions to store and retrievesubstrings.Null Values$PIECE does not distinguish between a delimited substring with a null string value, and anon-existent substring. Both return a null string value. For example, the following examplesboth return the null string for a from value of 7:SET colorlist="Red,Green,Blue,Yellow,Orange,Black"SET extract1=$PIECE(colorlist,",",6)SET extract2=$PIECE(colorlist,",",7)WRITE "6=",extract1,!,"7=",extract2SET colorlist="Red,Green,Blue,Yellow,Orange,Black,"SET extract1=$PIECE(colorlist,",",6)SET extract2=$PIECE(colorlist,",",7)WRITE "6=",extract1,!,"7=",extract2In the first case, there is no seventh substring; a null string is returned. In the second casethere is a seventh substring, as indicted by the delimiter at the end of the plist string; the valueof this seventh substring is the null string.The following example shows null values within a plist. It extracts substrings 1 and 3. Thesesubstrings exists, but both contain a null string. (Substring 1 is defined as the string precedingthe first delimiter character):SET colorlist=",Red,,Blue,"SET extract1=$PIECE(colorlist,",")SET extract3=$PIECE(colorlist,",",3)WRITE !,"sub1=",extract1,!,"sub3=",extract3284 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


The following examples also returns a null string, because the specified substrings do notexist:SET colorlist="Red,Green,Blue,Yellow,Orange,Black"SET extract=$PIECE(colorlist,",",0)WRITE !,"Length=",$LENGTH(extract),!,"Value=",extractSET colorlist="Red,Green,Blue,Yellow,Orange,Black"SET extract=$PIECE(colorlist,",",8,20)WRITE !,"Length=",$LENGTH(extract),!,"Value=",extractNested $PIECE OperationsTo perform complex extractions, you can nest $PIECE references within each other. Theinner $PIECE returns a substring that is operated on by the outer $PIECE. Each $PIECEuses its own delimiter. For example, the following returns the state abbreviation “MA”:SET patient="John Jones/29 River St./Boston MA 02095"SET patientstateaddress=$PIECE($PIECE(patient,"/",3)," ",2)WRITE patientstateaddressThe following is another example of nested $PIECE operations, using a hierarchy of delimiters.First, the inner $PIECE uses the circumflex (^) delimiter to find the second piece ofnestlist: "A,B,C". Then the outer $PIECE uses the comma (,) delimiter to return the first andsecond pieces ("A,B") of the substring "A,B,C":SET nestlist="1,2,3^A,B,C^@#!"WRITE $PIECE($PIECE(nestlist,"^",2),",",1,2)Using $PIECE to the Left of the Equals SignWhen making assignments with the SET command, you can use $PIECE to the left, as wellas to the right, of the equals sign. When used to the left of the equals sign, $PIECE designatesa substring to be replaced by the assigned value. The only restriction is that the expressionparameter evaluate to a valid variable name. It cannot be a general expression.The use of $PIECE (and $EXTRACT) in this context differs from other standard functionsbecause it modifies an existing value, instead of just returning a value. The following examplechanges the value of colorlist to "Red,Green,Cyan,Yellow,Orange,Black":SET colorlist="Red,Green,Blue,Yellow,Orange,Black"WRITE !,colorlistSET $PIECE(colorlist,",",3)="Cyan"WRITE !,colorlist$PIECEIf $PIECE specifies more occurrences of the delimiter than exist in the target variable, itappends additional delimiters to the end of the value, up to one less than the specified number.The following example changes the value of smallcolor to "Green;Blue;;Red". The number<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 285


<strong>Caché</strong> <strong>ObjectScript</strong> Functionsof delimiter characters added is equal to the from value, minus the number of existingdelimiters, minus one:SET smallcolor="Green;Blue"WRITE !,smallcolorSET $PIECE(smallcolor,";",4)="Red"WRITE !,smallcolorThe following example initializes newvar to the character pattern ">>>>>>TOTAL":SET newvar=""SET $PIECE(newvar,">",7)="TOTAL"WRITE newvarSee the "SET with $PIECE and $EXTRACT" section of the SET command documentationfor more information.$PIECE with Parameters over 32,768 CharactersThe following example creates a string of 5 periods and a null:SET x="",$PIECE(x,".",6)=""WRITE xNow consider the following example that creates a string of 32767 periods and a null:SET x="",$PIECE(x,".",32768)=""Although technically within the maximum length of a string, this example generates a error. Do not use a parameter with $PIECE greater than 32767.See Also• $EXTRACT function• $LENGTH function• $LIST function• $LISTBUILD function• SET command286 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$QLENGTH$QLENGTHReturns the number of subscripts in the specified local or global variable.$QLENGTH(namevalue)$QL(namevalue)ParametersnamevalueA string, or expression that evaluates to a string, which is a local orglobal reference.Description$QLENGTH returns the number of subscripts in a local variable, a process-private global,or a global specified by namevalue.ParametersnamevalueA string, or expression that evaluates to a string, which is a local or global reference. If thestring is a global reference, it can contain a namespace reference. It can have the formNAME(s 1 ,s 2 ,...,s n ).ExamplesThe following example show the results of $QLENGTH when used with subscripted andunsubscripted globals. The first $QLENGTH returns 0. The second $QLENGTH returns2.WRITE !,$QLENGTH("^|""USER""|%test")SET name="^|""USER""|%test(1,""customer"")"WRITE !,$QLENGTH(name)The following example returns the $QLENGTH value for a process-private global with twosubscript levels. The $ZREFERENCE special variable contains the name of the most recentlyreferenced variable.SET ^||myppg("food","fruit")="apples"WRITE !,$QLENGTH($ZREFERENCE) ; returns 2See Also• $QSUBSCRIPT function<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 287


<strong>Caché</strong> <strong>ObjectScript</strong> Functions• $ZREFERENCE special variable• Global Structure in Using <strong>Caché</strong> Multi-Dimensional Storage$QSUBSCRIPTReturns the variable name, its subscript names, or the namespace name for a global or othervariable.$QSUBSCRIPT(namevalue,intexpr)$QS(namevalue,intexpr)ParametersnamevalueintexprA string or an expression that evaluates to a string which is a local orglobal reference.An integer code that specifies which value to return.Description$QSUBSCRIPT returns the namespace environment name, the variable name, or the nameof the specified subscript of namevalue, depending on the value of intexpr.ParametersnamevalueA string or an expression that evaluates to a string which is a local variable, a process-privateglobal, or a global reference. If the string is a global reference, it can contain a namespacereference. The namevalue parameter can have the form: NAME(s 1 ,s 2 ,...,s n ).intexprInteger expression code that indicates which type of value to return. Assume that the namevalueparameter has the form NAME(s 1 ,s 2 ,...,s n ), where n is the ordinal number of the last subscript.The intexpr parameter can have any of the following values:288 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$QSUBSCRIPTCode< -1-10nReturn ValueGenerates a error; these numbers are reserved for futureextensions.Returns the namespace name if namevalue includes one; otherwise, returnsthe null string ("").Returns NAME without the namespace name, even if one is present.Returns the subscript value denoted by s n .Returns the null string ("").ExamplesThe following example returns $QSUBSCRIPT values when namevalue is a subscriptedglobal with one subscript level and a specified namespace:SET global="^|""account""|%test(""customer"")"WRITE !,$QSUBSCRIPT(global,-1) ; accountWRITE !,$QSUBSCRIPT(global,0) ; ^%testWRITE !,$QSUBSCRIPT(global,1) ; customerWRITE !,$QSUBSCRIPT(global,2) ; null stringThe following example returns $QSUBSCRIPT values when namevalue is a process-privateglobal with two subscript levels. The $ZREFERENCE special variable contains the nameof the most recently referenced variable.SET ^||myppg(1,3)="apples"WRITE !,$QSUBSCRIPT($ZREFERENCE,-1) ; null stringWRITE !,$QSUBSCRIPT($ZREFERENCE,0) ; ^||myppgWRITE !,$QSUBSCRIPT($ZREFERENCE,1) ; 1WRITE !,$QSUBSCRIPT($ZREFERENCE,2) ; 3See Also• $QLENGTH function• $ZREFERENCE special variable• Global Structure in Using <strong>Caché</strong> Multi-Dimensional Storage<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 289


<strong>Caché</strong> <strong>ObjectScript</strong> Functions$QUERYPerforms a physical scan of a local or global array.$QUERY(reference,direction,target)$Q(reference,direction,target)ParametersreferencedirectiontargetA reference that evaluates to the name (and optionally subscripts) ofa local or global variable.Optional — The direction (forwards or backwards) to traverse the array.Optional — Returns the current data value of the local or global variablespecified in reference.Description$QUERY performs a physical scan of a local or global array; it returns the full reference,name and subscripts, of the defined node next in sequence to the specified array node. If nosuch node exists, $QUERY returns the null string.ParametersreferenceThe returned global reference can be at the same level, a lower level, or a higher level as thelevel specified in the reference parameter. If you specify reference without specifying subscripts,$QUERY returns the first defined node in the array.directionIf no direction is specified, the default direction is forward. If you wish to specify a direction,a parameter value of 1 will traverse the array forward, a value of -1 will traverse the arraybackward.targetIf you wish to specify a target, you must specify a direction. If the variable identified in thereference parameter is undefined, the target value remains unchanged.290 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


ExampleThis example presents a generalized routine for outputting the data values for all the nodesin a user-specified array. It can accommodate arrays with any number of levels. The codeperforms the same operation as the code shown in the example under the $ORDER function.Instead of requiring 23 lines, however, it requires only six and is not restricted as to thenumber of levels it can handle.Start READ !,"Array name: ",ary QUIT:ary=""SET queryary=$QUERY(@ary@(""))WRITE !,@queryaryFOR {SET queryary=$QUERY(@queryary)QUIT:queryary=""WRITE !,@queryary}WRITE !,"Finished."QUITThe first SET command uses $QUERY with subscript indirection to initialize the globalreference to the first existing node that contains data. For more information, refer to Indirectionin Using <strong>Caché</strong> <strong>ObjectScript</strong>. (Like $ORDER, $QUERY accepts a null string to designatethe first subscript in an array.) The first WRITE command outputs the value of the first nodefound. If it were omitted, the first node would be skipped.In the FOR loop, $QUERY is used to retrieve the next node and update the global reference,whose contents are then output by the WRITE command. The postconditional QUIT terminatesthe loop when it finds a null string (""), indicating that $QUERY has reached the endof the array.No $DATA tests are required, unless you wish to distinguish between pointer nodes($DATA=11) and terminal nodes ($DATA=1).NotesUsing $QUERY to Traverse an ArrayUsed repetitively, $QUERY can traverse an entire array in left-to-right, top-to-bottom fashion,returning the entire sequence of defined nodes. $QUERY can start at the point determinedby the subscript specified for reference. It proceeds along both the horizontal and verticalaxes. For example:SET exam=$QUERY(^client(4,1,2))$QUERYBased on this example, $QUERY might return any of the following values, assuming a threelevelarray:<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 291


<strong>Caché</strong> <strong>ObjectScript</strong> FunctionsValue^client(4,1,3)^client(4,2)^client(5)null string ("")Returned by the $QUERY Function If...If ^client(4,1,3) exists and contains data.If ^client(4,1,3) does not exist or does not contain data and if^client(4,2) does exist and contains data.If ^client(4,1,3) and ^client(4,2) do not exist or do not contain data andif ^client(5) does exist and contains data.If none of the previous global references exist or contain data; $QUERYhas reached the end of the array.With a direction value of -1, $QUERY can traverse an entire array in reverse order in rightto-left,bottom-to-top fashion.$QUERY Compared to $ORDER$QUERY differs from the $ORDER function in that $QUERY returns a full global reference,while $ORDER returns only the subscript of the next node. $ORDER proceeds along onlythe horizontal axis, across nodes at one level.$QUERY also differs from $ORDER in that it selects only those existing nodes that containdata. $ORDER selects existing nodes, regardless of whether or not they contain data. Where$ORDER performs an implicit test for existence ($DATA'=0), $QUERY performs an implicittest for both existence and data ($DATA'=0 and $DATA'=10). Note, however, that $QUERYdoes not distinguish between pointer nodes ($DATA=11) and terminal nodes ($DATA=1)that contain data. To make this distinction, you must include appropriate $DATA tests inyour code.Like $ORDER, $QUERY is typically used with loop processing to traverse the nodes in asparse array. A sparse array is an array that can contain undefined nodes on any given level.$QUERY simply skips undefined or empty nodes to return the global reference of the nextexisting node. $QUERY provides very compact code for accessing global arrays.Like the $NAME and $ORDER functions, $QUERY can be used with a naked global reference,which is specified without the array name and designates the most recently executedglobal reference. For example:SET a=^client(1)SET x=2SET z=$QUERY(^(x))The first SET command establishes the current global reference, including the level for thereference. The second SET command sets up a variable for use with subscripts. The $QUERY292 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


function uses a naked reference to return the full global reference for the next node following^client(2). For example, the returned value might be ^client(2,1) or ^client(3).$QUERY and $ZUTIL(68,7) and $ZUTIL(69,7)The $ZUTIL(68,7) and $ZUTIL(69,7) functions allow you to control whether $QUERYreturns global references in Extended Global <strong>Reference</strong> mode.$ZUTIL(68,7) lets you set the Extended Global <strong>Reference</strong> mode switch for a particularprocess and $ZUTIL(69,7) lets you set the Extended Global <strong>Reference</strong> mode switch for theentire system.For further details on extended global references, see the Global Structure chapter in Using<strong>Caché</strong> Multi-Dimensional Storage.See Also• $DATA function• $ORDER function• $ZUTIL(68,7) Extended <strong>Reference</strong> Mode Process Switch function• $ZUTIL(69,7) Extended <strong>Reference</strong> Mode System Default function$RANDOM$RANDOMReturns a pseudo-random integer value in the specified range.$RANDOM(range)$R(range)ParameterrangeA nonzero positive integer used to calculate the random number.Description$RANDOM returns a pseudo-random integer value between 0 and range-1 (inclusive).Returned numbers are uniformly distributed across the specified range.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 293


<strong>Caché</strong> <strong>ObjectScript</strong> FunctionsParametersrangeA nonzero positive integer used to calculate the random number. The number returned isbetween zero and the value of range-1. It can be a nonzero positive integer value, the nameof an integer variable, or any valid <strong>Caché</strong> <strong>ObjectScript</strong> expression that evaluates to a nonzeropositive integer.ExamplesThe following example returns a random number from 0 through 24 (inclusive).WRITE $RANDOM(25)To return a random number with a decimal portion, you can use the concatenation operator(_) or the addition operator (+), as shown in the following example:SET x=$RANDOM(10)_$RANDOM(10)/10WRITE !,xSET y=$RANDOM(10)+($RANDOM(10)/10)WRITE !,yThis program returns numbers with one decimal position, ranging between .0 and 9.9(inclusive). Using either operator, <strong>Caché</strong> deletes any leading and trailing zeros (and the decimalpoint, if the decimal portion is zero). However, if both $RANDOM functions returnzero (0 and .0), <strong>Caché</strong> returns a zero (0).The following example simulates the roll of two dice.DiceWRITE !,"Do you want to roll the dice?"WRITE !, "Press to exit"READ !,"Roll Dice",AQUIT:A=""WRITE !,$RANDOM(6)+1,"+",$RANDOM(6)+1GOTO Dice294 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$REVERSE$REVERSEReturns the characters in a string in reverse order.$REVERSE(string)$RE(string)ParameterstringA string or expression that evaluates to a string.Description$REVERSE returns the characters in string in reverse order.ExamplesThe following WRITE commands shows the return value from $REVERSE. The first returns“CBA”, the second returns 321.WRITE !,$REVERSE("ABC")WRITE !,$REVERSE(123)You can use the $REVERSE function with other functions to perform search operationsfrom the end of the string. The following example demonstrates how you can use $REVERSEwith the $FIND and $LENGTH functions to locate the position of a word within a line oftext. It returns 33:SET line="THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG."SET position=$L(line)+2-$F($RE(line),$RE("THE"))WRITE "The second THE in the line begins at ",positionSee Also• $FIND function• $EXTRACT function• $LENGTH function• $PIECE function<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 295


<strong>Caché</strong> <strong>ObjectScript</strong> Functions$SELECTReturns the value associated with the first true expression.$SELECT(expression:value,...)$S(expression:value,...)ParametersexpressionvalueThe select test for the associated value parameter.The value to be returned if the associated expression evaluates totrue.DescriptionThe $SELECT function returns the value associated with the first expression that evaluatesto true (1). Each $SELECT argument is a pair of expressions separated by a colon. The lefthalf is a truth-valued expression. The right half can be any expression.The specified list of expression:value pairs can be of any length. $SELECT evaluates theparameters from left to right. When $SELECT discovers a truth-valued expression with thevalue of true (1), it returns the matching expression to the right of the colon. $SELECT stopsevaluation after it discovers the left-most true truth-valued expression. It never evaluates laterpairs on the parameter list.ParametersexpressionThe select test for the associated value parameter. It can be any valid <strong>Caché</strong> relational orlogical expression. If no expression evaluates to true, <strong>Caché</strong> generates a error.To prevent an error from disrupting an executing routine, the final expression can be the value1, which always tests true.valueThe value to be returned if the associated expression evaluates to true. It can be a numericvalue, a string literal, a variable name, or any valid <strong>Caché</strong> <strong>ObjectScript</strong> expression. If youspecify an expression for value, it is evaluated only after the associated expression evaluatesto true. If value contains a subscripted global reference, it changes the naked indicator whenit is evaluated. For this reason, be careful when using naked global references either within296 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


or immediately after a $SELECT function. For more details on the naked indicator, seeNaked Global <strong>Reference</strong> in Using <strong>Caché</strong> Multi-Dimensional Storage.ExampleIn this example, the $SELECT function selects the destination for the GOTO based on theuser's input.StartREAD !,"Which level: ",aQUIT:a=""SET x=$SELECT(a=1:"Level1",a=2:"Level2",a=3:"Level3")GOTO @xNotesIncluding a Default ValueTo ensure that a error never results, you should always include the value 1 asthe last expression with an appropriate default value at the end of the list. For example:StartREAD !,"Which level: ",aQUIT:a=""SET x=$SELECT(a=1:"Level1",a=2:"Level2",a=3:"Level3",1:"Start")GOTO @xIf the user enters a value other then 1, 2, 3, or the null string, control is passed back to theprompt.Replacing the IF CommandYou can use $SELECT to replace IF command clauses. The following example uses IF,ELSEIF, and ELSE clauses to determine whether a number is odd or even.OddsREAD !,"ENTER A NUMBER: ",XQUIT:X=""WRITE !,"THE NUMBER IS "IF X#1 { WRITE "NOT AN INTEGER" }ELSEIF X#2=1 { WRITE "ODD" }ELSE { WRITE "EVEN" }GOTO Odds$SELECTThe following example also accepts a number and determines if the number is odd or even.It uses $SELECT to replace the IF command in the previous example:OddsREAD !,"ENTER A NUMBER: ", XQUIT:X=""WRITE !,"NUMBER IS ",$SELECT(X#1:"NOT AN INTEGER",X#2=1:"ODD",1:"EVEN")GOTO Odds<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 297


<strong>Caché</strong> <strong>ObjectScript</strong> FunctionsSee Also• $CASE function$SORTBEGINInitiates a sorting mode to improve performance of multiple sets to a global.$SORTBEGIN(set_global)Parametersset_globalA global variable name.Description$SORTBEGIN initiates a special sorting mode during which sets to the specified targetglobal are redirected to a process-private temporary area and sorted into subsets. This modeis ended with a call to $SORTEND which copies the data into the target global reference.When the special sorting mode is in effect, all sets to the target global reference and any ofits descendants are affected.$SORTBEGIN is designed to help the performance of operations, such as index building,where a large amount of unordered data needs to be written to a global. When the amount ofdata written approaches or exceeds the amount of available buffer pool memory, performancecan suffer drastically. $SORTBEGIN solves this problem by guaranteeing that data is writtento the target global in sequential order, thus minimizing the number of physical disk accessesneeded. It does this by writing and sorting data into one or more temporary buffers (usingspace in the ^CacheTemp global if needed) and then, when $SORTEND is called, copyingthe data sequentially into the target global.While $SORTBEGIN is in effect, data read from the target global will not reflect any setoperations. You cannot use $SORTBEGIN in cases where you need to read global valuesfrom the same global in which you are inserting values.<strong>Caché</strong> Objects and <strong>Caché</strong> SQL applications automatically make use of $SORTBEGIN forindex and temporary index creation.The $SORTBEGIN sorting mode can be terminated without writing data to the target globalby calling $SORTEND with it optional second parameter set to 0.298 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


If successful, $SORTBEGIN returns a non-zero integer value. If unsuccessful, $SORTBEGINreturns zero.If you establish a $SORTBEGIN global, and then issue a $SORTBEGIN for an ancestoror descendent of that global, <strong>Caché</strong> issues a error. For example, if youinvoke $SORTBEGIN(^test(1,2,3)), the following function calls result in a error: $SORTBEGIN(^test(1,2)) or $SORTBEGIN(^test(1,2,3,4)).See Also• $SORTEND function$SORTEND$SORTENDConcludes the sorting mode initiated by $SORTBEGIN to improve performance of multiplesets to a global.$SORTEND(set_global,dosort)Parametersset_globaldosortA global variable name.Optional — A flag parameter. If 1, <strong>Caché</strong> performs the sort operationinitiated by $SORTBEGIN and copies the sorted data into set_global.If 0, <strong>Caché</strong> terminates the sort operation without copying any data.The default is 1.Description$SORTEND specifies the end of a special sorting mode initiated by $SORTBEGIN on aspecific target global. The value of set_global must match the corresponding parameterspecified for $SORTBEGIN.If successful, $SORTEND returns the total number of global nodes set as an integer value.If unsuccessful, $SORTEND returns -1.See Also• $SORTBEGIN function<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 299


<strong>Caché</strong> <strong>ObjectScript</strong> Functions$STACKReturns information about active contexts saved on the process call stack.$STACK(context_level,code_string)$ST(context_level,code_string)Parameterscontext_levelcode_stringThe zero-based context level number that specifies the contextfor which information is requested.Optional — An ASCII character string that specifies the kind ofcontext information that is requested.DescriptionEach time a routine invokes a DO command, an XECUTE command, or a user-definedfunction (but not a GOTO command), the context of the currently executing routine is savedon the call stack and execution starts in the newly created context of the called routine. Thecalled routine, in turn, can call another routine, and so on, causing more saved contexts to beplaced on the call stack.The $STACK function returns information about these active contexts saved on your processcall stack. $STACK also can return information about the currently executing context.However, during error processing, $STACK returns a snapshot of all the context informationthat is available when an error occurs in your application.See Error Handling in Using <strong>Caché</strong> <strong>ObjectScript</strong> for more detailed information about errorprocessing and your error process stack.The One-Argument Form of $STACK$STACK(context_level) returns a string that indicates how the specified context level wasestablished. The following table describes the string values that can be returned:300 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$STACKDOXECUTE$$ECODEReturned when the specified context was established by a DO command.Returned when the specified context was established by an XECUTEcommand.Returned when the specified context was established by a user-definedfunction reference.The error code of the error that caused the specified context to be addedto the error stack. When an error occurs at a context level where an errorhas already occurred, the context information is placed at the next highererror stack level; it is only returned when context information at the specifiederror stack context level is relocated information.When the specified context level is zero (0) or is undefined, $STACK returns the null string.You can also specify a -1 for the context level in the one-argument form of the $STACKfunction. In this case, $STACK returns the maximum context level for the information thatis available that, during normal processing, is the context level number of the currently executingcontext. However, during error processing, $STACK(-1) returns whichever is greater:• The maximum context level of your process error stack• The context level number of the currently executing contextThe Two-Argument Form of $STACK$STACK(context_level,code_string) returns information about the specified context levelaccording to the code-string designation you specify. The following describes the code stringsand the information returned when you specify each.• PLACE — Returns the entry reference and command number of the last command executedat a specified context level. The value is returned in the following format for DOand user-defined function contexts: "label[+offset][^routine name] +command". ForXECUTE contexts, the following format is used: "@ +command".• MCODE — Returns the source routine line, XECUTE string, or $ETRAP string thatcontains the last command executed at the specified context level. (Routine lines arereturned in the same manner as those returned by the $TEXT function.)Note:During error processing, if memory is low while the error stack is being built orupdated, you may not have enough memory to store the source line. In this case,the return value for the MCODE code string is the null string. However, thereturn value for the PLACE code string indicates the location.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 301


<strong>Caché</strong> <strong>ObjectScript</strong> Functions• ECODE — The error code of any error that occurred at the specified context level(available only in error stack contexts).When the requested information is not available at the specified context level, the two argumentform of $STACK returns the null string.ExampleThe following example demonstrates some of the information that $STACK can return:STAC ;SET $ECODE=""XECUTE "DO First"QUITFirst SET varSecond=$$Second()QUITSecond() FOR loop=0:1:$STACK(-1) {WRITE !,"Context level:",loop,?25,"Context type: ",$STACK(loop)WRITE !,?5,"Current place: ",$STACK(loop,"PLACE")WRITE !,?5,"Current source: ",$STACK(loop,"MCODE")WRITE ! }QUIT 1>DO ^STACContext level: 0 Context type:Current place: @ +1Current source: DO ^STACContext level: 1 Context type: DOCurrent place: STAC+2^STAC +1Current source: XECUTE "DO First"Context level: 2 Context type: XECUTECurrent place: @ +1Current source: DO FirstContext level: 3 Context type: DOCurrent place: First^STAC +1Current source: First SET Second=$$SecondContext level: 4 Context type: $$Current place: Second+2^STAC +4Current source: WRITE !,?5,"Current source: ",$STACK(loop,"MCODE")Notes$STACK Contains Error Stack Context When Errors OccurError stack context information is only available after an error occurs and the value of the$ECODE special variable contains a non-null value. In this case, $STACK returns informationabout the error stack context rather than an active stack context at the specified context level.When error stack context information is not available and you specify the current contextlevel with the two-argument form of $STACK, <strong>Caché</strong> returns information about the currentlyexecuting command.302 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$STACK$STACK Code String Arguments are Case InsensitiveThe code_string arguments you specify with the two-argument form of $STACK are caseinsensitive. For example, $STACK(1,"PLACE") and $STACK(1,"place") are equivalent.$STACK Counts Multiple-Argument CommandsWhen you specify a multiple-argument command, the command count includes commandkeywords and all command arguments beyond the first. Consider the following multipleargumentcommand:TESTSET X=1,Y=ZIn <strong>Caché</strong>, the $STACK statement, $STACK(i,PLACE) returns "TEST^TEST +2" becausethe Y=Z argument counts as a separate command.$STACK with Errors or Low Memory ConditionsAfter a error or under low-memory conditions, the information available normallythrough the application of the two-argument form of $STACK may not be available.See Also• DO command• XECUTE command• $ESTACK special variable• $STACK special variable• Error Handling in Using <strong>Caché</strong> <strong>ObjectScript</strong><strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 303


<strong>Caché</strong> <strong>ObjectScript</strong> Functions$TEXTReturns a line of source code found at the specified location.$TEXT(label+offset^routine)$TEXT(@expr_atom)$T(label+offset^routine)$T(@expr_atom)Parameterlabel+offset^routine@expr_atomOptional — A line label in a routine.Optional — A positive integer that identifies the line to be returned.Optional — A separate routine that resides on disk.Optional — An expression atom that uses indirection to supply alocation.Description$TEXT returns a line of source code found at the specified location. The source code isreturned as text and is not executed at the reference point. If $TEXT does not find sourcecode at the specified location, it returns the null string. In the returned source code, $TEXTreplaces any whitespace (including tab characters) at the start of the line or between the labeland the body of the line, with a single space character. $TEXT does not recognize the Returncharacter that terminates the line.ParameterslabelThe label within the current routine or, if the routine parameter is also supplied, in a separateroutine.offsetIf specified alone, the offset indicates a line number within the current routine. If specifiedwith the label parameter, the line number is calculated from the start of the label. If specifiedwith routine (and without label), the line number is calculated from the start of the separateroutine.304 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$TEXTroutineIf specified alone, it indicates the first line of code in the routine. If specified with only thelabel parameter, the line found at that specified label within the routine is returned. If specifiedwith only the offset parameter, the line at the specified offset within the routine is returned.If both label and offset are supplied, the line found at the specified offset within the specifiedlabel within the routine is returned.expression atom (@expr_atom)An indirect argument that evaluates to a $TEXT argument (label+offset^routine). For moreinformation, refer to Indirection in Using <strong>Caché</strong> <strong>ObjectScript</strong>.ExamplesThis example shows the $TEXT(label) form, which returns the line found at the specifiedlabel within the current routine. The label is also returned. If the user enters "?", the Info textis written out, along with the line label, and control returns to the initial prompt:Start READ !,"Array name or ? for Info: ",ary QUIT:ary=""IF ary="?" {WRITE !,$TEXT(Info),! GOTO Start }Info ;; This routine outputs the entire contents of a global array.QUITThis example shows the $TEXT(label+offset) form, which returns the line found at the offsetwithin the specified label, which must be within the current routine. If the offset is 0, the labelline, with the label, is returned. You can use this form in a FOR loop, to access multilinetext:Start READ !,"Array name or ? for Info: ",ary QUIT:ary=""IF ary="?" {DO InfoGOTO Start}Info FOR loop=1:1:5 { WRITE !,$TEXT(Info+loop) };; This routine outputs the entire contents of a global array.;; Specifically, it asks you to supply the name of the array;; and then writes out the current values for all existing;; nodes that contain data. It ignores any nodes;; that do not contain data.QUITThis example shows the $TEXT(+offset) form, which returns the line found at the specifiedoffset within the current routine. This form is similar to the previous form except that no labelis used. If the offset is 0, $TEXT returns the name of the current routine as filed on disk.Note that the routine name may be different from the line label in the file. Like the previousform, this form can be used in a FOR loop to access multiline text:<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 305


<strong>Caché</strong> <strong>ObjectScript</strong> Functions;; This routine outputs the entire contents of a global array.;; Specifically, it asks you to supply the name of the array;; and then writes out the current values for all existing;; nodes that contain data. It ignores any nodes;; that do not contain data.StartREAD !,"Array name: ",ary QUIT:ary=""IF ary="?" { GOTO Start }FOR i=1:1:5 {WRITE !,$TEXT(+i) }NotesArgument IndirectionIndirection of the entire $TEXT argument is a convenient way to make an indirect referenceto both the line and the routine. For example, if the variable ENTRYREF contains both a linelabel and a routine name, you can reference the variable:$TEXT(@ENTRYREF)rather than referencing the line and the routine separately:$TEXT(@$PIECE(ENTRYREF,"^",1)^@$PIECE(ENTRYREF,"^",2))Edit PointerIf you specify a routine in $TEXT other than the current routine, <strong>Caché</strong> resets the edit pointer(current line location) to +0. This can affect execution of the ZINSERT command. You canuse $ZNAME to determine the current routine.See Also• Indirection in Using <strong>Caché</strong> <strong>ObjectScript</strong>306 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$TRANSLATE$TRANSLATEPerforms character-for-character replacement within a string.$TRANSLATE(string,identifier,associator)$TR(string,identifier,associator)ParametersstringidentifierassociatorThe target string. It can be a numeric value, a string literal, the nameof a variable, or any valid <strong>Caché</strong> <strong>ObjectScript</strong> expression.The character(s) to search for in string. It can be a numeric value,a string literal, the name of a variable, or any valid <strong>Caché</strong><strong>ObjectScript</strong> expression.Optional — The replacement character(s) corresponding to eachcharacter in the identifier. It can be a numeric value, a string literal,the name of a variable, or any valid <strong>Caché</strong> <strong>ObjectScript</strong> expression.DescriptionThe $TRANSLATE function performs character-for-character replacement within a string.It processes the string parameter one character at a time. Initially, $TRANSLATE sets theoutput string to the input string. It compares each character in the input string with eachcharacter in the identifier parameter. If $TRANSLATE finds a match, it makes note of theposition of that character.• The two-argument form of $TRANSLATE removes those characters in the identifierparameter from the output string.• The three-argument form of $TRANSLATE replaces the identifier character(s) foundin the string with the positionally corresponding character(s) from the associatorparameter. Replacement is performed on a character, not a string, basis. If the identifierparameter contains fewer characters than the associator parameter, the excess character(s)in the associator parameter are ignored. If the identifier parameter contains more charactersthan the associator parameter, the excess character(s) in the identifier parameter aredeleted in the output string.$TRANSLATE by itself does not change the string parameter. To change the input string,you must SET it equal to a translation of itself.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 307


<strong>Caché</strong> <strong>ObjectScript</strong> FunctionsExamplesIn this example, the second SET command uses $TRANSLATE to remove the commas andproduce a valid number, 1462543.SET x="1,462,543"WRITE !,"before translation ",xSET x=$TRANSLATE(x,",")WRITE !,"after translation ",xThis example shows use of the three-argument $TRANSLATE and nested $TRANSLATEfunctions. The outermost $TRANSLATE function returns the string "06/23/93". The original"1" is replaced by "9" and the original occurrences of "9" are deleted. The hyphens are replacedby slashes.SET x="06-23-1993"WRITE !,"before translation ",xSET x=$TRANSLATE($TRANSLATE(x,"199","9"),"-","/")WRITE !,"after translation ",xIf a character appears multiple times in the identifier, the first (leftmost) occurrence of thecharacter is used to position the replacement. As a result, you cannot use $TRANSLATE toremove multiple occurrences of a character from a string. For example, if the innermost$TRANSLATE in the previous example were specified as:SET x = $TRANSLATE(x,"1993","93")It would result in the undesirable value "06/2/933". In the original string ("06-23-1993"), the"1" is replaced by "9" and each occurrence of "9" is replaced by "3". The original occurrencesof "3" are removed since "3" is an excess character in identifier. This is a case of attemptingto use $TRANSLATE to perform string, rather than character replacement.See Also• $EXTRACT function• $PIECE function• $REVERSE function• $ZCONVERT function308 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$VIEW$VIEWReturns the contents of memory locations.$VIEW(offset,mode,length)$V(offset,mode,length)ParametersoffsetmodelengthAn offset, in bytes, from a base address within the memory region specifiedby mode. Interpretation is mode-dependent (see below.)Optional — The memory region whose base address will be used to locatethe data. Default is -1.Optional — The length of the data to be returned in <strong>Caché</strong>. Default is 1.Description$VIEW returns the contents of memory locations.The view buffer is a special memory area used to store blocks of data read from the <strong>Caché</strong>database (CACHE.DAT) with the VIEW command. After reading a block into the view buffer,you can use the $VIEW function with the special 0 mode to examine the contents of the viewbuffer.The $VIEW function is usually used when debugging and repairing <strong>Caché</strong> databases andsystem information.ParametersoffsetThe value of this argument depends upon the mode argument, as follows:• When mode is 0, -1, or -2, specify a positive integer as the offset from the base address,in bytes, counting from 0.• When mode is -3, or a positive integer, specify -1, which represents the base address inthe virtual address space for the process. (Offset is not meaningful in a virtual addressspace.)• When mode is -5, specify a positive integer that specifies the number of global nodes inthe current block. In this case, odd values return full global references and even valuesreturn pointers or data.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 309


<strong>Caché</strong> <strong>ObjectScript</strong> FunctionsmodeThe possible values for mode are shown in the following table. If mode is omitted, the defaultis -1. Note that some values are implementation specific. Implementation restrictions arenoted in the table.Mode0-1-2-3-5-6-7nMemory Management RegionThe view bufferThe process's partition (default)The system tableThe virtual address space for the currentprocess.Global reference and dataReserved for <strong>InterSystems</strong>' useUsed only by the integrity checking utilityWhen n is a positive number, the virtualaddress space for the running process n,where n is the pid (value of the $JOB specialvariable) for that process. Treats offset andlength the same as mode -3.Base AddressBeginning of view bufferBeginning of partitionBeginning of system table0Special. See “Using Mode -5,”later in the Notes section.Special.0The following example shows two equivalent $VIEW statements, the first of which takesthe mode and length argument defaults:OPEN 63WRITE !,$VIEW(0)WRITE !,$VIEW(0,-1,1)CLOSE 63length• When mode is 0, -1, or -2, specify a negative integer from -1 to -8192 to return that lengthof data as a string. $VIEW returns the specified number of characters (from 1 to 8192)starting at the address indicated by offset. To return the decimal value of the data, specifya positive integer from 1 to 4. $VIEW returns from one to four contiguous bytes startingat the address indicated by offset. You can also use the letter C to indicate a four-byteaddress or the letter P to indicate a four-byte word address. Specify both the P or C andthe positive integer in double quotes. To return a byte value in reverse order (low-orderbyte at lowest address) append the letter O to the length number and enclose both in310 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


double quotes. If the length parameter is omitted for modes 0, -1, and -2, the default is1.• When mode is -3, or a positive integer, the full length of the data is returned, regardlessof the length parameter. Specify a length of 1 to return the decimal value of the data.Specify a negative integer (-1) to to return the data as a string. If the length parameter isomitted, the default is 1.• When mode is -5, do not specify a length parameter.NotesProcess Virtual Address SpaceUse mode -3 to return the value from the current process' virtual address space, as shown inthis example:WRITE $VIEW(-1,-3,1)To return the virtual address space of a specified process, provide the Process ID (pid) forthat process — rather than -3 — for the second argument, as shown in this example:SET pid=$PIECE($IO,"|",4)WRITE $VIEW(-1,pid,1)The value returned is in the following format:pid^mode^dev^mem^dir^rou^stat^prio^uic^loc^blk^^^defns^lic^jbstat$VIEWThe fields are defined as follows: pid=the process ID. mode=* if in programmer mode, + or– if the job is part of a callin connection, omitted for daemons. dev=current open device(s),returned as a comma-separated list. The principal device is indicated by an astrisk (*) suffix.mem=memory in use in the process partition (in KBs), if the process is not a daemon.dir=default directory. rou=routine name. stat=bol,gcnt where bol is the beginning of linetoken, specifying the number of lines executed, and gcnt is the global count, specifying thetotal number of FOR loops and XECUTES performed. prio=user's current base priority.uic=(no longer used by <strong>Caché</strong> security at version 5.1 and subsequent) high,low representingthe high and low order bits of the User Identification Code (uic). loc=location, for daemonprocesses only. blk=number of 2K blocks that can be used for buddy block queues.defns=default namespace. lic=license bits. jbstat=job status, specified as high,low representingthe high and low order bits. Refer to $ZJOB special variable for details.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 311


<strong>Caché</strong> <strong>ObjectScript</strong> FunctionsUsing Mode -5If the current block in the view buffer contains part of a global, specifying -5 for mode returnsthe global references and the values contained in the block. The length parameter is not validfor a mode of -5.With a mode of -5, the offset value specifies the number of global nodes in the block, ratherthan a byte offset from the base address. Odd values return full global references and evenvalues return pointers or data.For example, to return the full global reference of the nth node in the view buffer, specifyn*2-1 for offset. To return the value of the nth node, specify n*2. To return the global referenceof the last node in the block, specify -1 for the offset value.$VIEW returns the nodes in collating sequence (that is, numeric). This is the same sequencethat the $ORDER function uses. By writing code that expects this sequence, you can quicklyperform a sequential scan through a global in the view buffer. (Several of the <strong>Caché</strong> utilitiesuse this technique.) $VIEW returns a null string ("") if the offset specifies a location beyondthe last node in the view buffer. Be sure to include a test for this value in your code.If the current block is a pointer block, the values returned are <strong>Caché</strong> block numbers, whichare pointers. If the block is a data block, the values returned are the data values associatedwith the nodes.If $VIEW issues a or error, it means that the information inthe block is neither a valid global reference nor valid data.The following example shows generalized code for examining the contents of the view buffer.The code first opens the view buffer and prompts for the number of the block to be read in.The FOR loop then cycles through all the offsets in the current block. The $VIEW functionuses a mode of -5 to return the value at each offset. The WRITE commands output theresulting offset-value pairs.When the end of the block is reached, $VIEW returns a null string (""). The IF commandtests for this value and writes out the “End of block” message. The QUIT command thenterminates the loop and control returns to the prompt so the user can read in another block.312 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$VIEWStart OPEN 63WRITE !,"Opening view buffer."READ !!,"Number of block to read in: ",block QUIT:block=""VIEW blockFOR i=1:1 {SET x=$VIEW(i,-5)IF x="" {WRITE !!,"End of block: ",blockCLOSE 63QUIT }WRITE !,"Offset = ",iWRITE !,"Value = ",x}GOTO Start+2CLOSE 63QUITFor a global block, typical output produced by this routine might appear as follows:Opening view buffer.Number of block to read in:3720Offset = 1Value = ^client(5)Offset = 2Value = John JonesOffset = 3Value = ^client(5,1)Offset = 4Value = 23 Bay Rd./Boston/MA 02049...Offset = 126Value = ^client(18,1,1)Offset = 127Value = Checking/45673/1248.00End of block: 3720Number of block to read in:Reverse Order Byte ValuesYou can return byte values in reverse order by using the codes provided with the lengthparameter. When you specify the letter O, enclosed in double quotes, in length, $VIEWreturns a byte value in reverse order.Consider the following example:USE IOFOR Z=0:0 {WRITE *-6SET NEXTBN=$VIEW(LINKA,0,"3O")QUIT:NEXTBN=0 }In the previous example, the length parameter of $VIEW is “3O” (3 and the letter O). Thisindicates a length of the next three (3) bytes in reverse order (O). Thus, $VIEW starts at aposition in memory (the view buffer—as indicated by a mode of 0) and returns the highestbyte, the second highest byte, and the third highest byte.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 313


<strong>Caché</strong> <strong>ObjectScript</strong> FunctionsSee Also• VIEW command• JOB command• $ZUTIL(49) Obtain Database Label Information function• Error Handling in Using <strong>Caché</strong> <strong>ObjectScript</strong>314 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


Math and Time FunctionsThe following are reference pages for intrinsic functions that perform math operations andtime and date operations. These functions supplement the <strong>Caché</strong> <strong>ObjectScript</strong> general functionsdescribed earlier in this document. Functions are listed in alphabetical order.Further introductory information on function syntax and conventions is provided at thebeginning of the general functions reference pages. Additional information on <strong>Caché</strong> functionscan be found in the Functions chapter of Using <strong>Caché</strong> <strong>ObjectScript</strong>.$ZABSAbsolute value function.$ZABS(n)ParametersnAny number.Description$ZABS returns the absolute value of n.ParametersnAny number. Can be specified as a value, a variable, or an expression. The expression isevaluated, and the result converted to a positive value. Multiple plus and minus signs arepermitted. Leading and trailing zeros are deleted.ExampleThe following program returns the absolute value of the number you supply.READ "Input a number: ",numSET abs=$ZABS(num)WRITE "The absolute value of ",num," is ",abs<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 315


Math and Time FunctionsSee Also• Operators in Using <strong>Caché</strong> <strong>ObjectScript</strong>$ZARCCOSInverse (arc) cosine function.$ZARCCOS(n)ParametersnA signed decimal number.Description$ZARCCOS returns the trigonometric inverse (arc) cosine of n. The result is given in radians(to 18 decimal places).ParametersnSigned decimal number ranging from 1 to -1 (inclusive). It can be specified as a value, avariable, or an expression. Numbers outside the range generate an error.The following are arc cosine values returned by $ZARCCOS:10-1returns 0returns 1.570796326794896619returns pi (3.141592653589793238)ExampleThe following example permits you to compare the arc cosine and the arc sine of a number:316 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZARCSINREAD "Input a number: ",numIF num>1 { WRITE !,"ILLEGAL VALUE: number too big" }ELSEIF num


Math and Time FunctionsExampleThe following example permits you to compare the arc sine and the arc cosine of a number:READ "Input a number: ",numIF num>1 { WRITE !,"ILLEGAL VALUE: number too big" }ELSEIF num


$ZCOS210-1returns 1.107148717794090502returns .7853981633974483098returns 0returns -.7853981633974483098ExampleThe following example permits you to calculate the arc tangent of a number:READ "Input a number: ",numWRITE !,"the arc tangent is: ",$ZARCTAN(num)QUITSee Also• $ZTAN function• $ZPI special variable$ZCOSCosine function.$ZCOS(n)ParametersnAn angle in radians ranging from Pi to 2 Pi (inclusive). Other supplied numeric valuesare converted to a value within this range.Description$ZCOS returns the trigonometric cosine of n. The result is a signed decimal number rangingfrom -1 to +1 (see note).Note:$ZCOS (like all trigonometric functions) calculates its values based on pi roundedto the number of available decimal digits. Therefore, the value returned by $ZCOS(0)is 1.000000000000000001 and $ZCOS($ZPI) is –1.000000000000000001. For thisreason you should not perform limit tests comparing these returned values to 1 and–1.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 319


Math and Time FunctionsParametersnAn angle in radians ranging from Pi to 2 Pi (inclusive). It can be specified as a value, a variable,or an expression. You can specify the value Pi by using the $ZPI special variable. You canspecify positive or negative values smaller than Pi or larger than 2 Pi; <strong>Caché</strong> resolve thesevalues to the corresponding multiple of Pi. For example, 3 Pi is equivalent to Pi, negative Piis equivalent to Pi, and zero is equivalent to 2 Pi.ExampleThe following example permits you to compute the cosine of a number:READ "Input a number: ",numIF $ZABS(num)>(2*$ZPI) { WRITE !,"number is a larger than 2 pi" }ELSE {WRITE !,"the cosine is: ",$ZCOS(num)}QUITSee Also• $ZSIN function• $ZARCCOS function• $ZPI special variable$ZCOTCotangent function.$ZCOT(n)ParametersnAn angle in radians.Description$ZCOT returns the trigonometric cotangent of n. The result is a signed decimal number.320 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


ParametersnAn angle in radians, specified as a non-zero value. It can be specified as a value, a variable,or an expression.ExamplesThe following example permits you to compute the cotangent of a number:READ "Input a number: ",numIF num=0 { WRITE !,"zero is an illegal value" }ELSE {WRITE !,"the cotangent is: ",$ZCOT(num)}QUITThe following examples return the cotangent for various angles:WRITE $ZCOT(1)returns .6420926159343307032.WRITE $ZCOT(0)generates an error.WRITE $ZCOT(-1)returns -.6420926159343307032.WRITE $ZCOT($ZPI)returns -2161489179585166997.See Also• $ZTAN function• $ZPI special variable$ZCOT<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 321


Math and Time Functions$ZCSCCosecant function.$ZCSC(n)ParametersnAn angle in radians.Description$ZCSC returns the trigonometric cosecant of n. The result is a signed decimal number.ParametersnAn angle in radians, specified as a non-zero number. It can be specified as a value, a variable,or an expression. Specifying 0 generates an error.ExampleThe following example permits you to compute the cosecant of a number:READ "Input a number: ",numIF num=0 { WRITE !,"ILLEGAL VALUE: zero not permitted" }ELSE {WRITE !,"the cosecant is: ",$ZCSC(num)QUIT}See Also• $ZSEC function• $ZCOT function• $ZPI special variable322 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZDATE$ZDATEValidates date and converts format.$ZDATE(hdate,dformat,monthlist,yearopt,startwin,endwin,mindate,maxdate,erropt)$ZD(hdate,dformat,monthlist,yearopt,startwin,endwin,mindate,maxdate,erropt)ParametershdatedformatmonthlistyearoptstartwinendwinmindatemaxdateerroptThe internal date format value representing the number of days elapsedsince December 31, 1840.Optional — Format for the returned date.Optional — A string or the name of a variable that contains the monthnames you supplied.Optional — A code that specifies whether to represent years as twoorfour-digit valuesOptional — The start of the sliding window during which dates mustbe represented with two-digit years.Optional — The end of the sliding window during which dates arerepresented with two-digit years.Optional — The lower limit of the range of valid dates.Optional — The upper limit of the range of valid dates.Optional — This parameter suppresses error codes associated withinvalid or out of range hdate values.DescriptionThe $ZDATE function converts a specified date in $HOROLOG format to one of severalalternate date formats. The value returned by $ZDATE depends on the parameters you use.Simple $ZDATE format$ZDATE(hdate), the most basic form of $ZDATE, returns the date in a printable format thatcorresponds to the specified hdate. hdate is an integer value that is the number of days elapsedsince December 31, 1840, and can range from 0 to 2980013 (12/31/1840 to 12/31/9999).By default, $ZDATE(hdate) represents years between 1900 and 1999 with two digits. Itrepresents years that fall before 1900 or after 1999 with four digits. For example:WRITE $ZDATE(21400)<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 323


Math and Time Functionswill display as 08/04/1899.WRITE $ZDATE(50000)will display as 11/23/77.WRITE $ZDATE(60000)will display as 04/10/2005.WRITE $ZDATE(0)will display as 12/31/1840.Compare $ZDATE with the special variable $HOROLOG. $HOROLOG returns the currentsystem date and time as two integers separated by a comma. The following sets the variablex to the current date using the $HOROLOG special variable:SET x=$ZDATE($HOROLOG)Customizable Date DefaultThe default date format is set in the DateFormat property of your locale. This is the dateformat returned when dformat is omitted or set to –1. You can change the default for yourlocale by using NLS (National Language Support) functions.In the following example, the first $ZDATE returns a date in default format for the locale;in most cases this will be dformat=1 or the American date format with a slash date separator(MM/DD/[YY]YY). The first NLS function changes the locale default to dformat=4, or theEuropean date format (DD/MM/[YY]YY), as is shown by the second $ZDATE. The secondNLS function changes the locale default for the date separator character (which affects thedformat –1, 1, and 4). In this example, the date separator character is set to a dot (“.”):WRITE !,$ZDATE($HOROLOG)SET x=$$SetDCFormat^%NLS("DateFormat",4)WRITE !,$ZDATE($HOROLOG)SET y=$$SetDCFormat^%NLS("DateSeparator",".")WRITE !,$ZDATE($HOROLOG)Customizable Date Format$ZDATE(hdate,dformat,monthlist,yearopt,startwin,endwin,mindate,maxdate,erropt) returnsthe date in the form specified by dformat and by any of the other parameters you specify.324 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


ParametershdateThe internal date format value representing the number of days elapsed since December 31,1840. It must be an integer in the range 0 through 2980013. You can specify it as a numericvalue, the name of a variable, or an expression.dformatFormat for the returned date. Valid values are:$ZDATEValue-10123456789101112MeaningGet effective dformat value from the DateFormat property of the current locale,which defaults to a value of 1. This is the default behavior if you do not specifydformat.DD Mmm [YY]YY (01 Jul 97 or 27 Mar 2002)MM/DD/[YY]YY (07/01/97 or 03/27/2002)DD Mmm [ YY ]YY (01 Jul 97 or 27 Mar 2002)YYYY-MM-DD (1997-07-01 or 2002-03-27) - ODBC formatDD/MM/[YY]YY (01/07/97 or 27/03/2002) - European formatMmm D, YYYY (Jul 1, 1997 or Mar 27, 2002)Mmm D YYYY (Jul 1 1997 or Mar 27 2002)Mmm DD [YY]YY (Jul 01 97 or Mar 27 2002)YYYYMMDD (19970701 or 20020327) - Numeric formatMmmmm D, YYYY (July 1, 1997 or March 27, 2002)W (2) [2nd day of the week]Www (Tue)Wwwwww (Tuesday)where:SyntaxYYYYMMMeaningYYYY is a four-digit year. [YY]YY is a two-digit year if hdate falls within theactive window for two-digit years; otherwise it is a four-digit year.Two-digit month.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 325


Math and Time FunctionsSyntaxDDDMmmMmmmmWWwwWwwwwwMeaningOne-digit day if the day number


$ZDATE“Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec”except when dformat is 9, in which case $ZDATE uses the list of Month full names definedthe MonthName property of the current locale, which by default is:“January February March ... November December”yearoptWith dformat values 0, 1, 2, 4, or 7, a numeric code that specifies the time window in whichto display the year as a two-digit value. Valid values are:Value-10123456MeaningGet effective yearopt value from YearOption property of current locale whichdefaults to a value of 0. This is the default behavior if you do not specifyyearopt.Represent 20th century dates (1900 through 1999) with two-digit years andall other dates with four-digit years, unless a process-specific sliding window(established via the %DATE utility) is in effect. If such a window is in effect,represent only those dates falling within the sliding window by two-digit years,and all other dates with four-digit years.Represent 20th century dates with two-digit years and all other dates withfour-digit years.Represent all dates with two-digit years.Represent with two-digit years those dates falling within the sliding temporalwindow defined by startwin and (optionally) endwin. Represent all other dateswith four-digit years.When yearopt =3, startwin and endwin are absolute datesin $HOROLOG format.Represent all dates with four-digit years.Represent with two-digit years all dates falling within the sliding temporalwindow defined by startwin and (optionally) endwin. Represent all other dateswith four-digit years. When yearopt=5, startwin and endwin are relative years.Represent all dates in the current century with two-digit years and all otherdates with four-digit years.startwinA numeric value that specifies the start of the sliding window during which dates must berepresented with two-digit years. See parameter section. You must supply startwin whenyearopt is 3 or 5. startwin is not valid with any other yearopt values.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 327


Math and Time FunctionsWhen yearopt = 3, startwin is an absolute date in $HOROLOG date format that indicatesthe start date of the sliding window.When yearopt = 5, startwin is a numeric value that indicates the start year of the slidingwindow expressed as the number of years before the current year. The sliding window alwaysbegins on January 1st of the year specified in startwin.endwinA numeric value that specifies the end of the sliding window during which dates are representedwith two-digit years. You may optionally supply endwin when yearopt is 3 or 5. endwinis not valid with any other yearopt values.When yearopt = 3, endwin is an absolute date in $HOROLOG date format that indicates theend date of the sliding window.When yearopt = 5, endwin is a numeric value that indicates the end year of the sliding windowexpressed as the number of years past the current year. The sliding window always ends onDecember 31st of the year specified in endwin. If endwin is not specified, it defaults toDecember 31st of the year 100 years after startwin.If endwin is omitted or specified as -1, the effective sliding window will be 100 years long.If you supply both startwin and endwin, the sliding window they specify must not have aduration of more than 100 years.mindateA numeric value that specifies the lower limit of the range of valid dates. If omitted or specifiedas -1, this limit is obtained from the DateMinimum property of the current locale, whichdefaults to zero (corresponding to December 31, 1840). If mindate is larger than the specifiedhdate, <strong>Caché</strong> generates a error.maxdateA numeric value that specifies the upper limit of the range of valid dates. If omitted or ifspecified as -1, this limit is obtained from the DateMaximum property of the current locale,which defaults to the maximum permissible value for the date portion of $HOROLOG:2980013 (corresponding to December 31, 9999). If maxdate is larger than 2980013, <strong>Caché</strong>generates an error. If maxdate is smaller than the specified hdate,<strong>Caché</strong> generates a error.328 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZDATEerroptThis parameter suppresses errors associated with invalid or out of range hdate values. Insteadof generating or errors, the functionreturns erropt.ExamplesThe first example shows the $HOROLOG internal format:WRITE $HOROLOGreturns a value such as the following: 58890,42347.The following example returns this date in the default format, MM/DD/YY:WRITE $ZDATE($HOROLOG)returns 03/27/2002.The following command returns the date in a different format:WRITE $ZDATE($HOROLOG,2)returns 27 Mar 2002.Date Format ExamplesThe following examples illustrate how $ZDATE returns the various dformat formats:WRITE $ZDATE(26240,1)returns 11/04/12.WRITE $ZDATE(26240,2)returns 04 Nov 12.WRITE $ZDATE(26240,3)returns 1912-11-04.WRITE $ZDATE(26240,4)returns 04/11/12.WRITE $ZDATE(26240,5)returns Nov 4, 1912.WRITE $ZDATE(26240,6)<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 329


Math and Time Functionsreturns Nov 4 1912.WRITE $ZDATE(26240,7)returns Nov 04 12.WRITE $ZDATE(26240,8)returns 19121104.WRITE $ZDATE(26240,9)returns November 4, 1912.WRITE $ZDATE(26240,10)returns 1.WRITE $ZDATE(26240,11)returns Mon.WRITE $ZDATE(26240,12)returns Monday.Two-digit Year Sliding Window ExampleTo illustrate how to use an explicit sliding window, suppose you enter the following functioncall in 1997. The hdate of 59461 represents October 19, 2003; the dformat of 1 allows it toreturn two-digit or four-digit years, and the yearopt of 5 specifies a sliding window for fourdigityears. Because of the yearopt setting, the startwin and endwin are calculated relative tothe current year (in this case 1997) by addition and subtraction.WRITE $ZDATE(59461,1,,5,90,10)The sliding window for displaying the year as two digits extends from 1/1/1907 to 12/31/2006.Thus <strong>Caché</strong> displays the date as 10/19/03.Date Range ExampleThe following example illustrates the use of mindate and maxdate. The dates are specifiedin $HOROLOG format, and represent the date range from 1/8/1950 to 4/10/2005.WRITE $ZDATE(59451,,,,,,40000,60000)displays as 10/09/2003.WRITE !,$ZDATE(39000,,,,,,40000,60000)WRITE !,$ZDATE(62000,,,,,,40000,60000)330 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


oth of the above lines generate a error, because 10/12/1947and 10/1/2010 fall outside of the date range.NotesInvalid Values with $ZDATEYou receive a error in the following conditions:• If you specify an invalid dformat code (an integer value less than -1 or greater than 12,a zero, or a non-integer value).• If you do not specify a startwin value when yearopt is 3 or 5.You receive an error under the following conditions:• If you specify an invalid value for hdate and do not either supply an erropt value or set$ZUTIL(68,32) or $ZUTIL(69,32).• If the given month number is greater than the number of month values in monthlist.• If maxdate is less than mindate.• If endwin is less than startwin.• If startwin and endwin specify a sliding temporal window whose duration is greater than100 years.You receive a error under the following conditions:• If you specify an hdate value that is out of the range of valid dates. For standard <strong>Caché</strong>this is 0 through 298013. For ISM-compatible <strong>Caché</strong> this is 1 through 94232. See$ZUTIL(68,32) Set Date Range and Invalid Date Behavior.• If you specify an otherwise valid date which is outside the range defined by the valuesassumed for maxdate and mindate and do not supply an erropt value.Error Handling with erropt$ZDATE<strong>Caché</strong> performs standard numeric evaluation on hdate, which must evaluate to a positiveinteger; thus, 7, "7", +7, 0007, 7.0, "7 dwarves", and --7 all evaluate to the same date value:01/07/1841. By default, values greater than 2980013 or less than 0 generate a error; fractional values generate an error. Non-numericstrings (including the null string) return the initial date: 12/31/1840.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 331


Math and Time FunctionsWhen supplied, the erropt parameter suppresses errors generated due to invalid or out ofrange values of hdate. Errors generated due to invalid or out of range values of other parameterswill always generate errors whether or not erropt has been supplied.For example, an error is always generated when $ZDATE specifiesa sliding window where endwin is earlier than startwin. Similarly, an error is generated when maxdate is less than mindate.Error Handling with $ZUTIL(68,32) and $ZUTIL(69,32)The behavior of $ZDATE when given an invalid value for hdate can be set by using the$ZUTIL(68,32) and $ZUTIL(69,32) functions. $ZDATE can either issue an error, or returna null value. See $ZUTIL(68,32) Set Date Range and Invalid Date Behavior.The system-wide default behavior is configurable. Go to the System Management Portal,select System Configuration, select Advanced Settings, on the pull-down Category list select<strong>ObjectScript</strong>. View and edit the current setting of NullZDATE. The default is “false” , meaningthat $ZDATE returns an error.Using $ZDATE Instead of UtilitiesKeep the following points in mind when you need to choose between the $ZDATE functionand a date utility:• You can use the $ZDATE function in place of most existing entry points of the %DOor %D utilities.• You can invoke $ZDATE($HOROLOG,7) directly instead of calling INT ^%D. Thisprovides the current date in “Mmm DD [YY]YY” format.• $ZDATEH and $ZDATE are much faster than calling entry points of %DATE, %DIor %DO.Date Delimiter$ZDATE will use the value of the DateSeparator property of the current locale as thedelimiter between months, days, and the year when dformat=1 or 4. The delimiter in theODBC date format (dformat=3) will always be a “-” as required by the ODBC standard. Thedefault value of DateSeparator is “/” and all documentation uses this delimiter.See Also• JOB command• $ZDATEH function332 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZDATE• $ZDATETIME function• $ZDATETIMEH function• $ZTIME function• $ZUTIL(68,32) Set Date Range and Invalid Date Behavior function• $ZUTIL(69,32) Set Date Range and Invalid Date Behavior function• $HOROLOG special variable• $ZTIMESTAMP special variable• More information on locales in Customized National Language Translations<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 333


Math and Time Functions$ZDATEHValidates and converts a date.$ZDATEH(date,dformat,monthlist,yearopt,startwin,endwin,mindate,maxdate,erropt)$ZDH(date,dformat,monthlist,yearopt,startwin,endwin,mindate,maxdate,erropt)ParametersdatedformatmonthlistyearoptstartwinendwinmindatemaxdateerroptAn expression that evaluates to a date string. $ZDATEH converts thisdate string to $HOROLOG format. This can be either an explicit date(specified in various formats) or the string “T” or “t”, representing thecurrent date.The “T” or “t” string can optionally include a signed integeroffset. For example “T-7” meaning seven days prior to the currentdate.Optional — Format option for the date, specified as an integer code.Optional — A string or the name of a variable that contains the monthnames you supplied.Optional — A code that specifies whether to represent years as twoorfour-digit valuesOptional — The start of the sliding window during which dates mustbe represented with two-digit years.Optional — The end of the sliding window during which dates arerepresented with two-digit years.Optional — The lower limit of the range of valid dates.Optional — The upper limit of the range of valid dates.Optional — This parameter suppresses error messages associatedwith invalid or out of range date values.DescriptionThe $ZDATEH function validates a specified date and converts it from any of the formatssupported by the $ZDATE function to $HOROLOG format. The exact action $ZDATEHperforms depends on the parameters you use.Simple $ZDATEH Format$ZDATEH(date) converts a date in the form MM/DD/[YY]YY to the first integer in the$HOROLOG format. (The $HOROLOG format consists of two integers: the first integer334 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


is a date, the second integer is a time.) Two or four digits may be specified for years in therange 1900 to 1999. Four digits must be specified for years before 1900 or after 1999.Customizable $ZDATEH Format$ZDATEH(date,dformat,monthlist,yearopt,startwin,endwin,mindate,maxdate,erropt) convertsa date in the specified dformat to $HOROLOG format. The dformat, monthlist, yearopt,startwin, endwin, mindate, maxdate and erropt values are identical to the values used by$ZDATE. However, when you use a dformat of 5, 6, 7, 8, or 9, $ZDATEH recognizes andconverts a date in any of the external date formats defined for dformat codes 1, 2, 3, 5, 6, 7,8, and 9. (But not dformat code 4.) It also recognizes a special relative date format that consistsof a string beginning with the letter T or t (indicating “today”,) optionally followed by a plus(+) or a minus (-) sign, and an integer number of days after or before the current date.Parametersdate$ZDATEHThe date you want converted to $HOROLOG format, specified as a quoted string. This canbe an explicit date, or the implicit current date, represented by the string “T” or “t”.An explicit date must be specified in one of the formats supported by dformat. The permittedformat(s) depends on the dformat parameter. If dformat is not specified or is 1, 2, 3, or 4,only one date format is permitted. If dformat is 5, 6 , 7, 8, or 9, multiple date formats arepermitted. Note that European Date Format (dformat=4) is not one of the multiple date formatspermitted, because $ZDATEH could not differentiate between 02/03/02 (meaning February3, 2002) and the European 02/03/02 (meaning March 2, 2002). If you want European dateformat, you must explicitly specify dformat=4. If you specify a date in a non-permitted format,or a nonexistent date (such as February 31, 2002), $ZDATEH generates an error code. ($ZDATEH does check for leap year dates, permitting Feb. 29, 2004but not Feb. 29, 2003.)An implicit date is specified as a string beginning with the letter “T” or “t”, indicating thecurrent (today's) date. This string can optionally include a plus or minus sign and an integer,which specify a number of days offset from the current date. For example, “t+9” (nine daysafter the current date) or “t-12” (twelve days before the current date). Implicit dates are onlypermitted if dformat is 5, 6, 7, 8, or 9. The only permitted implicit date forms are “T” (or “t”),and “T” (or “t”) followed by a sign and integer. <strong>Caché</strong> generates an error if you specify a non-integer number, an arithmetic expression, an integer without a sign,or a sign without an integer. “T+0” and “T-0” are permitted, and return the current date.<strong>Caché</strong> generates a error if you specify an offset that wouldresult in a $HOROLOG date smaller than 0 or representing a date after the year 9999.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 335


Math and Time FunctionsdformatFormat for the date. Valid values are:Value-1123456789MeaningGet effective dformat value from the DateFormat property of the current locale,which defaults to a value of 1. This is the default behavior if you do not specifydformat.MM/DD/[YY]YY (07/01/97)DD Mmm [YY]YY (01 Jul 97)YYYY-MM-DD (1997-07-01) - ODBC formatDD/MM/[YY]YY (01/07/97) - European formatMmm D, YYYY (Jul 1, 1997)Mmm D YYYY (Jul 1 1997)Mmm DD [YY]YY (Jul 01 1997)YYYYMMDD (19970701) - Numeric formatMmmmm D, YYYY (July 1, 1997)Where:SyntaxYYYYMMDDDMmmMeaningYYYY is a four-digit year. [YY]YY is a two-digit year if the date falls withinthe active window for two-digit years; otherwise it is a four-digit years. Youmust supply the year value when using date formats (dformat) 1 through 4;these date formats do not supply a missing year value. Date formats 5through 9 assume the current year if the date you specify does not includea year.Two-digit month.One-digit day if the day number


$ZDATEHSyntaxMmmmmMeaningFull name of the month as specified by the MonthName property.The defaultvalues are: “January February March ... November December”.monthlistA string or the name of a variable that contains the month names you supplied. The namesin monthlist replace the default month values from the built-in list. You would use monthlistto specify full month names or month names or abbreviations in languages other than English.monthlist is valid only if dformat is 2, 5, 6, 7, or 9. If dformat is 1, 3, 4, or 8, $ZDATEHignores monthlist.The first character in monthlist specifies a delimiter (see the space before Jan in the defaultlist). The same delimiter must appear between each month name or abbreviation in monthlist.This delimiter appears between the month, day, and year portions of the returned date value.If you omit monthlist or specify a monthlist value of -1, $ZDATEH uses the list of monthname abbreviations defined in the MonthAbbr property of the current locale, which by defaultis:“Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec”except when dformat is 9, in which case $ZDATEH uses the list of month full names definedthe MonthName property of the current locale, which by default is:“January February March ... November December”yearoptA numeric code that specifies whether to represent years as either two-digit values or fourdigitvalues. Valid values are:Value-10MeaningGet effective yearopt value from YearOption property of current locale whichdefaults to a value of 0.This is the default behavior if you do not specify yearopt.Represent 20th century dates (1900 through 1999) with two-digit years, unlessa process-specific sliding window (established via the %DATE utility) is ineffect. If such a window is in effect, represent only those dates falling withinthe sliding window by two-digit years. Represent all dates falling outside the20th century or outside the process-specific sliding window by four-digit years.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 337


Math and Time FunctionsValue123456MeaningRepresent 20th century dates with two-digit years and all other dates withfour-digit years, regardless of any sliding temporal window in effect.Represent all dates with two-digit years, regardless of any sliding temporalwindow in effect. All dates are assumed to be in the 20th century. Becausethis option deletes two digits from four-digit years, its use results in anonreversible loss of century information. (This loss may be trivial if all datesare in the same century).Represent with two-digit years those dates falling within the sliding temporalwindow defined by startwin and (optionally) endwin. Represent all other dateswith four-digit years.When yearopt=3, startwin and endwin are absolute datesin $HOROLOG format.Represent all dates with four-digit years. Dates input with two- digit years arerejected as invalid.Represent with two-digit years all dates falling within the sliding temporalwindow defined by startwin and (optionally) endwin. Represent all other dateswith four-digit years. When yearopt=5, startwin and endwin are relative years.Represent all dates in the current century with two-digit years and all otherdates with four-digit years.startwinA numeric value that specifies the start of the sliding window during which dates must berepresented with two-digit years. You must supply startwin when you use a yearopt of 3 or5.startwin is not valid with any other yearopt values.When yearopt=3, startwin is an absolute date in $HOROLOG date format that indicates thestart date of the sliding window.When yearopt= 5, startwin is a numeric value that indicates the start year of the sliding windowexpressed in the number of years before the current year. The sliding window always beginson the first day of the year (January 1) specified in startwin.endwinA numeric value that specifies the end of the sliding window during which dates are representedwith two-digit years. You may optionally supply endwin when yearopt is 3 or 5. endwinis not valid with any other yearopt values.When yearopt=3, endwin is an absolute date in $HOROLOG date format that indicates theend date of the sliding window.338 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


When yearopt=5, endwin is a numeric value that indicates the end year of the sliding windowexpressed as the number of years past the current year. The sliding window always ends onthe last day of the year (December 31) of the year specified in endwin or of the implied endyear (if you omit endwin).If endwin is omitted or specified as -1, the effective sliding window will be 100 years long.If you supply both startwin and endwin, the sliding window they specify must not have aduration of more than 100 years.mindateA numeric value that specifies the lower limit of the range of valid dates. If omitted or specifiedas -1, this limit is obtained from the DateMinimum property of the current locale, whichdefaults to zero (corresponding to December 31, 1840).maxdateA numeric value that specifies the upper limit of the range of valid dates. If omitted or ifspecified as -1, this limit is obtained from the DateMaximum property of the current locale,which defaults to the maximum permissible value for the date portion of $HOROLOG:2980013 (corresponding to December 31, 9999). Attempting to exceed maxdate generates a error message.erroptThis parameter suppresses error messages associated with invalid or out of range date values.Instead of generating or error messages,the function returns erropt.ExamplesThe following example returns the $HOROLOG date for June 12, 1983:WRITE $ZDATEH("06/12/83")returns 52027.The following example returns the $HOROLOG date for June 12, 1902 (which may nothave been your intent):WRITE $ZDATEH("06/12/02")returns 22442.$ZDATEH<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 339


Math and Time FunctionsNote:Two-digit years, by default, are considered 20th Century dates; for 21st Centurydates, specify a four-digit year, or change the two-digit sliding window by specifyingthe yearopt, startwin and endwin parameters. This sliding window can also be setfor your locale.The following example shows how the dformat parameter is used to permit multiple dateentry formats:WRITE !,$ZDATEH("November 2, 1954",5)WRITE !,$ZDATEH("Nov 2, 1954",5)WRITE !,$ZDATEH("Nov. 2 1954",5)WRITE !,$ZDATEH("11/2/1954",5)WRITE !,$ZDATEH("11.02.54",5)WRITE !,$ZDATEH("11 02 1954",5)all return 41578.In the following examples, suppose the current date is November 25, 2002:WRITE $HOROLOGreturns 59133,37854, the first integer of which is the current date.The next example uses the “T” date to return today's date (here, Nov. 25, 2002):WRITE $ZDATEH("T",5)returns 59133.WRITE $ZDATEH("T+7",5)returns 59140.The final example illustrates that when no year is specified, $ZDATEH assumes the currentyear (in this case, 2002):WRITE $ZDATEH("25 Nov",5)returns 59133.NotesLeading ZerosAny numeric date value (or integer date offset) may include any number of leading zeros, oromit all leading zeros.Invalid Values with $ZDATEHYou receive a error in the following conditions:340 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


• If you specify an invalid dformat code (an integer less than -1 or greater than 9, a zero,or a non-integer value)• If you specify an invalid yearopt code (an integer less than -1 or greater than 6, a valueof zero, or a non-integer value)• If you do not specify a startwin value when yearopt is 3 or 5You receive a error under the following conditions:• If you specify an invalid value for a date and do not supply an erropt value• If the given month number is greater than the number of month values in monthlist• If maxdate is less than mindate• If endwin is less than startwin• If startwin and endwin specify a sliding temporal window whose duration is greater than100 yearsYou receive a error under the following conditions:• If you specify a date (or an offset to “T”) which is earlier than Dec. 31, 1840 or later thanDec. 31, 9999, and do not supply an erropt value• If you specify an otherwise valid date (or offset to “T”) which is outside the range definedby the values assumed for maxdate and mindate and do not supply an erropt valueError Handling with erroptWhen supplied, the erropt parameter only suppresses error messages generated due to invalidor out of range values of date. Errors generated due to invalid or out of range values of otherparameters will always generate error messages whether or not erropt has been supplied.For example, an error is always generated when $ZDATEH specifiesa sliding window where endwin is earlier than startwin. Similarly, an error is generated when maxdate is less than mindate.Acceptable Date Values with Date Formats 5 through 9The $ZDATEH date formats (dformat) 5 through 9 accept any date value that is unambiguous.Date formats 5 through 9 assume the current year if the date you specify does not include ayear. When you pass a dformat of 5, 6, 7, 8, or 9 to $ZDATEH, it accepts any of the followingformats:• Mmm D$ZDATEH<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 341


Math and Time Functions• Mmm D, YY• Mmm D, YYYY• Mmm D YY• Mmm D YYYY• Mmm DD• Mmm DD YY• Mmm DD YYYY• YYYYMMDD• YYMMDD• YYYY-MM-DD• YYYY Mmm DD• MM/DD• MM/DD/YY• MM/DD/YYYY• MM-DD• MM-DD-YY• MM-DD-YYYY• DD Mmm• DD Mmm YY• DD Mmm YYYY• DD-Mmm• DD-Mmm-YY• DD-Mmm-YYYYMMDD is not an implemented format.Using $ZDATEH Instead of UtilitiesKeep the following points in mind when you need to choose between the $ZDATEH functionand a date utility:342 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


• You can use the $ZDATEH function in place of the existing entry points of the %DATEand %DI utility.• $ZDATEH and $ZDATE are much faster than calling entry points of %DATE, %DIor %DO.Date Delimiter$ZDATEH will use the value of the DateSeparator property of the current locale as thedelimiter between months, days, and the year when dformat=1 or 4. The delimiter in theODBC date format (dformat=3) will always be a “-” as required by the ODBC standard. Thedefault value of DateSeparator is “/” and all documentation uses this delimiter.See Also• JOB command• $ZDATE function• $ZDATETIME function• $ZDATETIMEH function• $ZTIME function• $HOROLOG special variable• $ZTIMESTAMP special variable• More information on locales in Customized National Language Translations$ZDATEH<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 343


Math and Time Functions$ZDATETIMEValidates date and time and converts to display format.$ZDATETIME(hdatetime,dformat,tformat,precision,monthlist,yearopt,startwin,endwin,mindate,maxdate,erropt)$ZDT(hdatetime,dformat,tformat,precision,monthlist,yearopt,startwin,endwin,mindate,maxdate,erropt)ParametershdatetimedformattformatprecisionmonthlistyearoptstartwinendwinmindatemaxdateerroptThe date and time value, specified in internal date and time format.Optional — The format for the returned date value.Optional — The format for the returned time value.Optional — The number of decimal places of precision (fractionalseconds) for the returned time value.Optional — A string containing a list of month names (or month nameabbreviations). This string must begin with a delimiter character, andits 12 entries must be separated by this delimiter character.Optional — A numeric code that specifies the time window in whichto display the year as a two-digit value.Optional — The start of the sliding window during which dates arerepresented with two-digit years.Optional — The end of the sliding window during which dates arerepresented with two-digit years.Optional — A numeric value that specifies the lower limit of the rangeof valid dates. If omitted or specified as -1, this limit is obtained fromthe DateMinimum property of the current locale, which defaults to zero(corresponding to December 31, 1840).Optional — The upper limit of the range of valid dates.Optional — This parameter suppresses error messages associatedwith invalid or out of range hdatetime values.Description$ZDATETIME validates a specified date and time and converts them from $HOROLOGor $ZTIMESTAMP internal format to one of several alternative date and time display formats.The exact value returned depends on the parameters you specify.344 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


• $ZDATETIME(hdatetime) returns the date and time in the default display format forthe current locale.• $ZDATETIME(hdatetime,dformat,tformat,precision,monthlist,yearopt,startwin,endwin,mindate,maxdate,erropt)returns the date and time in the display format specified by dformat and tformat, furtherdefined by the other parameters you specify. The range of valid dates may be restrictedby the mindate and maxdate parameters.ParametershdatetimeThe date and time, specified as an internal format value. <strong>Caché</strong> internal format representsdates as a count of days from an arbitrary starting point (Dec. 31, 1840), and represents timesas a count of seconds in the current day. The hdatetime value must be a string in one of thefollowing formats:• $HOROLOG: two unsigned integers separated by comma. The first is an integer specifyingthe date (in days), the second is an integer specifying the time (in seconds).• $ZTIMESTAMP: two unsigned numbers separated by comma: the first is an integerspecifying the date (in days), the second is a number specifying the time (in seconds andfractions of a second). The time value can have up to nine digits of precision (fractionalseconds) to the right of the decimal point.You can specify hdatetime as a string value, a variable, or an expression.dformatFormat for the returned date. Valid values are:$ZDATETIMEValue-112345MeaningGet effective dformat value from the DateFormat property of the current locale,which defaults to a value of 1. This is the default behavior if you do not specifydformat.MM/DD/[YY]YY (01/01/97) - The default formatDD Mmm [YY]YY (01 Jul 97)YYYY-MM-DD (1997-07-01) - ODBC formatDD/MM/[YY]YY (01/07/97) - European formatMmm D, YYYY (Jul 1, 1997)<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 345


Math and Time FunctionsValue6789101112MeaningMmm D YYYY (Jul 1 1997)Mmm DD [YY]YY (Jul 01 1997)YYYYMMDD (19970701) - Numeric formatMmmmm D, YYYY (July 1, 1997)W (2) [2nd day of the week]Www (Tue)Wwwwww (Tuesday)Where:SyntaxYYYYMMDDDMmmMmmmmWWwwWwwwwwMeaningYYYY is a four-digit year. [YY]YY is a two-digit year if hdatetime falls withinthe active window for two-digit years; otherwise it is a four-digit year.Two-digit month.One-digit day if the day number


$ZDATETIMEtformatA numeric value that specifies the format in which you want to express the time value. Supportedvalues are:Value-112345678MeaningGet the effective tformat value from the TimeFormat property of the currentlocale, which defaults to a value of 1. This is the default behavior if you do notspecify tformat.Express time in the form "hh:mm:ss" (24-hour clock)Express time in the form “hh:mm” (24-hour clock)Express time in the form “hh:mm:ss[AM/PM]” (12-hour clock)Express time in the form “hh:mm[AM/PM]” (12-hour clock)Express time in the form "hh:mm:ss+/-hh:mm" (24-hour clock). The time isexpressed as local time. The plus (+) or minus (–) suffix shows the offset oflocal time from Coordinated Universal Time (UTC), also known as GreenwichMean Time (GMT). A minus sign (-hh:mm) indicates that the local time isearlier (westward) from Greenwich by the returned offset number of hoursand minutes. A plus sign (+hh:mm) indicates that the local time is later(eastward) from Greenwich by the returned offset number of hours andminutes.Express time in the form “hh:mm+/-hh:mm” (24-hour clock). The time isexpressed as local time. The plus (+) or minus (–) suffix shows the offset oflocal time from Coordinated Universal Time (UTC), also known as GreenwichMean Time (GMT). A minus sign (-hh:mm) indicates that the local time isearlier (westward) from Greenwich by the returned offset number of hoursand minutes. A plus sign (+hh:mm) indicates that the local time is later(eastward) from Greenwich by the returned offset number of hours andminutes.Express time in the form "hh:mm:ssZ" (24-hour clock).The “Z” suffix indicatesthat the time is expressed as Coordinated Universal Time (UTC), also knownas Greenwich Mean Time (GMT), rather than as local time.Express time in the form “hh:mmZ” (24-hour clock). The “Z” suffix indicatesthat the time is expressed as Coordinated Universal Time (UTC), also knownas Greenwich Mean Time (GMT), rather than as local time.For tformat values 1 through 4 (which return local time), the date is separated from the timeby a space. For tformat values 5 through 8 (which return UTC time information), the date isseparated from the time by the letter “T”.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 347


Math and Time FunctionsWhen tformat is set to 5 or 6, the hdatetime input value is assumed to be local time, and isdisplayed as local time. The offset from UTC is taken from the local timezone setting.When tformat is set to 7 or 8, the hdatetime input value is assumed to be local date and time.The time is changed to correspond to UTC time (calculated using the local timezone setting).The date returned may also be changed (if necessary) to correspond to this UTC time value.Thus the returned date may differ from the local date.Note:$ZDATETIME has no way to determine if an hdatetime input value is in UTC timeor local time. Therefore, do not use tformat values 5, 6, 7, or 8 with an hdatetimethat is already in UTC, such as a $ZTIMESTAMP value. If you use the output froma tformat 7 or 8 conversion in an operation that converts the time back to local timebe aware that the date may have been changed in the local-to-UTC conversion.precisionA numeric value that specifies the number of decimal places of precision in which you wantto express the time. That is, if you enter a value of 3 as precision, $ZDATETIME displaysthe seconds carried out to three decimal places. If you enter a value of 9 as precision,$ZDATETIME displays the seconds carried out to nine decimal places.Supported values are as follows:-1: Get the precision value from the TimePrecision property of the current locale, whichdefaults to a value of 0. This is the default behavior if you do not specify precision.A value of n that is greater than or equal to zero (0) results in the expression of time to ndecimal places.Precision is only applicable if the hdatetime format can include a fractional time value($ZTIMESTAMP format), and if the tformat option selected includes seconds. Trailingzeros are not suppressed. If the precision specified exceeds the precision available on yoursystem, the excess digits of precision are returned as trailing zeros.monthlistA string, or the name of a variable that contains a string of month names. The names inmonthlist replace the default month name values and month abbreviation values, overridingthe MonthName and MonthAbbr properties of the current locale. The most common use ofmonthlist is to specify full month names or month name abbreviations in languages otherthan the default language for your locale.monthlist is valid only if dformat is 2, 5, 6, 7, 9. If dformat is 1, 3, 4, 8, 10,11, or 12$ZDATETIME ignores monthlist.348 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZDATETIMEThe monthlist string has the following format:• The first character of the string is a delimiter character (usually a space). The samedelimiter must appear between each month name in monthlist. This delimiter appearsbetween the month, day, and year portions of the returned display date value, which iswhy a space is usually the preferred character.• The month names list should contain twelve entries, corresponding to January throughDecember. It is possible to specify more or less than twelve month names, but if there isno month name corresponding to the month in hdatetime an erroris generated.If you omit monthlist or specify a monthlist value of -1, and dformat is 2, 5, 6, or 7,$ZDATETIME uses the list of month name abbreviations defined in the MonthAbbr propertyof the current locale, which by default is: “ Jan Feb Mar Apr May Jun Jul Aug Sep Oct NovDec”.If you omit monthlist or specify a monthlist value of -1, and dformat is 9, $ZDATETIMEuses the list of month names defined in the MonthName property of the current locale, whichby default is: “ January February March April May June July August September OctoberNovember December”.yearoptWith dformat values 0, 1, 2, 4, or 7, a numeric code that specifies the time window in whichto display the year as a two-digit value. yearopt can be:Value-1012MeaningGet effective yearopt value from YearOption property of current locale whichdefaults to a value of 0.This is the default behavior if you do not specify yearopt.Represent 20th century dates (1900 through 1999) with two-digit years, unlessa process-specific sliding window (established via the %DATE utility) is ineffect. If such a window is in effect, represent only those dates falling withinthe sliding window by two-digit years. Represent all dates falling outside the20th century or outside the process-specific sliding window by four-digit years.Represent 20th century dates with two-digit years and all other dates withfour-digit years.Represent all dates with two-digit years.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 349


Math and Time FunctionsValue3456MeaningRepresent with two-digit years those dates falling within the sliding temporalwindow defined by startwin and (optionally) endwin. Represent all other dateswith four-digit years. When yearopt=3, startwin and endwin are absolute datesin $HOROLOG format.Represent all dates with four-digit years.Represent with two-digit years all dates falling within the sliding window definedby startwin and (optionally) endwin. Represent all other dates with four-digityears. When yearopt=5, startwin and endwin are relative years.Represent all dates in the current century with two-digit years and all otherdates with four-digit years.startwinA numeric value that specifies the start of the sliding window during which dates must berepresented with two-digit years. You must supply startwin when you use a yearopt of 3 or5. startwin is not valid with any other yearopt values.When yearopt=3, startwin is an absolute date in $HOROLOG date format that indicates thestart date of the sliding window.When yearopt=5, startwin is a numeric value that indicates the start year of the sliding windowexpressed in the number of years before the current year.endwinA numeric value that specifies the end of the sliding window during which dates are representedwith two-digit years. You may optionally supply endwin when yearopt is 3 or 5. endwinis not valid with any other yearopt values.When yearopt=3, endwin is an absolute date in $HOROLOG date format that indicates theend date of the sliding window.When yearopt=5, endwin is a numeric value that indicates the end year of the sliding windowexpressed as the number of years past the current year.When yearopt=5, the sliding window always begins on January 1st of the year specified instartwin and ends on December 31st of the year specified in endwin, or of the implied endyear (if you omit endwin).If endwin is omitted or specified as -1, the effective sliding window will be 100 years long.If you supply both startwin and endwin , the sliding window they specify must not have aduration of more than 100 years.350 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZDATETIMEmindateA numeric value that specifies the lower limit of the range of valid dates. If omitted or specifiedas -1, this limit is obtained from the DateMinimum property of the current locale, whichdefaults to zero (corresponding to December 31, 1840).maxdateA numeric value that specifies the upper limit of the range of valid dates. If omitted or ifspecified as -1, this limit is obtained from the DateMaximum property of the current locale,which defaults to the maximum permissible value for the date portion of $HOROLOG:2980013 (corresponding to December 31, 9999). Attempting to exceed maxdate generates a error message.erroptThis parameter suppresses error messages associated with invalid or out of range hdatetimevalues. Instead of generating or errormessages, the function returns erropt.ExamplesThe following example displays the current local date and time. It takes the default date andtime format for the locale:WRITE $ZDATETIME($HOROLOG)The following example displays the current date and time. $ZTIMESTAMP contains thecurrent date and time value as Coordinated Universal Time (UTC) date and time. The dformatparameter specifies ODBC date format, the tformat parameter specifies a 24-hour clock, andthe precision parameter specifies 6 digits of fractional second precision:WRITE $ZDATETIME($ZTIMESTAMP,3,1,6)returns the current timestamp date and time, formatted like: 2005-11-25 18:45:16.960000.The following example shows how a local time can be converted to UTC time, and how thedate may also change as a result of this conversion. In most time zones, the time conversionin one of the following $ZDATETIME operations also changes the date:SET local = $ZDATETIME("60219,82824",3,1)SET utcwest = $ZDATETIME("60219,82824",3,7)SET utceast = $ZDATETIME("60219,00024",3,7)WRITE !,local,!,utcwest,!,utceast<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 351


Math and Time FunctionsNotesInvalid Values with $ZDATETIMEYou receive a error in the following conditions:• If you specify an invalid dformat code (an integer value less than -1 or greater than 12,a zero, or a non-integer value)• If you specify a invalid value for tformat (an integer value less than -1 or greater than 8,a zero, or a non-integer value)• If you do not specify a startwin value when yearopt is 3 or 5You receive a error under the following conditions:• If you specify an invalid value for a date or time and do not supply an erropt value• If the given month number is greater than the number of month values in monthlist• If maxdate is less than mindate• If endwin is less than startwin• If startwin and endwin specify a sliding temporal window whose duration is greater than100 yearsYou receive a error under the following conditions:• If you specify an otherwise valid date which is outside the range defined by the valuesassumed for maxdate and mindate and do not supply an erropt valueError Handling with erroptWhen supplied, the erropt parameter only suppresses error messages generated due to invalidor out of range values of hdatetime. Errors generated due to invalid or out of range values ofother parameters will always generate error messages whether or not erropt has been supplied.For example, an error is always generated when $ZDATETIMEspecifies a sliding window where endwin is earlier than startwin. Similarly, an error is generated when maxdate is less than mindate.Date Delimiter$ZDATETIME will use the value of the DateSeparator property of the current locale as thedelimiter between months, days, and the year when dformat=1 or 4. The delimiter in the352 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


ODBC date format (dformat=3) will always be a “-” as required by the ODBC standard. Thedefault value of DateSeparator is “/” and all documentation uses this delimiter.Decimal Delimiter$ZDATETIME will use the value of the DecimalSeparator property of the current locale asthe delimiter between the whole and fractional parts of numbers. The delimiter in the ODBCdate format (dformat=3) will always be a “.” as required by the ODBC standard. The defaultvalue of DecimalSeparator is “.” and all documentation uses this delimiter.Time DelimiterBy default, <strong>Caché</strong> uses the value of the TimeSeparator property of the current locale todetermine the delimiter character for the time string. By default, the delimiter is “:” and thisdelimiter has been used in all of our examples.Time SuffixesBy default, <strong>Caché</strong> uses properties in the current locale to determine the names of its timesuffixes. For $ZDATETIME, these properties (and their corresponding default values) are:• AM (“AM”)• PM (“PM”)This documentation will always use these default values for these properties.Customizable Date and Time Defaults$ZDATETIMEThe default date format is set in the DateFormat property of your locale. This is the dateformat returned when dformat is omitted or set to –1. The default date separator and decimalseparator characters are also defined for your locale. You can change these defaults for yourlocale by using NLS (National Language Support) functions.In the following example, the first $ZDATETIME returns a date and time in the defaultformat for the locale. The input parameters are the $ZTIMESTAMP special variable, withthe dformat and tformat taking defaults, and precision set to 2 decimal digits. In most locales,the first $ZDATETIME will return dformat=1 or the American date and time format witha slash date separator and a dot decimal separator for fractional seconds.The first NLS function changes the locale date format default to dformat=4, or the Europeandate format (DD/MM/[YY]YY), as is shown by the second $ZDATETIME. The secondNLS function changes the locale default for the date separator character (which affects thedformat –1, 1, and 4). In this example, the date separator character is set to a dot (“.”), as<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 353


Math and Time Functionsshown by the third $ZDATETIME. The final NLS function changes the decimal separatorcharacter for this locale to the European standard (“,”), as shown by the final $ZDATETIME:WRITE !,$ZDATETIME($ZTIMESTAMP,,,2)SET x=$$SetDCFormat^%NLS("DateFormat",4)WRITE !,$ZDATETIME($ZTIMESTAMP,,,2)SET y=$$SetDCFormat^%NLS("DateSeparator",".")WRITE !,$ZDATETIME($ZTIMESTAMP,,,2)SET z=$$SetDCFormat^%NLS("DecimalSeparator",",")WRITE !,$ZDATETIME($ZTIMESTAMP,,,2)$ZDATETIME Compared to $ZDATE$ZDATETIME is similar to $ZDATE except it converts a combined date and time value.$ZDATE only converts a date value. For example:WRITE $ZDATE($HOROLOG)returns the current date, formatted like: 11/25/2002.WRITE $ZDATETIME($HOROLOG)returns the current date and time, formatted like: 11/25/2002 13:53:57.$ZDATE does not support tformat values 5 through 8.See Also• JOB command• $ZDATE function• $ZDATEH function• $ZDATETIMEH function• $ZTIME function• $HOROLOG special variable• $ZTIMESTAMP special variable• More information on locales in Customized National Language Translations354 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZDATETIMEH$ZDATETIMEHValidates date and time and converts to internal format.$ZDATETIMEH(datetime,dformat,tformat,monthlist,yearopt,startwin,endwin,mindate,maxdate,erropt)$ZDTH(datetime,dformat,tformat,monthlist,yearopt,startwin,endwin,mindate,maxdate,erropt)ParametersdatetimedformattformatmonthlistyearoptstartwinendwinmindatemaxdateerroptThe date and time value, specified in display format. This is the dateand time that you want to convert to $HOROLOG format.Optional — The date format corresponding to the date portion of thedatetime value.Optional — The time format corresponding to the time portion of thedatetime value.Optional — A string containing a list of month names (or month nameabbreviations). This string must begin with a delimiter character, andits 12 entries must be separated by this delimiter character.Optional — The time window in which to display the year as a two-digitvalue.Optional — The start of the sliding window during which dates mustbe represented with two-digit years.Optional — The end of the sliding window during which dates arerepresented with two-digit years.Optional — The lower limit of the range of valid dates.Optional — The upper limit of the range of valid dates.Optional — This parameter suppresses error messages associatedwith invalid or out of range datetime values.Description$ZDATETIMEH validates a specified date and time value and converts it from displayformat to internal format. The corresponding $ZDATETIME function converts a date andtime from internal format to display format. Internal format is the format used by the$HOROLOG or $ZTIMESTAMP. It represents a date and time value as a string of twonumeric values separated by a comma.The exact value returned depends on the parameters you use.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 355


Math and Time Functions$ZDATETIMEH(datetime) converts a date and time value in the format "MM/DD/[YY]YYhh:mm:ss[.ffff]” to $HOROLOG format.SyntaxMMDD[YY]YYhhmmssffffMeaningA two-digit month.A two-digit day.Two or four digits for years from 1900 to 1999. Four digits for years before1900 or after 1999.The hour in a 24-hour clock format.Minutes.Seconds.Fractional seconds (zero to nine digits).$ZDATETIMEH(datetime,dformat,tformat,monthlist,yearopt,startwin,endwin,mindate,maxdate,erropt)converts a date and time value that was originally specified (through $ZDATETIME) indate and time to $HOROLOG or $ZTIMESTAMP format. The dformat, tformat, yearopt,startwin and endwin values are identical to the values used by $ZDATETIME.However, when you use a dformat of 5, 6, 7, 8, or 9, $ZDATETIMEH recognizes and convertsa date in any of the external date formats corresponding to dformat codes 1, 2, 3, 5, 6, 7, 8,or 9, as well as a special relative date format that begins with T or t, optionally followed bya plus (+) or a minus (-), and the number of days after or before the current date.$ZDATETIMEH recognizes and converts a time in any of eight time formats, regardless ofwhich time format you specify in the function call. In addition, $ZDATETIMEH recognizesthe suffixes “AM, PM, NOON, and MIDNIGHT.” You can express these suffixes in uppercase,lowercase, or mixed case. You can also abbreviate these suffixes to any number of letters.The recognized forms include:• The default date format, MM/DD/[YY]YY• The format DDMmm[YY]YY• The ODBC format YYYY-MM-DD• The format DD/MM/[YY]YY• The format Mmm D, YYYY• The format Mmm D YYYY356 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZDATETIMEH• The format Mmm DD YY• The format YYYYMMDD (numeric format)Parameter ValuesdatetimeThe date and time that you want to convert to $HOROLOG format. You specify datetimeas an expression that evaluates to a single string with the date first, followed by a single blankspace, followed by the time. If you omit the time portion, $ZDATETIMEH sets the timeportion of the $HOROLOG format to zero. Valid date and time values depend on the Date-Format and TimeFormat properties of the current locale and the values specified for thedformat and tformat parameters. For details on specifying dates, refer to $ZDATEH.dformatFormat for the date. Valid values are:Value-1123456789MeaningGet effective dformat value from the DateFormat property of the current locale,which defaults to a value of 1. This is the default behavior if you do not specifydformat.MM/DD/[YY]YY (01/01/97 or 03/27/2002) - The default formatDD Mmm [YY]YY (01 Jul 97 or 27 Mar 2002)YYYY-MM-DD (1997-07-01 or 2002-03-27) - ODBC formatDD/MM/[YY]YY (01/07/97 or 27/03/2002) - European formatMmm D, YYYY (Jul 1, 1997 or Mar 27, 2002)Mmm D YYYY (Jul 1 1997 or Mar 27 2002)Mmm DD [YY]YY (Jul 01 1997 or Mar 27 2002)YYYYMMDD (19930701 or 20020327) - Numeric formatMmmmm D, YYYY (July 1, 1997 or March 27, 2002)Where:SyntaxYYYYMeaningYYYY is a four-digit year. [YY]YY is a two-digit year if datetime falls withinthe active window for two-digit dates; otherwise it is a four-digit number.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 357


Math and Time FunctionsSyntaxMMDDDMmmMmmmmMeaningTwo-digit month.One-digit day if the day number


$ZDATETIMEHValue678MeaningExpress time in the form “hh:mm+/-hh:mm” (24-hour clock). The time isexpressed as local time. The plus (+) or minus (–) suffix shows the offset oflocal time from Coordinated Universal Time (UTC), also known as GreenwichMean Time (GMT). A minus sign (-hh:mm) indicates that the local time is earlier(westward) from Greenwich by the returned offset number of hours and minutes.A plus sign (+hh:mm) indicates that the local time is later (eastward) fromGreenwich by the returned offset number of hours and minutes.Express time in the form "hh:mm:ssZ" (24-hour clock). The “Z” suffix indicatesthat the time is expressed as Coordinated Universal Time (UTC), also knownas Greenwich Mean Time (GMT), rather than as local time.Express time in the form “hh:mmZ” (24-hour clock). The “Z” suffix indicatesthat the time is expressed as Coordinated Universal Time (UTC), also knownas Greenwich Mean Time (GMT), rather than as local time.For tformat values 1 through 4 (which return local time), the date is separated from the timeby a space. For tformat values 5 through 8 (which return UTC time information), the date isseparated from the time by the letter “T”.When tformat is set to 7 or 8, the time is returned as UTC time, and the date returned is alsoadjusted (if necessary) to this UTC time value. This date may differ from the local date.monthlistA string, or the name of a variable that contains a string of month names. The names inmonthlist replace the default month name values and month abbreviation values, overridingthe MonthName and MonthAbbr properties of the current locale. The most common use ofmonthlist is to specify full month names or month name abbreviations in languages otherthan the default language for your locale.monthlist is valid only if dformat is 2, 5, 6, 7, or 9. If dformat is -1, 1, 3, 4, or8$ZDATETIMEH ignores monthlist.The monthlist string has the following format:• The first character of the string is a delimiter character (usually a space). The samedelimiter must appear between each month name in monthlist. This delimiter appearsbetween the month, day, and year portions of the returned display date value, which iswhy a space is usually the preferred character.• The month names list should contain twelve entries, corresponding to January throughDecember. It is possible to specify more or less than twelve month names, but if there is<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 359


Math and Time Functionsno month name corresponding to the month in hdatetime an erroris generated.If you omit monthlist or specify a monthlist value of -1, and dformat is 2, 5, 6, or 7,$ZDATETIMEH uses the list of month name abbreviations defined in the MonthAbbr propertyof the current locale, which by default is: “ Jan Feb Mar Apr May Jun Jul Aug Sep Oct NovDec”.If you omit monthlist or specify a monthlist value of -1, and dformat is 9, $ZDATETIMEHuses the list of month names defined in the MonthName property of the current locale, whichby default is: “ January February March April May June July August September OctoberNovember December”.yearoptWith dformat values 0, 1, 2, 4, or 7, a numeric code that specifies the time window in whichto display the year as a two-digit value. yearopt can be:Value-10123456MeaningGet effective yearopt value from YearOption property of current locale whichdefaults to 0. This is the default behavior if you do not specify yearopt .Represent 20th century dates (1900 through 1999) with two-digit years, unlessa process-specific sliding window (established via the %DATE utility) is ineffect. If such a window is in effect, represent only those dates falling withinthe sliding window by two-digit years. Represent all dates falling outside the20th century or outside the process-specific sliding window by four-digit years.Represent 20th century dates with two-digit years and all other dates withfour-digit years.Represent all dates with two-digit years.Represent with two-digit years those dates falling within the sliding temporalwindow defined by startwin and (optionally) endwin. Represent all other dateswith four-digit years.When yearopt =3, startwin and endwin are absolute datesin $HOROLOG format.Represent all dates with four-digit years.Represent with two-digit years all dates falling within the sliding window definedby startwin and (optionally) endwin. Represent all other dates with four-digityears. When yearopt=5, startwin and endwin are relative years.Represent all dates in the current century with two-digit years and all otherdates with four-digit years.360 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZDATETIMEHstartwinA numeric value that specifies the start of the sliding window during which dates must berepresented with two-digit years. You must supply startwin when you use a yearopt of 3 or5. startwin is not valid with any other yearopt values.When yearopt = 3, startwin is an absolute date in $HOROLOG date format that indicatesthe start date of the sliding window.When yearopt = 5, startwin is a numeric value that indicates the start year of the slidingwindow expressed in the number of years before the current year. The sliding window alwaysbegins on the first day of the year (January 1) specified in startwin.endwinA numeric value that specifies the end of the sliding window during which dates are representedwith two-digit years. You may optionally supply endwin when yearopt is 3 or 5. endwinis not valid with any other yearopt values.When yearopt =3, endwin is an absolute date in $HOROLOG date format that indicates theend date of the sliding window.When yearopt =5, endwin is a numeric value that indicates the end year of the sliding windowexpressed as the number of years past the current year. The sliding window always ends onDecember 31st of the year specified in endwin. If endwin is not specified, it defaults toDecember 31st of the year 100 years after startwin.If endwin is omitted or specified as -1, the effective sliding window will be 100 years long.If you supply both startwin and endwin , the sliding window they specify must not have aduration of more than 100 years.mindateA numeric value that specifies the lower limit of the range of valid dates. If omitted or specifiedas -1, this limit is obtained from the DateMinimum property of the current locale, whichdefaults to zero (corresponding to December 31, 1840).maxdateA numeric value that specifies the upper limit of the range of valid dates. If omitted or ifspecified as -1, this limit is obtained from the DateMaximum property of the current locale,which defaults to the maximum permissible value for the date portion of $HOROLOG:2980013 (corresponding to December 31, 9999). Attempting to exceed maxdate generates a error message.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 361


Math and Time FunctionserroptThis parameter suppresses error messages associated with invalid or out of range datetimevalues. Instead of generating or errormessages, the function returns erropt.Notes$ZDATETIMEH and Fractional SecondsUnlike $ZDATETIME, $ZDATETIMEH does not allow you to specify a precision for thetime. Any fractional seconds in the original $ZDATETIME-formatted time are retained inthe value $ZDATETIMEH returns.Note that $HOROLOG does not return fractional seconds.Invalid Values with $ZDATETIMEHYou receive a error in the following conditions:• If you specify an invalid dformat code (an integer value less than -1 or greater than 9, azero, or a non-integer value.)• If you specify an invalid value for tformat (an integer value less than -1 or greater than8, a zero, or a non-integer value.)• If you do not specify a startwin value when yearopt is 3 or 5.You receive a error under the following conditions:• If you specify an invalid value for a date and do not supply an erropt value.• If the given month number is greater than the number of month values in monthlist.• If maxdate is less than mindate.• If endwin is less than startwin.• If startwin and endwin specify a sliding temporal window whose duration is greater than100 years.You receive a error under the following conditions:• If you specify a date (or an offset to “T”) which is earlier than Dec. 31, 1840 or later thanDec. 31, 9999, and do not supply an erropt value.362 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


• If you specify an otherwise valid date (or an offset to “T”) which is outside the rangedefined by the values assumed for maxdate and mindate and do not supply an erroptvalue.Error Handling with erroptWhen supplied, the erropt parameter only suppresses error messages generated due to invalidor out of range values of datetime. Errors generated due to invalid or out of range values ofother parameters will always generate error messages whether or not erropt has been supplied.For example, an error is always generated when $ZDATETIMEHspecifies a sliding window where endwin is earlier than startwin. Similarly, an error is generated when maxdate is less than mindate.Date Delimiter$ZDATETIMEH uses the value of the DateSeparator property of the current locale as thedelimiter between months, days, and the year when dformat=1 or 4. The delimiter in theODBC date format (dformat=3) is always a “-” , as required by the ODBC standard. Thedefault value of DateSeparator is “/” and all <strong>Caché</strong> documentation examples use this delimiter.Time DelimiterBy default, <strong>Caché</strong> uses the value of the TimeSeparator property of the current locale todetermine the delimiter character for the time string. By default, the delimiter is “:” and thisdelimiter has been used in all of our examples. The delimiter in the ODBC date format(dformat=3) will always be a “:” as required by the ODBC standard.The delimiter for fractional seconds is a decimal point (.).Time SuffixesBy default, <strong>Caché</strong> uses properties in the current locale to determine the names of its timesuffixes. For $ZDATETIMEH, these properties (and their corresponding default values)are:• AM (“AM”)• PM (“PM”)• Midnight (“MIDNIGHT”)• Noon (“NOON”)This documentation will always use these default values for these properties.$ZDATETIMEH<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 363


Math and Time Functions$ZDATETIMEH Compared to $ZDATEH$ZDATETIMEH is similar to $ZDATEH except it converts both a date and a time valueto the internal $HOROLOG format (even if no time value is specified.) $ZDATEH onlyconverts a date value to $HOROLOG format. For example:WRITE $ZDATEH("Nov 25, 2002",5)returns 59133.WRITE $ZDATETIMEH("Nov 25, 2002 10:08:09.539",5)returns 59133,36489.539.Specifying $ZDATETIMEH with no time value:WRITE $ZDATETIMEH("Nov 25, 2002",5)returns 59133,0.See Also• JOB command• $ZDATE function• $ZDATEH function• $ZDATETIME function• $ZTIME function• $ZTIMEH function• $HOROLOG special variable• $ZTIMESTAMP special variable• %DATE utility• More information on locales in Customized National Language Translations364 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZEXP$ZEXPReturns the natural logarithm raised to the specified power.$ZEXP(n)ParametersnAny number.Description$ZEXP returns a value that is the natural logarithm (base e) raised to the power n.The corresponding natural logarithm function is $ZLN.ParametersnAny number. It can be specified as a value, a variable, or an expression.ExamplesThe following example writes the natural log raised to the power of negative and positiveintegers:FOR x=-3:1:3 {WRITE !,"The natural log raised to ",x," = ",$ZEXP(x)}QUITreturns:The natural log raised to -3 = .04978706836786394297The natural log raised to -2 = .1353352832366126919The natural log raised to -1 = .3678794411714423216The natural log raised to 0 = 1The natural log raised to 1 = 2.718281828459045236The natural log raised to 2 = 7.389056098930650228The natural log raised to 3 = 20.08553692318766774The following example writes the natural logs raised to the first nine multiples of pi:SET y=1FOR x=$ZPI:$ZPI:10*$ZPI {WRITE !,"The natural log raised to ",y,"pi = ",$ZEXP(x)SET y=y+1 }QUIT<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 365


Math and Time FunctionsWRITE $ZEXP("")returns 1.WRITE $ZEXP()generates a error.See Also• $ZLN function• $ZLOG function• $ZPI special variable$ZHEXConverts a hexadecimal string to a decimal number and vice versa.$ZHEX(num)$ZH(num)ParametersnumAn expression that evaluates to a numeric value be converted, either a quotedstring or an integer (signed or unsigned).Description$ZHEX converts a hexadecimal string to a decimal integer, or a decimal integer to a hexadecimalstring.If num is a string value, $ZHEX interprets it as the hexadecimal representation of a number,and returns that number in decimal. Be sure to place the string value within quotation marks.If num is a numeric value, $ZHEX converts it to a string representation of the number inhexadecimal format. If either the initial or the final numeric value cannot be represented asan 8-byte signed integer, $ZHEX generates a error.366 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


ParametersnumA string value or a numeric value, a variable that contains a string value or a numeric value,or an expression that evaluates to a string value or a numeric value.A string value is read as a hexadecimal number and converted to a positive decimal integer.$ZHEX recognizes both uppercase and lowercase letters “A” through “F” as hexadecimaldigits. It truncates leading zeros. It does not recognize plus and minus signs or decimal points.It stops evaluation of a string when it encounters a non-hexadecimal character. Therefore,the strings “F”, “f”, “00000F”, “F.7”, and “FRED” all evaluate to decimal 15. If the firstcharacter encountered in a string is not a hexadecimal character, $ZHEX evaluates the stringas zero. Therefore, the strings “0”, “0.9”, “+F”, “-F”, and “H” all evaluate to zero. The nullstring ("") is an invalid value and returns a error.An integer value is read as a decimal number and converted to hexadecimal. An integer canbe positive or negative. $ZHEX recognizes leading plus and minus signs. It truncates leadingzeros. It evaluates nested arithmetic operations. However, it does not recognize decimalpoints. It returns a error if it encounters a decimal point character. Therefore,the integers 217, 0000217, +217, -+-217 all evaluate to hexadecimal D9. -217, -0000217,and -+217 all evaluate to FFFFFFFFFFFFFF27 (the twos complement). Other values, suchas floating point numbers, trailing signs, and non-numeric characters result in a or error.ExamplesWRITE $ZHEX("F")returns 15.WRITE $ZHEX(15)returns F.WRITE $ZHEX("1AB8")returns 6840.WRITE $ZHEX(6840)returns 1AB8.WRITE $ZHEX("XXX")$ZHEX<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 367


Math and Time Functionsreturns 0.WRITE $ZHEX(-1)returns FFFFFFFFFFFFFFFF.WRITE $ZHEX((3+(107*2)))returns D9.NotesForcing a Hexadecimal InterpretationTo force an integer value to be interpreted as hexadecimal, concatenate any non-hexadecimalcharacter to the end of your num parameter. For example:WRITE $ZHEX(16_"H")returns 22.See Also• ZZDUMP command$ZLNReturns the natural logarithm of the specified number.$ZLN(n)ParameternAny positive non-zero number, which can be specified as a value, a variable, or anexpression.Description$ZLN returns the natural logarithm (base e) value of n.Specifying zero or a negative number generates an error.The corresponding natural logarithm power function is $ZEXP.368 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


ExamplesThe following example writes the natural log of the integers 1 through 10:$ZLNFOR x=1:1:10 {WRITE !,"The natural log of ",x," = ",$ZLN(x)}QUITreturns:The natural log of 1 = 0The natural log of 2 = .6931471805599453089The natural log of 3 = 1.098612288668109691The natural log of 4 = 1.386294361119890618The natural log of 5 = 1.609437912434100375The natural log of 6 = 1.791759469228055002The natural log of 7 = 1.945910149055313306The natural log of 8 = 2.079441541679835929The natural log of 9 = 2.197224577336219384The natural log of 10 = 2.302585092994045684The following example shows the relationship between $ZLN and $ZEXP:SET x=$ZEXP(1) ; x = 2.718281828459045236WRITE $ZLN(x)returns 1.WRITE $ZLN(0)generates an error.See Also• $ZEXP function• $ZLOG function• $ZPI special variable<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 369


Math and Time Functions$ZLOGReturns the base 10 logarithm value of the specified positive numeric expression.$ZLOG(n)ParameternAny positive, non-zero number, which can be specified as a value, a variable, oran expression.Description$ZLOG returns the base 10 logarithm value of n.Specifying zero or a negative number generates an error.The corresponding natural log (base e) function is $ZLN.ExamplesThe following example writes the base 10 logarithms of the integers 1 through 10:FOR x=1:1:10 {WRITE !,"The log of ",x," = ",$ZLOG(x)}QUITreturns:The log of 1 = 0The log of 2 = .301029995663981195The log of 3 = .477121254719662437The log of 4 = .60205999132796239The log of 5 = .698970004336018805The log of 6 = .778151250383643633The log of 7 = .845098040014256831The log of 8 = .903089986991943586The log of 9 = .954242509439324875The log of 10 = 1WRITE $ZLOG($ZPI)returns .4971498726941338541.WRITE $ZLOG(.5)returns -.301029995663981195.WRITE $ZLOG(0)370 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZPOWERgenerates an error.See Also• $ZEXP function• $ZLN function• $ZPI special variable$ZPOWERReturns the value of a number raised to the selected power.$ZPOWER(num,exponent)ParametersnumexponentThe number to be raised to a power.The exponent.Description$ZPOWER returns the value of the num parameter raised to the nth power. This functionperforms the same operation as the Binary Exponentiation operator (**). (See Operators inUsing <strong>Caché</strong> <strong>ObjectScript</strong>.)ParametersnumThe number to be raised to a power. It can be integer or floating point, negative, positive, orzero. It can be specified as a value, a variable, or an expression. If specified as a quoted string,evaluation terminates at the first non-numeric character. The null string ("") and non-numericstrings evaluate to zero.exponentThe exponent is a number that can be integer or floating point, negative, positive, or zero. Itcan be specified as a numeric or string value, a variable, or an expression. The null string ("")and non-numeric strings evaluate to zero. However, some restrictions apply:• If num is 0, exponent must be a positive, non-zero number.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 371


Math and Time Functions• If num is negative, exponent must be an integer.See Also• $ZSQR function• $ZEXP function• $ZLN function• $ZLOG function• Operators in Using <strong>Caché</strong> <strong>ObjectScript</strong>$ZSECReturns the trigonometric secant of the specified angle value.$ZSEC(n)ParametersnAngle in radians ranging from 0 to 2 Pi. It can be specified as a value, a variable,or an expression.Description$ZSEC returns the trigonometric secant of n. The result is a signed decimal number.Note:$ZSEC (like all trigonometric functions) calculates its values based on pi roundedto the number of available decimal digits. Therefore, the value returned by$ZSEC($ZPI) is –.999999999999999999 and $ZSEC(0) is .999999999999999999.For this reason you should not perform limit tests comparing these returned valuesto 1 or –1.ParametersnAn angle in radians ranging from Pi to 2 Pi (inclusive). It can be specified as a value, a variable,or an expression. You can specify the value Pi by using the $ZPI special variable. You canspecify positive or negative values smaller than Pi or larger than 2 Pi; <strong>Caché</strong> resolve these372 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


values to the corresponding multiple of Pi. For example, 3 Pi is equivalent to Pi, and negativePi is equivalent to Pi.ExampleThe following example permits you to compute the secant of a number:READ "Input a number: ",numIF $ZABS(num)>(2*$ZPI) { WRITE !,"number is a larger than 2 pi" }ELSE {WRITE !,"the secant is: ",$ZSEC(num)}QUITSee Also• $ZCSC function• $ZPI special variable$ZSIN$ZSINReturns the trigonometric sine of the specified angle value.$ZSIN(n)ParametersnAngle in radians ranging from Pi to 2 Pi (inclusive). Other supplied numeric valuesare converted to a value within this range.Description$ZSIN returns the trigonometric sine of n. The result is a signed decimal number rangingfrom 1 to -1 (see note).Note:$ZSIN (like all trigonometric functions) calculates its values based on pi roundedto the number of available decimal digits. Therefore, the value returned by$ZSIN($ZPI) is .000000000000000000462644 and $ZSIN($ZPI*2) is–.00000000000000000092529. For this reason you should not perform limit testscomparing these returned values to 0. $ZSIN(0) returns 0.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 373


Math and Time FunctionsParametersnAn angle in radians ranging from Pi to 2 Pi (inclusive). It can be specified as a value, a variable,or an expression. You can specify the value Pi by using the $ZPI special variable. You canspecify positive or negative values smaller than Pi or larger than 2 Pi; <strong>Caché</strong> resolve thesevalues to the corresponding multiple of Pi. For example, 3 Pi is equivalent to Pi, and negativePi is equivalent to Pi.ExampleThe following example permits you to compute the sine of a number:READ "Input a number: ",numIF $ZABS(num)>(2*$ZPI) { WRITE !,"number is a larger than 2 pi" }ELSE {WRITE !,"the sine is: ",$ZSIN(num)}QUITSee Also• $ZCOS function• $ZARCSIN function• $ZPI special variable$ZSQRReturns the square root of a specified number.$ZSQR(n)ParameternAny positive number, or zero. (The null string and non-numeric string values aretreated as a zero.) Can be specified as a value, a variable, or an expression.Description$ZSQR returns the square root of n. It returns the square root of 1 as 1. It returns the squareroot of 0 and the square root of a null string ("") as 0. Specifying a negative number invokes374 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


an error. You can use the absolute value function $ZABS to convertnegative numbers to positive numbers.ExamplesThe following example returns the square root of a user-supplied number.READ "Input number for square root: ",numIF num


Math and Time FunctionsNote:$ZTAN (like all trigonometric functions) calculates its values based on pi roundedto the number of available decimal digits. Therefore, the value returned by$ZTAN($ZPI) is –.000000000000000000462644 and $ZTAN(–$ZPI) is.000000000000000000462644. For this reason you should not perform limit testscomparing these returned values to 0. $ZTAN(0) is 0.ParametersnAn angle in radians ranging from 0 to 2 Pi. It can be specified as a value, a variable, or anexpression.ExampleThe following example permits you to compute the tangent of a number:READ "Input a number: ",numWRITE !,"the tangent is: ",$ZTAN(num)QUITSee Also• $ZARCTAN function• $ZSIN function• $ZPI special variable376 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZTIME$ZTIMEConverts the internal system time from the specified format to a printable format.$ZTIME(Htime,format,precision,erropt)$ZT(Htime,format,precision,erropt)ParametersHtimeformatprecisionerroptThe internal system time that can be specified as a numeric value, thename of a variable, or as an expression.Optional — A numeric value that specifies the format in which you wantto express the time value.Optional — A numeric value that specifies the number of decimal placesof precision in which you want to express the time.Optional — The expression returned if the Htime parameter isconsidered invalid.DescriptionThe $ZTIME function converts an internal system time, Htime, specified in the time formatfrom the special variable $HOROLOG or $ZTIMESTAMP, to a printable format. If nooptional parameters are used, the time will be returned in the format: “hh:mm:ss”; where“hh” is hours in a 24–hour clock, “mm” is minutes, and “ss” is seconds. Otherwise, the timewill be returned in the format specified by the value of the format and precision parameters.ParametersformatSupported values are as follows:<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 377


Math and Time FunctionsCode-11234DescriptionGet the effective format value from the TimeFormat property of the currentlocale, which defaults to a value of 1. This is the default behavior if you do notspecify format.Express time in the form "hh:mm:ss" (24-hour clock).Express time in the form “hh:mm” (24-hour clock).Express time in the form “hh:mm:ss[AM/PM]” (12-hour clock).Express time in the form “hh:mm[AM/PM]” (12-hour clock).precisionThe function displays the seconds carried out to the number of decimal places specified inthe precision parameter. For example, if you enter a value of 3 as precision, $ZTIME displaysthe seconds carried out to three decimal places. If you enter a value of 9, $ZTIME displaysthe seconds carried out to nine decimal places. Supported values are as follows:Value-1nDescriptionGets the precision value from the TimePrecision property of the current locale,which defaults to a value of 0. This is the default behavior if you do not specifyprecision.A value that is greater than or equal to 0 results in the expression of time ton decimal places.erroptThis parameter suppresses error messages associated with invalid Htime values. Instead ofgenerating error messages, the function returns the value indicated byerropt.ExamplesTo return the current local time using the special variable $HOROLOG, you must use the$PIECE function to specify the second piece of $HOROLOG. The following returns thetime in the 24–hour clock format “13:55:11”:WRITE $ZTIME($PIECE($HOROLOG,",",2),1)378 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


In the examples that follow, Htime is set to $PIECE($HOROLOG,",",2) for the currenttime. These examples show how to use the various forms of $ZTIME to return different timeformats.The following example in many cases returns time in the format "13:28:55"; however, thisformat is dependent on locale:SET Htime=$PIECE($HOROLOG,",",2)WRITE $ZTIME(Htime)The following example returns time in the format "13:28:55":SET Htime=$PIECE($HOROLOG,",",2)WRITE $ZTIME(Htime,1)The following example returns time in the format "13:28:55.999":SET Htime=$PIECE($HOROLOG,",",2)WRITE $ZTIME(Htime,1,3)The following example returns time in the format "13:28:55.999999999":SET Htime=$PIECE($HOROLOG,",",2)WRITE $ZTIME(Htime,1,9)The following example returns time in the format "13:28":SET Htime=$PIECE($HOROLOG,",",2)WRITE $ZTIME(Htime,2)The following example returns time in the format "01:28:24PM":SET Htime=$PIECE($HOROLOG,",",2)WRITE $ZTIME(Htime,3)The following example returns time in the format "01:28PM":SET Htime=$PIECE($HOROLOG,",",2)WRITE $ZTIME(Htime,4)The following example returns time in the format “13:45:56.021”, the current UTC time withthree decimal places of precision:SET t=$ZTIME($PIECE($ZTIMESTAMP,",",2),1,3)WRITE "Current UTC time is ",t$ZTIME<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 379


Math and Time FunctionsNotesInvalid Parameter Values• You receive a error if you specify an invalid format code (an integer lessthan -1 or greater than 4, a zero, or a non-integer value).• You receive an error if you specify a value for Htime outside theallowed range of 0 to 86399 (inclusive) and do not supply an erropt value.Decimal Delimiter$ZTIME will use the value of the DecimalSeparator property of the current locale as thedelimiter between the whole and fractional parts of numbers. The default value of DecimalSeparatoris “.”; all documentation examples use this delimiter.Time DelimiterBy default, <strong>Caché</strong> uses the value of the TimeSeparator property of the current locale todetermine the delimiter character for the time string. By default, the delimiter is “:”; all documentationexamples use this delimiter.Time SuffixesBy default, <strong>Caché</strong> uses properties in the current locale to determine the names of its timesuffixes. For $ZTIME, these properties (and their corresponding default values) are:• AM (“AM”)• PM (“PM”)This documentation will always use these default values for these properties.See Also• $ZDATETIME function• $ZDATETIMEH function• $ZTIMEH function• $PIECE function• $HOROLOG special variable• $ZTIMESTAMP special variable• More information on locales in Customized National Language Translations380 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZTIMEH$ZTIMEHConverts a time value from a printable format to the <strong>Caché</strong> time special variable format.$ZTIMEH(time,format,erropt)$ZTH(time,format,erropt)ParameterstimeformaterroptThe time value to be converted.Optional — A numeric value that specifies the time format from which youare converting.Optional — The expression returned if the time parameter is consideredinvalid.DescriptionThe $ZTIMEH function converts a time value from a format produced by the $ZTIMEfunction to the format of the special variables $HOROLOG and $ZTIMESTAMP. If theoptional parameter format is not used, the input time must be in the format“hh:mm:ss.fff...”.Otherwise, the same integer format code used to produce the printable timefrom the $ZTIME function must be used for the time to be converted properly.ParametersformatSupported values are as follows:Code-11234DescriptionGet the effective format value from the TimeFormat property of the currentlocale, which defaults to a value of 1. This is the default behavior if you do notspecify format.Input time is in the form "hh:mm:ss" (24-hour clock).Input time is in the form “hh:mm” (24-hour clock).Input time is in the form “hh:mm:ss[AM/PM]” (12-hour clock).Input time is in the form “hh:mm[AM/PM]” (12-hour clock).<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 381


Math and Time FunctionserroptThis parameter suppresses error messages associated with invalid time values. Instead ofgenerating error messages, the function returns the value indicated byerropt.ExamplesWhen the input time is “14:43:38”, the following examples both return 53018:SET time="14:43:38"WRITE !,$ZTIMEH(time)WRITE !,$ZTIMEH(time,1)When the input time is “14:43:38.974”, the following example returns 53018.974:SET time="14:43:38.974"WRITE $ZTIMEH(time,1)NotesFractional SecondsUnlike the $ZTIME function, $ZTIMEH does not allow you to specify a precision. Anyfractional seconds in the original time format returned by $ZTIME are retained in the valuereturned by $ZTIMEH.Invalid Parameter ValuesYou receive a error if you specify an invalid format code (an integer less than-1 or greater than 4, a zero, or a non-integer value).If you do not supply an erropt value, you receive an error under thefollowing conditions:• Specify a time with an hour value outside the allowed range of 0 to 23 (inclusive).• Specify a time with a minute value outside the allowed range of 0 to 59 (inclusive).• Specify a time with a second value outside the allowed range of 0 to 59 (inclusive).• Specify a time value which uses a delimiter other than the value of the TimeSeparatorproperty in the current locale.382 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZTIMEHTime DelimiterBy default, <strong>Caché</strong> uses the value of the TimeSeparator property of the current locale todetermine the delimiter character for the time string. By default, the delimiter is “:”; all documentationexamples use this delimiter.Time SuffixesBy default, <strong>Caché</strong> uses properties in the current locale to determine the names of its timesuffixes. For $ZTIMEH, these properties (and their corresponding default values) are:• AM (“AM”)• PM (“PM”)• Midnight (“MIDNIGHT”)• Noon (“NOON”)This documentation will always use these default values for these properties.See Also• $ZDATETIME function• $ZDATETIMEH function• $ZTIME function• $HOROLOG special variable• $ZTIMESTAMP special variable• More information on locales in Customized National Language Translations<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 383


Routine, Debugging, and OtherCommandsThe following are reference pages for routine and debugging commands supported by <strong>Caché</strong><strong>ObjectScript</strong>. These commands supplement the <strong>Caché</strong> <strong>ObjectScript</strong> general commandsdescribed earlier in this document. Commands are listed in alphabetical order.Further introductory information on <strong>Caché</strong> command syntax and conventions is provided atthe beginning of the general commands reference pages. Additional information on <strong>Caché</strong>commands can be found in the Commands chapter of Using <strong>Caché</strong> <strong>ObjectScript</strong>.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 385


Routine, Debugging, and Other CommandsZBREAKSets a breakpoint.ZBREAK:pc location:action:condition:execute_codeZB:pc location:action:condition:execute_codeZBREAK:pc /command:optionZB:pc /command:optionArgumentspclocation:action:condition:execute_code/command:optionOptional — A postconditional expression.Specifies a code location (that sets a breakpoint) or a local orsystem variable (which sets a watchpoint). If the locationspecified already has a breakpoint/watchpoint defined, thenew specification completely replaces the old one.Optional — Specifies the action to take when thebreakpoint/watchpoint is triggered, specified as an alphabeticcode. Action code letters may be uppercase or lowercase,but must be enclosed in quotation marks. If omitted, defaultis “B”. If omitted, and either :condition or :execute_code isspecified, the colon must appear as a place-holder.Optional —Specifies an expression that will be evaluated toa boolean value when the breakpoint/watchpoint is triggered.The expression must be surrounded by quotation marks. Iftrue, action is carried out. If not specified, the default is true.If omitted, and :execute_code is specified, the colon mustappear as a place-holder.Optional —Specifies <strong>Caché</strong> <strong>ObjectScript</strong> code to be executedif :condition is true.The code must be surrounded by quotationmarks if it is a literal.A command governing all breakpoints and watchpoints. Theslash (/) prefix is mandatory. Available commands are:/CLEAR, /DEBUG, /TRACE, /ERRORTRAP, and/INTERRUPT. All except /CLEAR take an option, as describedbelow.386 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


DescriptionZBREAK sets breakpoints at specific lines of code and watchpoints on specific variables toallow you to interrupt program execution for debugging. This command is described fully inthe Debugging chapter in Using <strong>Caché</strong> <strong>ObjectScript</strong>.To view online help text about ZBREAK at the terminal prompt, specify a question mark,as follows:USER>ZBREAK ?ArgumentspcAn optional postconditional expression. <strong>Caché</strong> executes the command if the postconditionalexpression is true (evaluates to a non-zero numeric value). <strong>Caché</strong> does not execute the commandif the postconditional expression is false (evaluates to zero). For further details, referto Command Postconditional Expressions in Using <strong>Caché</strong> <strong>ObjectScript</strong>.locationZBREAKA required argument that specifies the breakpoint location as a line reference, *variable, or$. To set a breakpoint, specify the location and, optionally, the action, condition, and/orexecute_code. Any of these optional arguments may be omitted, but if specified or skipped,the mandatory colon separators (:) must be specified.The location argument may be prefixed by plus and minus signs, which indicate what to dowith an existing breakpoint at the specified location:Sign Prefixlocation–location+location-–locationMeaningSet breakpoint at location.Disable breakpoint at location.Enable breakpoint at location.Remove breakpoint at location.actionA code that specifies the action to take when the breakpoint/watchpoint is triggered. Forbreakpoints, the action occurs before the line of code is executed. For watchpoints, the actionoccurs after the command that modifies the local variable.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 387


Routine, Debugging, and Other CommandsAction Code“B”“L”“L+”“S”“S+”“T”“N”DescriptionSuspends execution and displays the line at which the breakoccurred, with a caret (^) indicating the location within the line. AGOTO resumes execution. “B” is the default.Suspends execution for single-step execution of lines using GOTO.Single-step mode suspended during DO, XECUTE, or user-definedfunctions.Suspends execution for single-step execution of lines using GOTO.Single-step mode also applies to DO, XECUTE, and user-definedfunctions.Suspends execution for single-step execution of commands usingGOTO. Single-step mode suspended during DO, FOR, XECUTE,or user-defined functions.Suspends execution for single-step execution of commands usingGOTO. Single-step mode also applies to DO, FOR, XECUTE, anduser-defined functions.Outputs a trace message to the trace device. Can be combined withany other action code. For example “TB” means suspend execution(“B”) and output trace message (“T”). “T” by itself does not suspendexecution. This action only works if a previous ZBREAK commandspecifies ZBREAK /TRACE:ON.Take no action at this breakpoint or watchpoint.conditionA boolean expression. When true (1), the action should be taken and the execute_code (ifpresent) executed. When false (0), the action and execute_code are ignored. Default is true(1).execute_codeThe <strong>Caché</strong> <strong>ObjectScript</strong> code to be executed. This code is executed prior to the action beingcarried out. Before the code is executed, the value of $TEST is saved. After the code hasexecuted, the value of $TEST as it existed in the program being debugged is restored./command:optionA command keyword used to set the ZBREAK environment for subsequent ZBREAKcommands. The /CLEAR command takes no option. The other command keywords are followedby an option, separated by a colon.388 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


ZINSERTKeyword/CLEAR/DEBUG:device/TRACE/ERRORTRAP/INTERRUPTDescriptionRemove all breakpoints.Clear or set debug device.Enable or disable sending trace messages to the trace device (the“T” action in subsequent ZBREAK commands.) Options are:ON=enable trace. :OFF=disable trace. :ALL=trace all lines.You canredirect output with the :ON or :ALL options by specifying a device.For example ZBREAK /TRACE:ON:device.Enable or disable $ZTRAP and $ETRAP. Options are :ON and :OFF.Specify Control-C action. Options are :NORMAL and :BREAK.See Also• BREAK command• OPEN command• USE command• $ZUTIL(68,5) Argumentless BREAK Process Switch function• $ZUTIL(69,5) Argumentless BREAK System Default function• Debugging chapter in Using <strong>Caché</strong> <strong>ObjectScript</strong>ZINSERTInserts a line of code in the current routine.ZINSERT:pc "code":locationZI:pc "code":locationArgumentspccodelocationOptional — A postconditional expression.A line of <strong>Caché</strong> <strong>ObjectScript</strong> code, specified as a string literal (enclosedin quotation marks) or a variable that contains a string literal. The firstcharacter must be either a space or a label name.Optional — The line after which ZINSERT inserts the code.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 389


Routine, Debugging, and Other CommandsDescriptionZINSERT "code" inserts a specified line of <strong>Caché</strong> <strong>ObjectScript</strong> code in the current routineat the current line location (edit pointer), as established by the ZPRINT or ZREMOVEcommand, by a previous ZINSERT command, or by some forms of the $TEXT function.ZINSERT "code":location inserts the specified line of code in the current routine after thespecified line location. Line location can be specified as number of lines offset from thebeginning of the routine, or number of lines offset from a specified label.After ZINSERT inserts a line of code, it resets the edit pointer to the end of this new line ofcode. This means the next ZINSERT places its line of code directly after the last new line,unless it explicitly specifies a location.ZINSERT effects only the local copy of the routine. It does not change the routine as storedon disk. To store inserted lines, you must use the ZSAVE command to save the routine.ZINSERT incrementally compiles each line.The ZINSERT command is usually executed from the programmer prompt. It should not becoded into the body of a routine, because its operation would effect the execution of thatroutine. To call ZINSERT from a routine, use the XECUTE command.CAUTION:ZINSERT and other commands move the edit pointer.ArgumentspcAn optional postconditional expression. <strong>Caché</strong> executes the command if the postconditionalexpression is true (evaluates to a non-zero numeric value). <strong>Caché</strong> does not execute the commandif the postconditional expression is false (evaluates to zero). For further details, referto Command Postconditional Expressions in Using <strong>Caché</strong> <strong>ObjectScript</strong>.codeA line of <strong>Caché</strong> <strong>ObjectScript</strong> code, specified as a string literal (in quotes), or a variable thatcontains a string literal. This line of code can contain one or more <strong>Caché</strong> <strong>ObjectScript</strong> commands,a new label name, or both a label and one or more commands. Because the code isinserted into a routine, it must follow <strong>Caché</strong> <strong>ObjectScript</strong> formatting. Therefore, the firstcharacter of the code string literal must either be a blank space (standard <strong>Caché</strong> <strong>ObjectScript</strong>indentation) or a label. The enclosing quotation marks are required. Since quotation marksenclose the line of code you are inserting, quotes within the code itself must be doubled.390 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


ZINSERTlocationThe line after which ZINSERT will insert the code. It can take either of the following forms:+offsetlabel+offsetSpecifies a line number within the routine. (The plus sign isrequired.)Specifies a label and a line number within the labelled section.Note:Specifying label^routine for the location generates a error.Lines of code are numbered beginning with 1. Thus a location of +1 inserts a line of codeafter the first line of the routine. To insert a line at the start of the routine or the start of alabelled section (before the existing first line), use an offset of +0. For example:ZINSERT "Altstart SET c=12,d=8":+0inserts the code line at the start of the routine.If location is omitted, the code is inserted at the current line location (edit pointer).ExamplesThe following example inserts the code line SET x=24 after the fourth line within the currentroutine. Because this inserted code line does not begin with a label, an initial space must beincluded as the required line start character.ZINSERT " SET x=24":+4In the following example, assume that the currently loaded routine contains a label called"Checktest". The ZINSERT command inserts a new line after the sixth line within Checktest(Checktest+6). This new line contains the label "Altcheck" and the command SET y=12.ZINSERT "Altcheck SET y=12":Checktest+6Note that because the inserted code line begins with the label “Altcheck”, no initial space isrequired after the quotation mark.The following example inserts the code line SET x=24 WRITE !,"x is set to ",x afterthe fourth line within the current routine. Because an inserted code line is enclosed in quotationmarks, the quotation marks in the WRITE command must be doubled.ZINSERT " SET x=24 WRITE !,""x is set to "",x":+4<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 391


Routine, Debugging, and Other CommandsNotesZINSERT and ZREMOVEYou can use the ZREMOVE command to remove one or more lines of code from the currentlyexecuting routine. Thus by using ZREMOVE and ZINSERT, you can substitute a new codeline for an existing code line. These operations only affect the copy of the routine currentlybeing run by your process.ZINSERT, XECUTE, and $TEXTYou use the XECUTE command to define and insert a single line of executable code fromwithin a routine. You use the ZINSERT command to define and insert by line position asingle line of executable code from outside a routine.An XECUTE command cannot be used to define a new label. Therefore, XECUTE doesnot require an initial blank space before the first command in its code line. ZINSERT canbe used to define a new label. Therefore ZINSERT does require an initial blank space (orthe name of a new label) before the first command in its command line.The $TEXT function permits you to extract a line of code by line position from within aroutine. $TEXT simply copies the specified line of code as a text string; it does not affectthe execution of that line or change the current line location (edit pointer) when extractingfrom the current routine. (Using $TEXT to extract code from a routine other than the currentroutine does change the current line location.) $TEXT can supply a line of code to theXECUTE command. $TEXT can also supply a line of code to a WRITE command, andthus supply a code line to the programmer prompt.See Also• XECUTE command• ZLOAD command• ZPRINT command• ZREMOVE command• ZSAVE command• $TEXT function392 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


ZKILLZKILLDeletes a node while preserving the node's descendants.ZKILL:pc array-node,...ZK:pc array-node,...Argumentspcarray-nodeOptional — A postconditional expression.A local variable, a process-private global, or a global that is an arraynode, or a comma-separated list of local, process-private global, orglobal array nodes.DescriptionThe ZKILL command removes the value of a specified array node without killing that node'sdescendants. In contrast, the KILL command removes the value of a specified array nodeand all of that node's descendants. An array node can be a local variable, a process-privatevariable, or a global variable.ArgumentspcAn optional postconditional expression. <strong>Caché</strong> executes the command if the postconditionalexpression is true (evaluates to a non-zero numeric value). <strong>Caché</strong> does not execute the commandif the postconditional expression is false (evaluates to zero). For further details, referto Command Postconditional Expressions in Using <strong>Caché</strong> <strong>ObjectScript</strong>.array-nodeA local, process-private global, or global array node. You can specify a single array node, ora comma-separated list of array nodes. For further details on subscripts and nodes, refer toGlobal Structure in Using <strong>Caché</strong> Multi-Dimensional Storage.ExampleIn this example, the ZKILL command deletes node a(1), but does not remove node a(1,1).<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 393


Routine, Debugging, and Other CommandsSET a(1)=1,a(1,1)=11SET x=a(1)SET y=a(1,1)ZKILL a(1)SET z=a(1,1)WRITE "x=",x," y=",y," z=",zreturns x=1 y=11 z=11. However, then issuing a:WRITE a(1)generates an error.See Also• KILL commandZLOADLoads routines into the routine buffer.ZLOAD:pc routineZL:pc routineArgumentspcroutineOptional — A postconditional expression.Optional — The routine to be loaded. If omitted, <strong>Caché</strong> loads a routinefrom the current device.DescriptionThe ZLOAD command loads <strong>Caché</strong> <strong>ObjectScript</strong> routines into the routine buffer. ZLOADhas two forms:• ZLOAD without an argument• ZLOAD with an argumentZLOAD without an ArgumentThe ZLOAD command without an argument loads a <strong>Caché</strong> <strong>ObjectScript</strong> routine from thecurrent device into the routine buffer. To load a routine from a device, execute the following:1. An OPEN command to open the device.394 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


ZLOAD2. A USE command to make the device the current device.3. A ZLOAD command without arguments.Line loading will continue until <strong>Caché</strong> reads a null string line (""). This loaded routine hasno name until you file it with the ZSAVE command.ZLOAD with an ArgumentZLOAD routine loads the specified (existing) routine into the routine buffer from the currentnamespace.ZLOAD does an implicit ZREMOVE when it loads the routine. That is, ZLOAD deletesany routine previously loaded as it writes the loaded routine. When it loads the routine,ZLOAD leaves the line pointer at the end of the last line of the routine.Once loaded, a routine remains the current one for the process until you load another routineexplicitly, with a ZLOAD command, or implicitly, with a DO or a GOTO command. Aslong as the routine is current, you can edit the routine (with ZINSERT and ZREMOVEcommands) and display it (with the ZPRINT command).You can only use the ZLOAD command when you enter it from the programmer prompt orwhen you call it using an XECUTE command. It should not be coded into the body of aroutine because its operation would effect the execution of that routine. Specifying ZLOADin a routine results in a compile error. Any attempt to execute ZLOAD from within a routinealso generates an error.ArgumentspcAn optional postconditional expression. <strong>Caché</strong> executes the command if the postconditionalexpression is true (evaluates to a non-zero numeric value). <strong>Caché</strong> does not execute the commandif the postconditional expression is false (evaluates to zero). For further details, referto Command Postconditional Expressions in Using <strong>Caché</strong> <strong>ObjectScript</strong>.routineThe name of the routine to be loaded. Routine names are case-sensitive. If the specified routinedoes not exist, <strong>Caché</strong> generates a error.ExamplesThe following example loads the routine ROUT, saved on disk:ZLOAD ROUT<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 395


Routine, Debugging, and Other CommandsThe following example loads the first routine from the device dev:OPEN devUSE devZLOADNotesRoutine Behavior with ZLOADIf you specify routine, <strong>Caché</strong> looks for the routine in the pool of routine buffers in memory.If the routine is not there, <strong>Caché</strong> loads the <strong>Caché</strong> <strong>ObjectScript</strong> object code version of theroutine into one of the buffers. The <strong>Caché</strong> <strong>ObjectScript</strong> source (intermediate) code remainsin the ^ROUTINE global of the current namespace, but is updated if you make edits and savethe changes. For example,ZLOAD TestThis example loads the object code version of the routine Test (if it is not already loaded).You can view and edit the contents of the ^ROUTINE global using the System ManagementPortal. Select the Globals option, then select the current namespace from the list of AvailableNamespaces.If you omit routine, <strong>Caché</strong> loads new lines of code that you enter from the current device,usually the keyboard until you terminate the code by entering a null line (that is, just press). This routine has no name until you save it with a subsequent ZSAVE command.ZLOAD and Language ModesWhen a routine is loaded, the current language mode changes to the loaded routine's languagemode. At the conclusion of called routines, the language mode is restored to the languagemode of the calling routine. However, at the conclusion of a routine loaded with ZLOADthe language mode is not restored to the previous language mode. For further details onchecking and setting language modes, refer to the $ZUTIL(55) function.See Also• OPEN command• USE command• XECUTE command• ZSAVE command396 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


ZNSPACEZNSPACESets the current namespace.ZNSPACE:pc nspaceZN:pc nspaceArgumentspcnspaceOptional — A postconditional expression.A string expression that evaluates to the name of an existing namespace.DescriptionZNSPACE nspace changes the current namespace to the nspace value. If nspace does notexist, <strong>Caché</strong> generates a error.nspace can be an explicit namespace or an implied namespace.<strong>Caché</strong> maintains the name of the current namespace in the $ZNSPACE special variable.You can change the current namespace by using the ZNSPACE command, the $ZUTIL(5)function, the %CD utility, or by setting the $ZNSPACE special variable. Use of ZNSPACEor %CD is preferable, because these provide more extensive error checking.You can determine the current namespace from the $ZNSPACE special variable or the$ZUTIL(5) function. You can determine whether an explicit namespace is defined on yoursystem using the $ZUTIL(90,10) function.On UNIX and OpenVMS systems, you can set the system-wide default namespace using the$ZUTIL(90,4) function. Calling this function has no effect on Windows systems. For Windowssystems, the system-wide default namespace can be set using a command-line start-up option.For information on creating and modifying namespaces, and mapping databases, routines,and globals to a namespace, see Configuring Namespaces in <strong>Caché</strong> System AdministrationGuide.ArgumentspcOptional — An optional postconditional expression. <strong>Caché</strong> executes the command if thepostconditional expression is true (evaluates to a non-zero numeric value). <strong>Caché</strong> does not<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 397


Routine, Debugging, and Other Commandsexecute the command if the postconditional expression is false (evaluates to zero). For furtherdetails, refer to Command Postconditional Expressions in Using <strong>Caché</strong> <strong>ObjectScript</strong>.nspaceAny valid string expression that evaluates to the name of the new namespace. nspace can bean explicit namespace or an implied namespace. In either case, it must be specified as a quotedstring.Namespace names are case-insensitive. <strong>Caché</strong> always displays explicit namespace names inall uppercase letters, and implied namespace names in all lowercase letters.An implied namespace specifies the namespace by system name and directory. There are twoforms:• "^^dir" (if the namespace directory is on the current system)• "^system^dir" (if the namespace directory is on a remote system)For dir, specify a directory path or an OpenVMS file specification. For example:ZNSPACE "^^c:\Cache51\Mgr\CacheTemp"W $ZNSPACEExamplesThe following example assumes that a namespace called "accounting" already exists. Otherwise,you receive a error.From the programmer prompt:USER>ZNSPACE "Accounting"ACCOUNTING>By default, as shown in this example, the <strong>Caché</strong> Terminal prompt displays the currentnamespace name. Namespace names are always displayed in uppercase letters.The following example tests for the existence of a namespace, then sets the current namespaceand the <strong>Caché</strong> Terminal prompt either to the specified namespace or to USER:398 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


ZNSPACEWRITE !,"Current namespace is ",$ZNSPACESET ns="accounting"IF 1=$ZUTIL(90,10,ns) {WRITE !,"Changing namespace to: ",nsZNSPACE nsXECUTE "SET x=$ZUTIL(68,26,1)"WRITE !,"and ",$ZNSPACE," will display at the prompt"}ELSE {WRITE !,"Namespace ",ns," does not exist"SET ns="user"WRITE !,"Changing namespace to: ",nsZNSPACE nsXECUTE "SET x=$ZUTIL(68,26,1)"WRITE !,"and ",$ZNSPACE," will display at the prompt"}NotesNamespaces with Default DirectoriesIf the namespace you select has a default directory on a remote machine, ZNSPACE doesnot change the current directory of your process to that namespace's directory. Thus, yourcurrent namespace becomes the namespace you selected, but your current directory remainsthe directory that was current before you issued the ZNSPACE command.Controlling Namespace DisplayTerminal PromptBy default, the <strong>Caché</strong> Terminal prompt displays the current namespace name. This defaultis configurable:Go to the System Management Portal, select System Configuration, select Advanced Settings,on the pull-down Category list select <strong>ObjectScript</strong>. View and edit the current setting ofPromptShowsNamespace.This also sets the prompt for Telnet windows. You can override this default for the currentprocess by using $ZUTIL(68,26), or system-wide by using $ZUTIL(69,26).$NAME and $QUERY FunctionsThe $NAME and $QUERY functions can return the extended global reference form of aglobal variable, which includes the namespace name. You can control whether these functionsreturn namespace names as part of the global variable name. $ZUTIL(68,7) sets this extendedglobal reference switch for the current process; $ZUTIL(69,7) sets this extended global referenceswitch system-wide. For further information on extended global references, see GlobalStructure in Using <strong>Caché</strong> Multi-Dimensional Storage.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 399


Routine, Debugging, and Other CommandsZNSPACE and $ZUTIL(39)When a process switches namespaces using the ZNSPACE command, $ZUTIL(39) informationis normally reset. The only exception to this is when the process switches from an impliednamespace to an implied namespace, in which case $ZUTIL(39) settings are preserved. Forfurther information on implied namespaces, see Global Structure in Using <strong>Caché</strong> Multi-Dimensional Storage.See Also• JOB command• $ZUTIL(5) Display or Switch Namespace function• $ZUTIL(39) Specify Search Path function• $ZUTIL(90,4) Start Up in a Specified Namespace function• $ZUTIL(90,10) Test Whether a Namespace is Defined function• $ZNSPACE special variable• Configuring Namespaces in <strong>Caché</strong> System Administration GuideZPRINTDisplays code from the current routine.ZPRINT:pc lineref1:lineref2ZP:pc lineref1:lineref2Argumentspclineref1:lineref2Optional — A postconditional expression.Optional — The line to be displayed, or the first line in a range of linesto be displayed. Can be a label name, a numeric offset (+n) or a labelname and a numeric offset.Optional — The last line in a range of lines to be displayed. To definea range, lineref1 must be specified.400 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


DescriptionThe ZPRINT command displays lines of code from the currently loaded routine. The outputis sent to the current device. You establish the current device with the USE command. <strong>Caché</strong>maintains the current device ID in the $IO special variable.ZPRINT has two forms:• Without arguments• With argumentsZPRINT without arguments displays all the lines of code in the currently loaded routine.ZPRINT with arguments displays the specified lines of code. ZPRINT lineref1 displays theline specified by lineref1. ZPRINT lineref1:lineref2 displays the range of lines starting withlineref1 and ending with lineref2.ArgumentspcAn optional postconditional expression. <strong>Caché</strong> executes the command if the postconditionalexpression is true (evaluates to a non-zero numeric value). <strong>Caché</strong> does not execute the commandif the postconditional expression is false (evaluates to zero). For further details, referto Command Postconditional Expressions in Using <strong>Caché</strong> <strong>ObjectScript</strong>.lineref1The line to be printed or the first in a range of lines to be displayed or printed. Can be specifiedin either of the following forms: +offset where offset is a positive integer specifying the linenumber within the current routine. label[+offset] where label is a label within the routineand offset is the line number within the label. If you omit the offset option, <strong>Caché</strong> prints thefirst code line and the label. Note that with this form, offset actually evaluates to offset+1.For example, label+1 prints the second line within the label.lineref2The last line in a range of lines to be displayed or printed. Specify in the same way as lineref1.The preceding colon is required.NotesZPRINT Equivalent to PRINTThe ZPRINT command is the exact equivalent of the PRINT command.ZPRINT<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 401


Routine, Debugging, and Other CommandsSee Also• PRINT command• ZINSERT command• ZLOAD command• ZREMOVE command• ZSAVE command• $IO special variable• The Spool Device in <strong>Caché</strong> I/O Device GuideZREMOVEErases lines from the current routine.ZREMOVE:pc lineref1:lineref2ZR:pc lineref1:lineref2Argumentspclineref1:lineref2Optional — A postconditional expression.Optional — The line or first in a range of lines to be removed.Optional — The last in a range of lines to be removed.DescriptionThe ZREMOVE command erases routine lines from the current routine. ZREMOVE hastwo forms:• Without an argument• With argumentsZREMOVE without an argument erases the entire current routine.ZREMOVE lineref1 as an argument erases the specified line. ZREMOVE lineref1:lineref2as an argument erases the range for lines starting with the first line reference and ending withthe second line reference.402 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


You can only use the ZREMOVE command when you enter it at the programmer promptor when you call it using an XECUTE command. It should not be coded into the body of aroutine because its operation would effect the execution of that routine.Only the local copy of the routine is affected, not the routine as stored on disk. To store themodified code, you must use the ZSAVE command to save the routine.ArgumentspcAn optional postconditional expression. <strong>Caché</strong> executes the command if the postconditionalexpression is true (evaluates to a non-zero numeric value). <strong>Caché</strong> does not execute the commandif the postconditional expression is false (evaluates to zero). For further details, referto Command Postconditional Expressions in Using <strong>Caché</strong> <strong>ObjectScript</strong>.lineref1ZREMOVEThe line to be removed, or the first in a range of lines to be removed. It can take any of thefollowing forms:+offsetlabellabel+offsetSpecifies a line number within the routine.Specifies a label within the routine. ZREMOVE erases only thelabel line itself. This includes any code that follows the label onthat line.Specifies a label and the number of line to offset within thelabeled section.You can use lineref1 to specify the beginning of a range of lines (lineref1:lineref2). The onlyrequirement is that the first location appear before the second in your routine.If you omit lineref1, ZREMOVE deletes the entire current routine.lineref2The last in a range of lines to be removed. Specify in any of the same formats used for lineref1.The colon prefix (:) is mandatory.ExamplesThis command erases the fourth line within the current routine.ZREMOVE +4<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 403


Routine, Debugging, and Other CommandsThis command erases the sixth line within the subroutine Test1.ZREMOVE Test1+6This command erases lines three through ten, inclusive, within the current routine.ZREMOVE +3:+10See Also• XECUTE command• ZINSERT command• ZSAVE commandZSAVESaves the current routine.ZSAVE:pc routineZS:pc routineArgumentspcroutineOptional — A postconditional expression.Optional — A new name for the routine.DescriptionThe ZSAVE command saves the current routine. Use ZSAVE to save any changes you havemade to the routine with ZINSERT and ZREMOVE commands. ZSAVE has two forms:• Without an argument• With an argumentZSAVE without arguments saves the current routine under its current name (that is, the nameunder which you previously saved it) on disk in the current namespace.ZSAVE routine saves the current routine under the name specified to disk in the currentnamespace.404 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


ArgumentspcAn optional postconditional expression. <strong>Caché</strong> executes the command if the postconditionalexpression is true (evaluates to a non-zero numeric value). <strong>Caché</strong> does not execute the commandif the postconditional expression is false (evaluates to zero). For further details, referto Command Postconditional Expressions in Using <strong>Caché</strong> <strong>ObjectScript</strong>.routineA new name under which to save the routine. If a routine by that name already exists, <strong>Caché</strong>overwrites it. Note that you are not asked to confirm the overwrite. If you omit routine, <strong>Caché</strong>saves the routine under its current name.ExampleThis example saves the currently loaded routine with "Test" as its new name.SET x="ZSAVE Test"XECUTE xNotesWhere to Use ZSAVEThe ZSAVE command works only when entered at the programmer prompt or when codedwithin an XECUTE statement in a routine. It should not be coded into the body of a routinebecause its operation would effect the execution of that routine. If you code ZSAVE in aroutine, but outside of an XECUTE statement, that ZSAVE saves the current program.ZSAVE and Routine RecompilationZSAVE recompiles the saved routine.ZSAVE with % RoutinesYou receive a error if you try to ZSAVE a %routine to a remote dataset, evenif that dataset is the current dataset for the process. The percent sign prefix is used for thenames of non-modifiable routines, such as system utilities.Concurrent ZSAVE OperationsZSAVEWhen using ZSAVE in a networked environment, a situation may occur in which two differentjobs might concurrently save a routine and assign it the same name. This operation has thepotential for one routine overwriting part of the other, producing unpredictable results. When<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 405


Routine, Debugging, and Other Commandsthis possibility exists, acquire an advisory lock on the routine prior to the ZSAVE operation.For example, LOCK ^ROUTINE("name"). For further details, refer to the LOCK command.When running a job across ECP, the saved source is more vulnerable to such concurrent savesbecause local buffer protection is not visible to other clients.See Also• XECUTE command• ZINSERT command• ZREMOVE commandZSYNCSynchronizes and forces the end of networked transactions for the current job.ZSYNC:pcArgumentspcOptional — A postconditional expression.DescriptionZSYNC synchronizes and forces the conclusion of all network transactions for the currentjob. You can also use ZSYNC in non-networked applications that might later be run in anetworked environment. Simply place it at the end of each complete transaction.ArgumentspcAn optional postconditional expression. <strong>Caché</strong> executes the command if the postconditionalexpression is true (evaluates to a non-zero numeric value). <strong>Caché</strong> does not execute the commandif the postconditional expression is false (evaluates to zero). For further details, referto Command Postconditional Expressions in Using <strong>Caché</strong> <strong>ObjectScript</strong>.406 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


NotesZSYNC Guarantees Return of Asynchronous ErrorsDepending on the operation requested, network errors are reported at different times. Errorsfor synchronous operations, such as LOCK, $GET, $ORDER and $QUERY, are reportedimmediately through the normal error trap on the command that performed the error.Errors for asynchronous operations, such as SET and KILL, may be reported either immediatelyor after a delay.Delayed errors return as a result of buffered asynchronous operations. When a job invokeseither SET or KILL, processing can continue on the client while the operation on the servercompletes. In this case, a special interrupt trap may occur sometime later in the program. Theerror code returned is identical to the error that originally occurred on the server.When you use the ZSYNC command to synchronize the activity of clients and servers, youforce the return of any asynchronous errors. That is to say, all global errors return to the jobbefore the ZSYNC command completes.ZSYNC Guarantees Transaction CompletionThe ZSYNC command lets applications synchronize activity on network servers. Executingthis command forces the completion of all network transactions for this job. Do not use thiscommand at the end of an update transaction that completes the filing of all global nodes onall servers, because it forces any delayed errors to be returned. In other words, all globalerrors are delivered to the job before the ZSYNC command completes.See Also• $ZUTIL(68,34)— Process Interruptible by Asynchronous Errors function• $ZUTIL(69,34) — Processes Interruptible by Asynchronous Errors function• Using <strong>ObjectScript</strong> for Transaction Processing in Using <strong>Caché</strong> <strong>ObjectScript</strong>ZSYNC<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 407


Routine, Debugging, and Other CommandsZTRAPForces an error with a specified error code.ZTRAP:pc ztrapargZTRAP:pc $ZERRORZTRAP:pc $ZEArgumentspcztraparg$ZERROROptional — A postconditional expression.Optional — An error code string. An error code string is specified as astring literal or an expression that evaluates to a string; only the firstfour characters of the string are used.The special variable $ZERROR, which can be abbreviated $ZE.DescriptionThe ZTRAP command accepts both a command postconditional and argument indirection.ZTRAP has three forms:• Without an argument• With a string argument• With $ZERRORZTRAP without an argument forces an error with the error code .ZTRAP ztraparg forces an error with the error code , where xxxx is the first fourcharacters of the string specified by ztraparg. If you specify an expression, rather than aquoted string literal, the compiler evaluates the expression and uses the first four charactersof the resulting string. When evaluating an expression, <strong>Caché</strong> strips the plus sign and leadingand trailing zeros from numbers. All remaining characters of ztraparg are ignored.ZTRAP $ZERROR does not force a new error. It stops execution at the current programstack level and pops stack levels until another error handler is found. Execution then continuesin that error handler with the current error code.408 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


ArgumentspcAn optional postconditional expression. <strong>Caché</strong> executes the command if the postconditionalexpression is true (evaluates to a non-zero numeric value). <strong>Caché</strong> does not execute the commandif the postconditional expression is false (evaluates to zero). For further details, referto Command Postconditional Expressions in Using <strong>Caché</strong> <strong>ObjectScript</strong>.ztrapargA string literal or an expression that evaluates to a string. Any of the following values canbe specified for ztraparg:• A quoted string of any length containing any characters. ZTRAP uses only the first fourcharacters to generate an error code; if there are fewer than four characters, it uses thecharacters provided. Unlike system error codes, which are always uppercase, case ispreserved. Thus:ZTRAP "FRED" ; generates ZTRAP "Fred" ; generates ZTRAP "Freddy" ; generates ZTRAP "foo" ; generates ZTRAP " foo" ; generates ZTRAP "@#$%" ; generates ZTRAP "" ; generates ZTRAP """" ; generates ZTRAPThe ZTRAP command accepts argument indirection. For more information, refer to Indirectionin Using <strong>Caché</strong> <strong>ObjectScript</strong>.Passing Control to an Error Handler with $ZERRORWhen the ZTRAP argument is the special variable $ZERROR, special processing is performedwhich is useful in $ZTRAP error handlers. ZTRAP $ZERROR does not force anew error. It stops execution at the current program stack level and pops stack levels untilanother error handler is found. Execution then continues in that error handler with the currenterror code. This error handler may be located in a different namespace.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 409


Routine, Debugging, and Other CommandsThis way of passing control to an error handler is preferable to use of the legacy ZQUITcommand.ExamplesThis example shows how you use the ZTRAP command with an expression to produce anerror code:; at this point the routine discovers an error ...ZTRAP "ER23"...When the routine is run and it discovers the anticipated error condition, the output appearsas follows:tag+offset^routineThis example shows how the use of a postconditional affects the ZTRAP command:;ZTRAP:y


ZWRITEMainNEW $ESTACKSET $ZTRAP="OnErr"WRITE !,"$ZTRAP set to: ",$ZTRAPWRITE !,"Main $ESTACK= ",$ESTACK // 0WRITE !,"Main $ECODE= ",$ECODE," $ZERROR=",$ZERRORDO SubAWRITE !,"Returned from SubA" // not executedWRITE !,"MainReturn $ECODE= ",$ECODE," $ZERROR=",$ZERRORQUITSubAWRITE !,"SubA $ESTACK= ",$ESTACK // 1ZTRAPWRITE !,"SubA $ECODE= ",$ECODE," $ZERROR=",$ZERRORQUITOnErrWRITE !,"OnErr $ESTACK= ",$ESTACK // 0WRITE !,"OnErr $ECODE= ",$ECODE," $ZERROR=",$ZERRORQUITSee Also• $ZERROR special variable• $ZTRAP special variable• Error Handling in Using <strong>Caché</strong> <strong>ObjectScript</strong>ZWRITEDisplays variables.ZWRITE:pc variableZW:pc variableArgumentspcvariableOptional — A postconditional expression.Optional — Name of a variable to display, or a comma-separated listof variables to display.DescriptionThe ZWRITE command displays variables on the current device. The ZWRITE commandhas two forms:• Without an argument• With arguments<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 411


Routine, Debugging, and Other CommandsZWRITE without an argument displays all variables in the local variable environment,including private variables.ZWRITE with a global or local variable name as an argument writes that variable and all itsdefined nodes. ZWRITE with a subscripted global or local variable name as an argumentwrites only the specified node and all its descendant nodes. A private variable cannot bespecified as a ZWRITE argument.ArgumentspcAn optional postconditional expression. <strong>Caché</strong> executes the command if the postconditionalexpression is true (evaluates to a non-zero numeric value). <strong>Caché</strong> does not execute the commandif the postconditional expression is false (evaluates to zero). For further details, referto Command Postconditional Expressions in Using <strong>Caché</strong> <strong>ObjectScript</strong>.variableName of a variable to display, or a comma-separated list of the names of variables to display.The variable can be a local variable or a global variable. It cannot be a private variable.Variables can be subscripted. You can use extended global reference to specify a globalvariable not mapped to the current namespace. For further information on subscripted variablesand extended global reference, refer to Global Structure in Using <strong>Caché</strong> Multi-DimensionalStorage.ExamplesZWRITE Without an ArgumentThe following example shows ZWRITE without an argument. It lists all defined local variables.SET x=100SET y=80SET d=x+yZWRITEreturns:d=180x=100y=80412 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


ZWRITEZWRITE with ArgumentsThe following example shows ZWRITE displaying two of the variables that were set in theprevious example:SET x=100SET y=80SET d=x+yZWRITE d,yreturns:d=180y=80By comparison, WRITE d,y displays the variables values without identifiers or line breaks:18080.ZWRITE Displaying a Global in the Current NamespaceThe following example shows ZWRITE displaying the contents of a subscripted globalvariable (located in the current namespace):ZNSPACE "SAMPLES"ZWRITE ^CinemaooFilmD(17)returns:^CinemaooFilmD(17)=".A complex history of struggle and redemptionCooking with Jane Austen 5 u R"ZWRITE Displaying a Global in Another NamespaceThe following example shows ZWRITE using extended global reference to display thecontents of a subscripted global variable located in another namespace called SAMPLES:ZNSPACE "USER"ZWRITE ^["SAMPLES"]CinemaooFilmD(17)ZWRITE Displaying a Global and DescendantsThe following example shows ZWRITE displaying the contents of a subscripted globalvariable and all its descendent nodes:ZNSPACE "SAMPLES"ZWRITE ^CinemaooFilmCategoryDreturns:<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 413


Routine, Debugging, and Other Commands^CinemaooFilmCategoryD=5^CinemaooFilmCategoryD(1)="Drama"^CinemaooFilmCategoryD(2)="Animation"^CinemaooFilmCategoryD(3)="Thriller"^CinemaooFilmCategoryD(4)="Action"^CinemaooFilmCategoryD(5)="Comedy"See Also• WRITE commandZZDUMPDisplays an expression in hexadecimal dump format.ZZDUMP:pc expression,...ArgumentspcexpressionOptional — A postconditional expression.The data to be displayed in hexadecimal dump format. You canspecify a number, a string (enclosed in quotation marks), a list(created with $LISTBUILD), or a variable that resolves to one ofthese.You can specify a single expression, or a comma-separatedlist of expressions.DescriptionZZDUMP displays an expression in hexadecimal dump format. ZZDUMP is primarily ofinterest to system programmers, but it can be useful in viewing strings that contain controlcharacters.ZZDUMP returns lines in one of the following formats:For a number or string value:position: hexdata printdataFor a list value:position: length datatype hexdata printdataThese format elements are described in the following table:414 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


ZZDUMPReturned LineElementpositionlengthdatatypehexdataprintdataDescriptionThe zero-based relative position of the initial character of thedisplayed line of the dump (in hexadecimal), followed by a colon.This value is always 0000 for the first line of a dump, and thenincrements for subsequent lines.Optional — In a list created with $LISTBUILD, the length, in bytes,of the list item, specified in hexadecimal. A list item containing aone-character string has a length of 03 because ZZDUMP countsthe length byte, the datatype byte, and the actual data byte.Optional — In a list created with $LISTBUILD, the data type ofthe stored list item, specified as a two-digit hexadecimal code.00 = Marker (no hexdata value)01 = Binary string (8 bits per character)02 = Unicode string (16–bits per character)04 = Positive integer05 = Negative integer06 = Positive floating point integer07 = Negative floating point integer08 = $DOUBLE integer (positive or negative)The data values for each character, represented in hexadecimal.If ASCII, these data values are represented by 2 hexadecimaldigits per character. If Unicode, these data values are representedby 4 hexadecimal digits per character.The printable character version of the data. If a character is notprintable, it is represented by a dot. In a list created with$LISTBUILD, the printable data characters are preceded by dotsrepresenting the length byte (see Notes below) and the datatypebyte.You can use the $ZHEX function to convert hexadecimal to decimal and vice versa.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 415


Routine, Debugging, and Other CommandsArgumentspc<strong>Caché</strong> executes the ZZDUMP command if the postconditional expression is true (evaluatesto a non-zero numeric value). <strong>Caché</strong> does not execute the command if the postconditionalexpression is false (evaluates to zero). For further details, refer to Command PostconditionalExpressions in Using <strong>Caché</strong> <strong>ObjectScript</strong>.expressionYou can specify expression as a numeric, a string literal, a list, or a variable that resolves toone of these. You can specify a single expression, or a comma-separated list of expressions.Specifying a comma-separated list of expressions is parsed as issuing a separate ZZDUMPcommand for each expression.ExamplesThe following example shows ZZDUMP returning hex dumps for two single-character stringvariables. Note that each comma-separated expression is treated as a separate invocation ofZZDUMP:SET x="A"SET y="B"ZZDUMP x,y0000: 41 A0000: 42 BThe following example shows ZZDUMP returning a hex dump for a string variable too longfor a single dump line. Note that the position for the second dump line (0010:) is in hexadecimal:SET z="ABCDEFGHIJKLMNOPQRSTUVWXYZ"ZZDUMP z0000: 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F 50 ABCDEFGHIJKLMNOP0010: 51 52 53 54 55 56 57 58 59 5A QRSTUVWXYZThe following example shows ZZDUMP returning hex dumps for three variables. Note thatno hex dump (not even a blank line) is returned for a null string variable. Also note that anumber is converted to canonical form (leading and trailing zeros and plus sign removed); astring containing a number is not converted to canonical form:SET x=+007SET y=""SET z="+007"ZZDUMP x,y,z416 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


ZZDUMP0000: 37 70000: 2B 30 30 37 +007Examples of List ElementsThe following examples show ZZDUMP returning hex dumps for lists created using$LISTBUILD.The following example shows two lists, the first with a single item, the second with threeitems. Note that each list item has its own length and datatype, and that these two bytes arerepresented both in the length count and as dots (non-printing characters) in the printdata onthe right side of each line. The datatype code for a string is 01.SET x=$LISTBUILD("ABC")SET y=$LISTBUILD("A","B","C")ZZDUMP x,y0000: 05 01 41 42 43 ..ABC0000: 03 01 41 03 01 42 03 01 43 ..A..B..CThe following example shows a list element that do not contain a value. Note how an undefinedlist differs from the null string list. An undefined list has a length of 01 (the length byte itself)and no datatype or value. A null string list has a length of 02 (the length byte and the datatypebyte) and has a datatype of 01 (string).ZZDUMP $LISTBUILD() // 01 .ZZDUMP $LISTBUILD("") // 02 01 ..The following example shows two lists that contain different forms of the number 65. In thefirst case, ZZDUMP treats “65” as a two-character string and returns the hexadecimal valuefor each character. In the second case, ZZDUMP treats 65 as a decimal number and returnsthe equivalent hexadecimal number (41) and the corresponding ASCII character (“A”) , inthe printdata on the right side of the dump line.ZZDUMP $LISTBUILD("65") // 04 01 36 35 ..65ZZDUMP $LISTBUILD(65) // 03 04 41 ..AThe following example shows lists with different datatype values. The comments for eachline show the length and datatype values returned:ZZDUMP $LISTBUILD("A") // 03 01ZZDUMP $LISTBUILD($CHAR(960)) // 04 02ZZDUMP $LISTBUILD(7) // 03 04ZZDUMP $LISTBUILD(-7) // 03 05ZZDUMP $LISTBUILD($ZPI) // 0B 06ZZDUMP $LISTBUILD(-$ZPI) // 0B 07ZZDUMP $LISTBUILD($DOUBLE($ZPI)) // 0A 08ZZDUMP $LISTBUILD($DOUBLE(-$ZPI)) // 0A 08ZZDUMP $LISTBUILD(-$DOUBLE($ZPI)) // 0A 08<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 417


Routine, Debugging, and Other CommandsNotesThe Length Byte and Long List ElementsIn the relatively small list items in the above examples, the length byte has always appearedin the printdata as a dot (a non-printing character). In fact, the character displayed in printdatafor the length byte depends on the hexadecimal value of the length byte. Therefore, stringslonger than 29 characters (length=31) display the length byte as a printable character inprintdata.When a list item exceeds 253 characters, length can no longer be specified using a singlebytelength indicator. In these cases, length is represented by a three-byte field. Unlike thesingle-byte length, the three-byte length field is not included in the total length.UnicodeIf one or more characters in a ZZDUMP expression is a wide (Unicode) character, all charactersin that expression are represented as wide characters. The following examples showthree variables containing a Unicode character. In all three cases, all characters are displayedas wide characters. Note however, that $LISTBUILD imposes its own formatting on therepresentation of wide characters, always using little-endian order regardless of the hardwareplatform. For further details, refer to the $LISTBUILD function.SET x=$CHAR(987)SET y=$CHAR(987)_"ABC"SET z=$LISTBUILD($CHAR(987)_"ABC")ZZDUMP x,y,z0000: 03DB ?0000: 03DB 0041 0042 0043 ?ABC0000: 0A 02 DB 03 41 00 42 00 43 00 ..Û.A.B.C.See Also• $CHAR function• $DOUBLE function• $LISTBUILD function• $ZHEX function418 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


<strong>Caché</strong> <strong>ObjectScript</strong> SpecialVariablesSpecial variables are variables that are maintained by the system. They are also referred toas system variables, but are here referred to as special variables to avoid confusion withstructured system variables.Special variable names begin with a dollar sign ($). They can be distinguished from functionsbecause they are not followed by parentheses and take no parameters. Special variable namesare case-insensitive. Many special variable names can be abbreviated. In the Synopsis foreach special variable, the full name syntax is first presented, and below it is shown theabbreviated name (if one exists).Historically, special variables have held scalar values. The system automatically updatesthese special variables to reflect various aspects of the operating environment. For example,the $IO special variable contains the ID of the current device. The $JOB special variablecontains the ID of the current job.Although you can set some special variables, most are read-only. With the exception of thisread-only constraint, you can treat the special variables just as you would any other variable.For example, you can reference a special variable in an expression and assign its current valueto another (user-defined) variable.Any implementation-specific special variable form is marked with the abbreviation of theplatform that supports it (Windows, OpenVMS, or UNIX). Any form that is not marked witha platform abbreviation is supported by all platforms.Special variables are listed in alphabetical order.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 419


<strong>Caché</strong> <strong>ObjectScript</strong> Special Variables$DEVICEContains user-specified device status information.$DEVICEDescription$DEVICE can be used to record device status information. You can use the $ZUTIL(96,5)function to place a value in $DEVICE. By convention, this value should describe the outcomeof an I/O operation as a 3-piece string, in the form:standard_error,user_error,explanatory_textYou can also set $DEVICE using the SET command.By default, $DEVICE contains the null string.See Also• $ZUTIL(96,5) Set $DEVICE Special Variable function$ECODEContains the current error code string.$ECODE$ECDescriptionWhen an error occurs, <strong>Caché</strong> sets the $ECODE special variable to a comma-surroundedstring containing the error code corresponding to the error. For example, when a referenceis made to an undefined global variable, <strong>Caché</strong> sets the $ECODE special variable to thefollowing string:,M7,$ECODE can contain ANSI-standard M error codes, with the form M#, where # is an integer.For example, M6 and M7 are “undefined local variable” and “undefined global variable,”respectively. (M7 is issued for both globals and process-private globals.) For a complete list,see ANSI-Standard M Error Messages in the <strong>Caché</strong> Error <strong>Reference</strong>.420 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ECODE can also contain error codes that are the same as <strong>Caché</strong> General System error codes(the error codes returned at the terminal prompt and to the $ZERROR special variable).However, $ECODE appends a “Z” to these error codes, and removes the angle brackets.Thus the $ECODE error ZSYNTAX is a error, ZILLEGAL VALUE is an error, and ZFUNCTION is a error. $ECODE doesnot retain any additional error info for those error codes that provide it; thus ZPROTECT isa error; the additional info component is kept in $ZERROR, but not in$ECODE. For more information about <strong>Caché</strong> error codes, see $ZERROR; for a completelist, see General System Error Messages in the <strong>Caché</strong> Error <strong>Reference</strong>.If an error occurs when $ECODE already contains an error code, <strong>Caché</strong> appends the codefor the new error to the current $ECODE value as a new piece in a string delimited by commas,as follows:,ZSTORE,M6,ZILLEGAL VALUE,ZPROTECT,In the above case, the most recent error is a error.Error codes accrue in the $ECODE special variable until one of the following happens:• You explicitly clear or set $ECODE.• The length of the accumulated string in $ECODE exceeds the maximum string datalength for your implementation.• You terminate the current process.Clearing or Setting $ECODEYou can clear or set $ECODE with the SET command. For example, you can clear $ECODEby setting it to the null string as follows:SET $ECODE=""Clearing the value of $ECODE also affects error processing flow of control for $ETRAPerror handlers and clears the error stack for your job. See Error Processing in Using <strong>Caché</strong><strong>ObjectScript</strong> for more details.You can force an error by setting $ECODE. Setting $ECODE to any non-null value forcesan interpreter error during the execution of a <strong>Caché</strong> <strong>ObjectScript</strong> routine. After <strong>Caché</strong> sets$ECODE to the non-null value that you specify, <strong>Caché</strong> takes the following steps:1. Generates an error condition (setting $ZERROR to the value )2. Passes control to any error handlers you have established.$ECODE<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 421


<strong>Caché</strong> <strong>ObjectScript</strong> Special VariablesYour error handlers can check for a particular string value you choose and take steps tohandle the particular condition appropriately.$ECODE String OverflowIf the length of the accumulated string in $ECODE exceeds 512 characters, the first newerror code that causes the string overflow replaces the current list of error codes in $ECODE.See Using <strong>Caché</strong> <strong>ObjectScript</strong> for more information about the maximum string data length.NotesCreating Your Own Error CodesThe format for the $ECODE special variable is a comma-surrounded list of one or moreerror codes. Error codes starting with the letter U are reserved for the user. All other errorcodes are reserved for <strong>Caché</strong>Non-null values that you use to set $ECODE should be distinguishable from the values <strong>Caché</strong>automatically generates. To ensure this, always prefix your error text with the letter U. Alsoremember to delineate your error code with commas. For example:SET $ECODE=",Upassword expired!,"WRITE !,"ECODE set to: ",$ECODESET $ECODE=""WRITE !,"ECODE cleared: ",$ECODECheck $ZERROR Rather Than $ECODE for <strong>Caché</strong> ErrorsYour error handlers should check $ZERROR rather than $ECODE for the most recent <strong>Caché</strong>error.See Also• ZTRAP command• $STACK function• $ESTACK special variable• $ZEOF special variable• $ZERROR special variable• $ZTRAP special variable• Error Handling in Using <strong>Caché</strong> <strong>ObjectScript</strong>• System Error Messages in <strong>Caché</strong> Error <strong>Reference</strong>422 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ESTACK$ESTACKContains the number of context frames saved on the call stack from a user-defined point.$ESTACK$ESDescription$ESTACK contains the number of context frames saved on the call stack for your job froma user-defined point. You specify this point by creating a new copy of $ESTACK using theNEW command.The $ESTACK special variable is similar to the $STACK special variable. Both contain thenumber of context frames currently saved on the call stack for your job or process. <strong>Caché</strong>increments and restores both when changing context. The major difference is that you canreset the $ESTACK count to zero at any point by using the NEW command. You cannotreset the $STACK count.Context Frames and Call StacksWhen a <strong>Caché</strong> image is started, before any contexts have been saved on the call stack, thevalues of both $ESTACK and $STACK are zero. Each time a routine calls another routinewith DO, <strong>Caché</strong> saves the context of the currently executing routine on the call stack, increments$ESTACK and $STACK, and starts execution of the called routine in the newly-createdcontext. The called routine can, in turn, call another routine, and so on. Each time anotherroutine is called, <strong>Caché</strong> increments $ESTACK and $STACK and places more saved contextson the call stack.Issuing a DO command, an XECUTE command, or a call to a user-defined function establishesa new execution context. Issuing a GOTO command does not.As DO commands, XECUTE commands, or user-defined function references create newcontexts, <strong>Caché</strong> increments the values of $STACK and $ESTACK. As QUIT commandscause contexts to exit, <strong>Caché</strong> restores the previous contexts from the call stack and decrementsthe values of $STACK and $ESTACK.The $ESTACK and $STACK special variables cannot be modified using the SET command.Attempting to do so results in a error.Creating a New $ESTACKYou can create a new copy of $ESTACK in any context by using the NEW command. <strong>Caché</strong>takes the following actions:<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 423


<strong>Caché</strong> <strong>ObjectScript</strong> Special Variables1. Saves the old copy of $ESTACK.2. Creates a new copy of $ESTACK with a value of zero (0).In this way, you can establish a particular context as the $ESTACK level 0 context. As youcreate new contexts with DO, XECUTE, or user-defined functions, <strong>Caché</strong> increments this$ESTACK value. However, when you exit the context in which the new $ESTACK wascreated ($ESTACK at level 0), <strong>Caché</strong> restores the value of the previous copy of $ESTACK.ExamplesThe following example shows the effect of a NEW command on $ESTACK. In this example,the MainRoutine displays the initial values of $STACK and $ESTACK (which are the samevalue). It then calls Sub1. This call increments $STACK and $ESTACK. The NEW commandcreates an $ESTACK with a value of 0. Sub1 calls Sub2, incrementing $STACK and$ESTACK. Returning to MainRoutine restores the initial values of $STACK and $ESTACK:MainWRITE !,"Initial: $STACK=",$STACK," $ESTACK=",$ESTACKDO Sub1WRITE !,"Return: $STACK=",$STACK," $ESTACK=",$ESTACKQUITSub1WRITE !,"Sub1Call: $STACK=",$STACK," $ESTACK=",$ESTACKNEW $ESTACKWRITE !,"Sub1NEW: $STACK=",$STACK," $ESTACK=",$ESTACKDO Sub2QUITSub2WRITE !,"Sub2Call: $STACK=",$STACK," $ESTACK=",$ESTACKQUITThe following example demonstrates how the value of $ESTACK is incremented as newcontexts are created by issuing DO and XECUTE commands, and decremented as thesecontexts are exited. It also shows that a GOTO command does not create a new context orincrement $ESTACK:MainNEW $ESTACKWRITE !,"Inital Main: $ESTACK=",$ESTACK // 0DO Sub1WRITE !,"Return Main: $ESTACK=",$ESTACK // 0QUITSub1WRITE !,"Sub1 via DO: $ESTACK=",$ESTACK // 1XECUTE "WRITE !,""Sub1 XECUTE: $ESTACK="",$ESTACK" // 2WRITE !,"Sub1 post-XECUTE: $ESTACK=",$ESTACK // 1GOTO Sub2Sub1ReturnWRITE !,"Sub1 after GOTO: $ESTACK=",$ESTACK // 1QUITSub2WRITE !,"Sub2 via GOTO: $ESTACK=",$ESTACK // 1GOTO Sub1Return424 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


NotesContext Levels in Programmer and Application ModesA routine invoked in application mode starts at a different context level than a routine youinvoke with the DO command in programmer mode. When you enter a DO command at the<strong>Caché</strong> Terminal programmer mode prompt, <strong>Caché</strong> creates a new context for the routine called.The routine you call can compensate by establishing a $ESTACK level 0 context and thenuse $ESTACK for all context-level references.Consider the following routine:$ESTACKSTART; Establish an $ESTACK Level 0 ContextNEW $ESTACK; Display the $STACK context levelWRITE !,"$STACK level in routine START is ",$STACK; Display the $ESTACK context level and exitWRITE !,"$ESTACK level in routine START is ",$ESTACKQUITWhen you run START in application mode, you see the following display:$STACK level in routine START is 0$ESTACK level in routine START is 0When you run START in programmer mode (by issuing DO ^START at the <strong>Caché</strong> Terminalprompt), you see the following display:$STACK level in routine START is 1$ESTACK level in routine START is 0$ESTACK and Error Processing$ESTACK is particularly useful during error processing when error handlers must unwindthe call stack to a specific context level. See Error Handling in Using <strong>Caché</strong> <strong>ObjectScript</strong> formore information about error processing.See Also• $STACK function• $STACK special variable• Error Handling in Using <strong>Caché</strong> <strong>ObjectScript</strong><strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 425


<strong>Caché</strong> <strong>ObjectScript</strong> Special Variables$ETRAPContains a string of <strong>Caché</strong> <strong>ObjectScript</strong> commands to be executed when an error occurs.$ETRAP$ETDescription$ETRAP contains a string that specifies one or more <strong>Caché</strong> <strong>ObjectScript</strong> commands that areexecuted when an error occurs.You use the SET command to give $ETRAP the value of a string that contains one or more<strong>Caché</strong> <strong>ObjectScript</strong> commands. Then, when an error occurs, <strong>Caché</strong> executes the commandsyou entered into $ETRAP. For example, suppose you set $ETRAP to a string that containsa GOTO command to transfer control to an error-handling routine:SET $ETRAP="GOTO LOGERR^ERRROU"<strong>Caché</strong> then executes this command in $ETRAP immediately following any <strong>Caché</strong> <strong>ObjectScript</strong>command that generates an error condition. <strong>Caché</strong> executes the $ETRAP command(s) at thesame context level in which the error condition occurs.$ETRAP Commands Compared with XECUTE CommandsThe commands in a $ETRAP string are not executed in a new context level, unlike thecommands in an XECUTE string. In addition, the $ETRAP command string is always terminatedby an implicit QUIT command. The implicit QUIT command quits with a null-stringargument when the $ETRAP error-handling commands are invoked in a user-defined functioncontext where an argumented QUIT command is required.Setting $ETRAP Values in Different Context LevelsBy default, <strong>Caché</strong> carries the value of the $ETRAP special variable forward into new DO,XECUTE, and user-defined function contexts. However, you can create a new copy of$ETRAP in a context by issuing the NEW command, as follows:NEW $ETRAPWhenever you issue a NEW for $ETRAP, <strong>Caché</strong> performs the following actions:1. Saves the copy of $ETRAP that was in use at that point.2. Creates a new copy of $ETRAP.3. Assigns the new copy of $ETRAP the same value as the old, saved copy of $ETRAP.426 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


You then use the SET command to assign a different value to the new copy of $ETRAP. Inthis way, you can establish new $ETRAP error-handling commands for the current context.You can also clear $ETRAP by setting it to the null string. <strong>Caché</strong> then executes no $ETRAPcommands at the context level in the event of an error.When a QUIT command causes the current context to be exited, <strong>Caché</strong> restores the old, savedvalue of $ETRAP.ExampleThe following example demonstrates how the value of $ETRAP is carried forward into newcontexts and how you can invoke $ETRAP error-handling commands again in each contextafter an error occurs. The $ETRAP commands in this example make no attempt to dismissthe error. Rather, control by default is passed back to $ETRAP error-handling commands ateach previous context level.The sample code is as follows:ETRNEW $ETRAPSET $ETRAP="WRITE !,""$ETRAP invoked at Context Level "",$STACK"; Initiate an XECUTE context that initiates a DO contextXECUTE "DO A"QUIT; Initiate a user-defined function contextASET A=$$BQUIT; A User-defined function that generates an errorB()QUIT 1A sample session using this code might run as follows:>DO ^ETR$ETRAP invoked at context level 4$ETRAP invoked at context level 3$ETRAP invoked at context level 2$ETRAP invoked at context level 1NotesUse NEW Before Setting $ETRAP to a New Value$ETRAPIf you assign a new value to $ETRAP in a context without first creating a new copy of$ETRAP with the NEW command, <strong>Caché</strong> establishes that new value as the value of $ETRAPnot only for the current context but also for all previous contexts. Therefore, <strong>InterSystems</strong>strongly recommends that you create a new copy of $ETRAP with the NEW commandbefore it is set with a new value.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 427


<strong>Caché</strong> <strong>ObjectScript</strong> Special Variables$ETRAP Value is a Line of <strong>ObjectScript</strong> CodeBecause the string value of $ETRAP is executable <strong>Caché</strong> <strong>ObjectScript</strong> commands, the lengthof the string cannot be longer than the maximum length of a <strong>Caché</strong> <strong>ObjectScript</strong> routine line.See Using <strong>Caché</strong> <strong>ObjectScript</strong> for more information.$ETRAP and Error HandlingThe $ETRAP special variable is one of many <strong>Caché</strong> <strong>ObjectScript</strong> language features thatenable you to control the handling and logging of errors that occur in your applications.$ETRAP in particular plays an important role in controlling the flow of execution after anerror occurs. See Error Handling in Using <strong>Caché</strong> <strong>ObjectScript</strong> for more information abouterror handling.When setting $ETRAP to execute an error handler (for example, with a GOTO command)you can specify the error handler as tag (a label in the current routine), ^routine (the beginningof a specified external routine), or tag^routine (a specified label in a specified external routine).$ETRAP supports tag+offset in some contexts (but not in procedures). This optional +offsetis an integer specifying the number of lines to offset from tag. <strong>InterSystems</strong> recommendsthat you avoid the use of a line offset when specifying an error handler location.When you set an error handler using $ZTRAP, this handler takes precedence over anyexisting $ETRAP error handler. <strong>Caché</strong> implicitly performs a NEW $ETRAP command andsets $ETRAP to the null string ("").See Also• NEW command• SET command• $ECODE special variable• $ZEOF special variable• $ZTRAP special variable• Error Handling in Using <strong>Caché</strong> <strong>ObjectScript</strong>428 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$HALT$HALTContains a halt trap routine call.$HALTDescription$HALT contains the name of the current halt trap routine. A halt trap routine is called byyour application when a HALT command is encountered. This halt trap routine may performclean up or logging processing before issuing a HALT command, or it may substitute otherprocessing rather than halting program execution.You set $HALT to a halt trap routine using the SET command. The halt trap routine isspecified by a quoted string with the following format:SET $HALT=locationHere location can be specified as tag (a label in the current routine), ^routine (the beginningof a specified external routine), or tag^routine (a specified label in a specified external routine).$HALT supports tag+offset in some contexts (but not in procedures). This optional +offsetis an integer specifying the number of lines to offset from tag. <strong>InterSystems</strong> recommendsthat you avoid the use of a line offset when specifying location.$HALT defines a halt trap routine for the current context. If there is already a halt trap definedfor the current context, the new one replaces it. If you specify a non-existent routine name,a HALT command ignores that $HALT and unwinds the stack to locate a valid $HALT ata previous context level.To remove the halt trap for the current context, set $HALT to a null string. Attempting toremove a halt trap by using the NEW or KILL commands results in a error.Halt Trap ExecutionWhen you issue a HALT command, <strong>Caché</strong> checks the current context for $HALT. If no$HALT is defined for the current context (or it is set to a non-existent routine name or thenull string), <strong>Caché</strong> unwinds the stack to the previous context and looks for $HALT there.This process continues until either a defined $HALT is located or the stack is completelyunwound. <strong>Caché</strong> uses the value of $HALT to transfer execution to the specified halt traproutine. The halt trap routine executes in the context at which $HALT was defined. No errorcode is set or error message issued.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 429


<strong>Caché</strong> <strong>ObjectScript</strong> Special VariablesIf no valid $HALT is set in the current context or previous contexts, issuing a HALT commandcompletely unwinds the stack and performs an actual program halt.Commonly, a halt trap routine performs some clean-up or reporting processing, and thenissues a HALT command. Note that with $HALT defined, the original HALT commandinvokes the halt trap, but does not perform an actual program halt. For an actual halt to occur,the halt trap routine must contain a second HALT command.A HALT command issued by a halt trap routine is not trapped by that halt trap, but it maybe trapped by a halt trap established at a lower context level. Thus a cascading series of halttraps may be invoked by a single HALT command.Similar processing is performed by the error trap command ZTRAP, and the associated$ZTRAP and $ETRAP special variables.ExamplesThe following example uses $HALT to establish a halt trap:SET $HALT="MyTrap^CleanupRoutine"WRITE !,"the halt trap is: ",$HALTNote that it is the programmer's responsibility to make sure that the specified routine exists.The following example shows how the halt trap routine executes in the context at which$HALT was defined. In this example, $HALT is defined at $ESTACK level 0, HALT isissued at $ESTACK level 1, and the halt trap routine executes at $ESTACK level 0.MainNEW $ESTACKSET $HALT="OnHalt"WRITE !,"Main $ESTACK= ",$ESTACK," $HALT= ",$HALT // 0DO SubAWRITE !,"Returned from SubA" // not executedQUITSubAWRITE !,"SubA $ESTACK= ",$ESTACK," $HALT= ",$HALT // 1HALTWRITE !,"this should never display"QUITOnHaltWRITE !,"OnHalt $ESTACK= ",$ESTACK // 0HALTQUITThe following example is identical to the previous example, except that $HALT is definedat $ESTACK level 1. A HALT command is issued at $ESTACK level 1, and the halt traproutine executes at $ESTACK level 1. The HALT issued by the halt trap routine unwindsthe stack, and, failing to find a $HALT defined at the previous context level, it halts programexecution. Thus, the WRITE command following the DO command is not executed.430 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$HALTMainNEW $ESTACKWRITE !,"Main $ESTACK= ",$ESTACK," $HALT= ",$HALT // 0DO SubAWRITE !,"Returned from SubA" // not executedQUITSubASET $HALT="OnHalt"WRITE !,"SubA $ESTACK= ",$ESTACK," $HALT= ",$HALT // 1HALTWRITE !,"this should never display"QUITOnHaltWRITE !,"OnHalt $ESTACK= ",$ESTACK // 1HALTQUITThe following example shows how a cascading series of halt traps can be invoked. Halt trapHalt0 is defined at $ESTACK level 0, and halt trap Halt1 is defined at $ESTACK level 1.The HALT command is issued at $ESTACK level 2. <strong>Caché</strong> unwinds the stack to invoke thehalt trap Halt1 at $ESTACK level 1. This halt trap issues a HALT command; <strong>Caché</strong> unwindsthe stack to invoke the halt trap Halt0 at $ESTACK level 0. This halt trap issues a HALTcommand that halts program execution.MainNEW $ESTACKSET $HALT="Halt0"WRITE !,"Main $ESTACK= ",$ESTACK," $HALT= ",$HALT // 0DO SubAWRITE !,"Returned from SubA" // not executedQUITSubASET $HALT="Halt1"WRITE !,"SubA $ESTACK= ",$ESTACK," $HALT= ",$HALT // 1DO SubBWRITE !,"Returned from SubA" // not executedQUITSubBWRITE !,"SubB $ESTACK= ",$ESTACK," $HALT= ",$HALT // 2HALTWRITE !,"this should never display"QUITHalt0WRITE !,"Halt0 $ESTACK= ",$ESTACK // 0WRITE !,"Bye-bye!"HALTQUITHalt1WRITE !,"Halt1 $ESTACK= ",$ESTACK // 1HALTQUITSee Also• HALT command<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 431


<strong>Caché</strong> <strong>ObjectScript</strong> Special Variables$HOROLOGContains the current date and time as integer counters.$HOROLOG$HDescription$HOROLOG contains a character string that consists of two integer values, separated by acomma. These two integers represent the current date and time. These integers are counters,not user-readable dates and times. $HOROLOG returns the current date and time in thefollowing format:date,timeThe first integer is the number of days since December 31, 1840, where day 1 is January 1,1841. Because <strong>Caché</strong> represents dates using a counter from an arbitrary starting point, <strong>Caché</strong>is unaffected by the Year 2000 boundary. The maximum value for this date integer is 2980013,which corresponds to December 31, 9999.The second integer is the number of seconds since midnight of the current day. The systemincrements the time field from 0 to 86399 seconds. When it reaches 86399 at midnight, thesystem resets the time field to 0 and increments the date field by 1.Setting $ZTIMEZONE affects the value of $HOROLOG for the current process. It changesthe time portion of $HOROLOG, and this change of time can also change the date portionof $HOROLOG.The various ways to return the current date and time are compared, as follows:• $HOROLOG contains the local, variant-adjusted date and time in <strong>Caché</strong> storage format.It does not record fractional seconds. How $HOROLOG resolves fractional secondsdepends on the operating system platform: On Windows, it rounds up any fractionalsecond to the next whole second. On UNIX, it truncates the fractional portion.• $ZUTIL(188) returns the local, variant-adjusted date and time, with fractional seconds,in <strong>Caché</strong> storage ($HOROLOG) format. Fractional seconds are expressed in six digitsof precision.• $ZTIMESTAMP contains the UTC (Greenwich Mean) date and time, with fractionalseconds, in <strong>Caché</strong> storage ($HOROLOG) format. Fractional seconds are expressed inthree digits of precision (on Windows systems), or six digits of precision (on UNIX systems).432 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


You can obtain the same current date and time information by invoking a system method, asfollows:WRITE $SYSTEM.SYS.Horolog()Refer to the “Class %SYSTEM.SYS” section of the <strong>Caché</strong> Class <strong>Reference</strong> for further details.Separating Date and TimeTo get just the date portion or just the time portion of $HOROLOG, you can use the $PIECEfunction, specifying the comma as the delimiter character:SET dateint=$PIECE($HOROLOG,",",1)SET timeint=$PIECE($HOROLOG,",",2)WRITE !,"Date and time: ",$HOROLOGWRITE !,"Date only: ",dateintWRITE !,"Time only: ",timeintTo get just the date portion of a $HOROLOG value, you can also use the following programmingtrick:SET dateint=+$HOROLOGWRITE !,"Date and time: ",$HOROLOGWRITE !,"Date only: ",dateintThe plus sign (+) causes <strong>Caché</strong> to parse the $HOROLOG string as a number. When <strong>Caché</strong>encounters a non-numeric character (the comma) it truncates the rest of the string and returnsthe numeric portion. This is the date integer portion of the string.Date and Time ConversionsYou can use the $ZDATE function to convert the date portion of $HOROLOG into external,user-readable form. You can use the $ZTIME function to convert the time portion of$HOROLOG into external user-readable form. You can use the $ZDATETIME functionto convert both the date and time. When using $HOROLOG, setting the precision for timevalues in these functions always returns zeros as fractional seconds.You can use the $ZDATEH function to convert a user-readable date into the date portion of$HOROLOG. You can use the $ZTIMEH function to convert a user-readable time into thetime portion of $HOROLOG. You can use the $ZDATETIMEH function to convert boththe date and time to a $HOROLOG value.Setting the Date$HOROLOGYou can use the $ZUTIL(71) function to set $HOROLOG to a user-specified date for thecurrent process.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 433


<strong>Caché</strong> <strong>ObjectScript</strong> Special VariablesThis special variable cannot be modified using the SET command. Attempting to do so resultsin a error.WRITE !,$ZUTIL(71,12345) // set $HOROLOG dateSET x=$HOROLOGSET y=$ZUTIL(188)SET z=$ZTIMESTAMPWRITE !,x," which is ",$ZDATETIME(x,1,1,9) // changed dateWRITE !,y," which is ",$ZDATETIME(y,1,1,9) // no date changeWRITE !,z," which is ",$ZDATETIME(z,1,1,9) // no date changeNote that $ZUTIL(71) changes the $HOROLOG value, but not the $ZUTIL(188) or$ZTIMESTAMP value.Local Time Variant Thresholds$HOROLOG calculates the number of seconds from midnight by consulting the systemclock. Therefore, if the system clock is automatically reset when crossing a local time variantthreshold, such as the beginning or end of Daylight Savings Time, the time value of$HOROLOG also shifts abruptly ahead or back by the appropriate number of seconds. Forthis reason, comparisons of two $HOROLOG time values may yield unanticipated resultsif the period between the two values includes a local time variant threshold.Dates Before 1840$HOROLOG cannot be directly used to represent dates outside of the range of years 1840through 9999. However, you can represent historic dates far beyond this range using the SQLJulian date feature. The SQL Julian date functions TO_DATE and TO_CHAR take an unsignedinteger and format it as a date, counting from 4711 BC (BCE). By using the $PIECE function,you can extract the date integer from $HOROLOG and use this as input to one of theseJulian date functions, as shown in the following example. Note that the $HOROLOG integerrepresenting the current date give a far different Julian date value. For example, a$HOROLOG date in the year 2004 gives a Julian date in the year 4548 BC.SET x=$PIECE($HOROLOG,",",1)&sql(SELECT TO_DATE(:x,'J') INTO :yFROM Sample.Person)WRITE !,"Julian date= ",yExamplesThe following example displays the current contents of $HOROLOG.WRITE $HOROLOGreturns a value formatted like this: 58923,49170434 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


The following example uses $ZDATE to convert the date field in $HOROLOG to a dateformat.WRITE $ZDATE($PIECE($HOROLOG,",",1))returns a value formatted like this: 04/29/2002The following example converts the time portion of $HOROLOG to a time in the form ofhours:minutes:seconds on a 12-hour (a.m. or p.m.) clock.CLOCKTIMENEWSET Time=$PIECE($HOROLOG,",",2)SET Sec=Time#60SET Totmin=Time\60SET Min=Totmin#60SET Milhour=Totmin\60IF Milhour=12 { SET Hour=12,Meridian=" pm" }ELSEIF Milhour>12 { SET Hour=Milhour-12,Meridian=" pm" }ELSE { SET Hour=Milhour,Meridian=" am" }WRITE !,Hour,":",Min,":",Sec,MeridianQUITSee Also• $ZDATE function• $ZDATEH function• $ZDATETIME function• $ZDATETIMEH function• $ZTIME function• $ZTIMEH function• $ZUTIL(188) Local Date/Time with Fractional Seconds function• $ZUTIL(71) Set Date to a Fixed Value function• $ZTIMESTAMP special variable• $ZTIMEZONE special variable$HOROLOG<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 435


<strong>Caché</strong> <strong>ObjectScript</strong> Special Variables$IOContains the ID of the current input/output device.$IO$IDescription$IO contains the device ID of the current device to which all input/output operations aredirected. (If the input and output devices are different, $IO contains the ID of the currentinput device.)<strong>Caché</strong> sets the value of $IO to the principal input/output device at login. $PRINCIPALcontains the ID of the principal device. You issue a USE command to change the currentdevice. Only the USE and CLOSE commands, a BREAK command, or a return to the programmerprompt can change this value.The $ZUTIL(96,14) function returns the device type of the current device.On UNIX and VMS systems, $IO contains the actual device name.On Windows systems, $IO contains a <strong>Caché</strong>-generated unique identifier for the principaldevice. For terminal devices (TRM, TNT, and LAT), this consists of a pseudo-device nameenclosed in vertical bars, a colon and another vertical bar, followed by the device's processID (pid) number. For non-terminal devices, the pseudo-device name is enclosed in verticalbars and followed by a unique numeric identifier.For a <strong>Caché</strong> terminal: |TRM|:|pidFor a Telnet terminal: |TNT|nodename:portnumber|pidFor a LAT terminal: |LAT|:|pidFor a file descriptor: |FD|file_descriptor_number(File descriptors are used with CALLIN/CALLOUT remote access.)For a TCP device: |TCP|unique_device_identifierFor a named pipe: |NPIPE|unique_device_identifierFor the default printer: |PRN|For a printer other than the default: |PRN|physical_device_name436 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


If the principal device is a null device (which is the default for a background process), $IOcontains the null device name with ":pid" appended, thus allowing you to use $IO for a uniquesubscript. The null device name contained in $IO depends on the operating system.• For Windows systems, $IO contains //./nul:pid• For UNIX systems, $IO contains /dev/null:pid• For VMS systems, $IO contains NLA0::pidIf the input device is redirected via a pipe or file, $IO contains “00”.You can test the value of $IO, as in the following OpenVMS example:TESTPRGOPEN "/dev/tty04"USE "/dev/tty04"SET old=$IOCLOSE $IOOPEN "/dev/tty03"USE "/dev/tty03"WRITE !,"Old device: ",old,!,"Current device: ",$IOCLOSE $IOQUITThe default device number for a device is configurable. Go to the System Management Portal,select System Configuration, select Advanced Settings, on the pull-down Category list selectDevices. Click “contents” to display the current list of devices. For the desired device, click“edit” to display and modify its PhysicalDevice: option. If you do this, $IO will contain theassigned device number, rather than the actual operating system device name.This special variable cannot be modified using the SET command. Attempting to do so resultsin a error.See Also• USE command• $PRINCIPAL special variable• $ZUTIL(96,14) Return current device type function• I/O Devices and Commands in <strong>Caché</strong> I/O Device Guide• Terminal I/O in <strong>Caché</strong> I/O Device Guide$IO<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 437


<strong>Caché</strong> <strong>ObjectScript</strong> Special Variables$JOBContains the ID of the current process.$JOB$JDescription$JOB contains the ID number of the current process. This ID number is the host operatingsystem's actual process ID (PID). This ID number is unique for each process.The ID number for an I/O process (such as a <strong>Caché</strong> terminal process) is part of the stringcontained in the $IO special variable.The format of the string returned to $JOB is determined by the setting of the $ZUTIL(68,42)or $ZUTIL(69,42) functions. By default $JOB returns only the 10-digit PID, but you canset these functions to have $JOB return both the PID and the node name. If you change thesetting of this switch, you must recompile any routines that use the string returned to $JOBin arithmetic operations where $JOB is converted to an integer.This special variable cannot be modified using the SET command. Attempting to do so resultsin a error.To return the PID as the terminal prompt, use $ZUTIL(186,5).Other Information About the Current ProcessYou can obtain the same current process ID number by invoking a system method, as follows:WRITE $SYSTEM.SYS.ProcessID()Refer to the “Class %SYSTEM.SYS” section of the <strong>Caché</strong> Class <strong>Reference</strong> for further details.You can use $JOB to obtain the job number for the current process as follows:ZNSPACE "%SYS"SET Job=##CLASS(SYS.Process).%OpenId($JOB)WRITE Job.JobNumberRefer to the “Class SYS.Process” section of the <strong>Caché</strong> Class <strong>Reference</strong> for further details.You can obtain status information about the current process from the $ZJOB special variable.You can obtain the PID of the child process or the parent process of the current process fromthe $ZCHILD and $ZPARENT special variables.438 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


You can obtain the PIDs of the current jobs in the job table from the ^$JOB structured systemvariable.See Also• JOB command• $ZUTIL(68,42) $JOB Format for Process function• $ZUTIL(69,42) $JOB Format System Default function• $IO special variable$KEY$KEYContains the terminator character from the most recent READ.$KEY$KDescription$KEY contains the character or character sequence that terminated the last READ commandon the current device. $KEY and $ZB are very similar in function; see below for a detailedcomparison.• If the last read terminated because of a terminator character (such as the key), $KEY contains the terminator character.• If the last read terminated because of a timeout or a fixed-length read length limit, $KEYcontains the null string. No terminator character was encountered.• If the last read was a single-character read (READ *a), and a character was entered, $KEYcontains the actual input character.$KEY and $ZB are very similar, though not identical. See below for a comparison.You can use the SET command to specify a value for $KEY. You can use the ZZDUMPcommand to display the value of $KEY.During a terminal session, the end of every command line is recorded in $KEY as a carriagereturn (hexadecimal 0D). In addition, the $KEY special variable is initialized to carriagereturn by the process that initializes the terminal session. Therefore, to display the value of<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 439


<strong>Caché</strong> <strong>ObjectScript</strong> Special Variables$KEY set by the READ command or a SET command during a terminal session, you mustcopy the $KEY value to a local variable within the same line of code.ExamplesIn the following example, a variable-length READ command either receives data from theterminal or times out after 10 seconds. If the user inputs the data before the timeout, $KEYcontains the user-input carriage return (hex 0D) that terminated the data input. If, however,the READ timed out, $KEY contains the null string, indicating that no terminator characterwas received.READ "Ready or Not: ",x:10ZZDUMP $KEYIn the following example, a fixed-length READ command either receives data from the terminalor times out after 10 seconds. If the user inputs the specified number of characters (inthis case, one character), the user does not have to press to conclude the READoperation. The user can respond to the read prompt by pressing rather thanentering the specified number of characters.If the read operation timed out, both $KEY and $ZB contain the null string. If the user inputsa one-character middle initial, $KEY contains the null string, because the fixed-length READoperation concluded without a terminator character. If the user pressed ratherthan entering a middle initial, $KEY contains the user-input carriage return.READ "Middle initial: ",z#1:10IF $ASCII($ZB)=-1 {WRITE !,"The read timed out" }ELSEIF $ASCII($KEY)=-1 {WRITE !,"A character was entered" }ELSEIF $ASCII($KEY)=13 {WRITE !,"A line return was entered" }ELSE {WRITE !,"Unexpected result" }Notes$KEY and $ZB ComparedBoth $KEY and $ZB contain the character that terminates a READ operation. These twospecial variables are similar, but not identical. Here are the principal differences:• $KEY can be set using the SET command. $ZB cannot be SET.• Following a successful fixed-length READ, $ZB contains the final character input (forexample, when the 5-digit postal code “02138” is input as a fixed-length READ, $ZBcontains “8”). Following a successful fixed-length READ, $KEY contains the null string("").440 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


• $KEY does not support block-based read and write operations, such as magnetic tapeI/O.$KEY on the Command LineWhen issuing commands interactively from the <strong>Caché</strong> Terminal command line, you press to issue each command line. The $KEY and $ZB special variables record thiscommand line terminator character. Therefore, when using $KEY or $ZB to return the terminationstatus of a read operation, you must set a variable as part of the same command line.For example, if you issue the command:>READ x:10from the command line, then check $KEY, it will not contain the results of the read operation;it will contain the character that executed the command line. To return the resultsof the read operation, set a local variable with $KEY in the same command line, as follows:>READ x:10 SET rkey=$KEYThis preserves the value of $KEY set by the read operation. To display this read operationvalue, issue either of the following command line statements:>WRITE $ASCII(rkey); returns -1 for null string (time out); returns ASCII decimal value for terminator character>ZZDUMP rkey; returns blank line for null string (time out); returns hexadecimal value for terminator characterSee Also• READ command• SET command• ZZDUMP command• $ZB special variable$KEY<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 441


<strong>Caché</strong> <strong>ObjectScript</strong> Special Variables$PRINCIPALContains the ID of the principal I/O device.$PRINCIPAL$PDescription$PRINCIPAL contains the ID of the principal I/O device for the current process.$PRINCIPAL operates like $IO. Refer to $IO for details of specific device types and systemplatforms.If the principal device is closed, $PRINCIPAL does not change. If the principal input andoutput devices differ, $PRINCIPAL reflects the ID of the principal input device.This special variable cannot be modified using the SET command. Attempting to do so resultsin a error.ExamplesThis example uses $PRINCIPAL to test for a principal device.IF $PIECE($PRINCIPAL,"|",4) {WRITE "Principal device is: ",$PRINCIPAL }ELSE { WRITE "Undefined" }This example uses and writes to the principal device.USE $PRINCIPALWRITE "output to $PRINCIPAL"Notes$PRINCIPAL and USE 0$PRINCIPAL is functionally equivalent to the widely used, but non-standard, USE 0. Use$PRINCIPAL instead of USE 0 because it is standard, and because it makes your code moreflexible.See Also• USE command• $IO special variable442 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$QUIT$QUITContains a flag indicating what kind of QUIT is required to exit the current context.$QUIT$QDescription$QUIT contains a value that indicates whether an argumented QUIT command is requiredto exit from the current context. If an argumented QUIT is required to exit from the currentcontext, $QUIT contains a one (1). If an argumented QUIT is not required to exit from thecurrent context, $QUIT contains a zero (0).In a context created by issuing a DO or XECUTE command, an argumented QUIT is notrequired to exit. In a context created by a user-defined function, an argumented QUIT isrequired to exit.This special variable cannot be modified using the SET command. Attempting to do so resultsin a error.ExampleThe following example demonstrates $QUIT values in a DO context, in an XECUTE context,and in a user-defined function context.The sample code is as follows:QUIDO. WRITE !,"$QUIT in a DO context = ",$QUIT. QUITXECUTE "WRITE !,""$QUIT in an XECUTE context = "",$QUIT"SET A=$$AQUITA()WRITE !,"$QUIT in a User-defined function context =",$QUITQUIT 1A sample session using this code might run as follows:USER>DO ^QUI$QUIT in a DO context = 0$QUIT in an XECUTE context = 0$QUIT in a User-defined function context = 1<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 443


<strong>Caché</strong> <strong>ObjectScript</strong> Special VariablesNotes$QUIT and Error ProcessingThe $QUIT special variable is particularly useful during error processing when the sameerror handler can be invoked at context levels that require an argumented QUIT and at contextlevels that require an argumentless QUIT.See the Error Handling in Using <strong>Caché</strong> <strong>ObjectScript</strong> for more information about error processing.See Also• DO command• QUIT command• XECUTE command$ROLESContains the roles assigned to the current process.$ROLESDescription$ROLES contains the list of roles assigned to the current process. This list of roles consistsof a comma-separated string that can contain both User Roles and Added Roles.A role is assigned to a user either by using the SQL GRANT statement, or by using theSystem Management Portal's Security Management options to edit the definition of the Userto assign a role. A role can be defined using the SQL CREATE ROLE statement and deletedusing the SQL DROP ROLE statement. A role must be defined before it can be assigned toa user. A role can be revoked from a user using the SQL REVOKE statement.The $ROLES list does not contain a listing of roles assigned to roles. This hierarchicalassignment of roles is used within SQL exclusively, and is not available through <strong>Caché</strong> SystemSecurity.When a process is created using the JOB command, it inherits the same $ROLES and$USERNAME values as its parent process.444 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ROLESSET $ROLESYou can use the SET command to change the Added Roles part of the list contained in$ROLES. Setting $ROLES only alters a process' Added Roles. It can not alter its User Roles.To set $ROLES to a different list of Added Roles is a restricted system capability. However,such restrictions do not apply to setting $ROLES to a null string, which deletes the list ofAdded Roles.A role must be defined before it can be added. You can define a role using the SQL CREATEROLE command. CREATE ROLE does not give any privileges to a role. To assign privilegesto a role use either the SQL GRANT statement, or the System Management Portal interface.NEW $ROLESNEW $ROLES stacks the current values of both $ROLES and $USERNAME. You canuse the NEW command on $ROLES without security restrictions.ExamplesThe following example returns the list of roles for the current process.WRITE $ROLESThe following example first creates the roles Vendor, Sales, and Contractor. It then displaysthe comma-separated list of default roles (which contain both User Roles and Added Roles).The first SET $ROLES replaces the list of Added Roles with the two roles Sales and Contractor.The second SET $ROLES concatenates the Vendor role to the list of Added Roles.The final SET $ROLES sets the Added Roles list to the null string, removing all AddedRoles. The User Roles remain unchanged throughout:CreateRolesDO $SYSTEM.Security.Login("_SYSTEM","SYS")&sql(CREATE ROLE Vendor)&sql(CREATE ROLE Sales)&sql(CREATE ROLE Contractor)IF SQLCODE=0 {WRITE !,"Created new roles"GOTO SetRoles }ELSEIF SQLCODE=-118 {WRITE !,"Role already exists"GOTO SetRoles }ELSE { WRITE !,"CREATE ROLE failed, SQLCODE=",SQLCODE }SetRolesWRITE !,"Initial: ",$ROLESSET $ROLES="Sales,Contractor"WRITE !,"Replaced: ",$ROLESSET $ROLES=$ROLES_",Vendor"WRITE !,"Concatenated: ",$ROLESSET $ROLES=""WRITE !,"Nulled: ",$ROLES<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 445


<strong>Caché</strong> <strong>ObjectScript</strong> Special VariablesSee Also• <strong>Caché</strong> <strong>ObjectScript</strong>: SET command NEW command $USERNAME special variable• <strong>Caché</strong> SQL: CREATE ROLE DROP ROLE GRANT REVOKE %CHECKPRIV$STACKContains the number of context frames saved on the call stack.$STACK$STDescription$STACK contains the number for context frames currently saved on the call stack for yourprocess. You can also look at $STACK as the zero-based context level number of the currentlyexecuting context. Therefore, when a <strong>Caché</strong> job is started, before any contexts have beensaved on the call stack, the value of $STACK is zero (0).Each time a routine calls another routine with a DO command, the context of the currentlyexecuting routine is saved on the call stack and execution starts in the newly created contextof the called routine. The called routine can, in turn, call another routine and so on. Eachadditional call causes another saved context to be placed on the call stack.An XECUTE command and a user-defined function reference also establish a new executioncontext. A GOTO command does not.As new contexts are created by DO commands, XECUTE commands, or user-defined functionreferences, the value of $STACK is incremented. As contexts are exited with the QUITcommand, previous context are restored from the call stack and the value of $STACK isdecremented.This special variable cannot be modified using the SET command. Attempting to do so resultsin a error.$ESTACK is identical to $STACK, except that you can establish an $ESTACK level of 0(zero) at any point by issuing a NEW $ESTACK command. You cannot NEW the $STACKspecial variable.446 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


ExamplesThe following example demonstrates how the value of $STACK is incremented as newcontexts are create and decremented as contexts are exited.The sample code is as follows:STAWRITE !,"Context level in routine STA = ",$STACKDO AWRITE !,"Context level after routine A = ",$STACKQUITAWRITE !,"Context level in routine A = ",$STACKDO BWRITE !, "Context level after routine B = ",$STACKQUITBWRITE !,"Context level in routine B = ",$STACKXECUTE "WRITE !,""Context level in XECUTE = "",$STACK"WRITE !,"Context level after XECUTE = ",$STACKQUITA sample session using this code might run as follows:USER>DO ^STAContext level in routine STA = 1Context level in routine A = 2Context level in routine B = 3Context level in XECUTE = 4Context level after XECUTE = 3Context level after routine B = 2Context level after routine A = 1NotesContext levels in Application Mode and Programmer ModeA routine that is invoked in application mode starts at a different context level than a routineinvoked from the programmer mode prompt with a DO command. The DO command typedat the programmer mode prompt causes a new context to be created. The following exampleshows the routine START invoked in application mode and in programmer mode.Consider the following routine:START; Display the context level and exitWRITE !,"Context level in routine START is ",$STACKQUITWhen you run START in application mode, you see the following display:Context level in routine START is 0$STACK<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 447


<strong>Caché</strong> <strong>ObjectScript</strong> Special VariablesWhen you run START in programmer mode (by issuing DO ^START at the terminal prompt),you see the following display:Context level in routine START is 1See Also• $STACK function• $ESTACK special variable• Error Handling in Using <strong>Caché</strong> <strong>ObjectScript</strong>$STORAGEContains the number of bytes available for local variable storage.$STORAGE$SDescription$STORAGE returns the number of bytes available for local variable storage in the currentprocess partition. This value decreases as local variables are added to the local variable space,for example, by using the SET command. This value increases as local variables are removed,for example, by using the KILL command. The $STORAGE value is not affected by thesize of the current routine.To return the initial size of the local variable storage area, use the $ZSTORAGE specialvariable.This special variable cannot be modified using the SET command. Attempting to do so resultsin a error.See Also$ZSTORAGE special variable448 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$SYSTEM$SYSTEMContains system information about system objects.$SYSTEM$SYSTEM.class.method()Description$SYSTEM can be invoked as either a special variable, or as a class which invokes methodsthat return system information.$SYSTEM as a special variable contains the current system name and the name of the currentinstance of <strong>Caché</strong>, separated by a colon (:). These names are in uppercase letters, and if <strong>Caché</strong>is used in the name of your current instance of <strong>Caché</strong> it is spelled without an accent on thefinal letter. For example:MYCOMPUTER:CACHE2The same information can be returned using the $ZUTIL(131,1) function.$SYSTEM as a class provides access to a variety of system objects. You can invoke a methodthat returns information, or a method that performs some operation such as upgrading orloading and returns status information. <strong>Caché</strong> supports several classes of system objects,including the following:• Version: for version numbers of <strong>Caché</strong> and its components• SYS: for the system itself• OBJ: for Objects• SQL: for SQL queries• CSP: for <strong>Caché</strong> Server PagesNote that object class names and method names are case-sensitive. Specifying the wrong casefor these names generates a or error. If you do not specify parentheses with the method name, it generates a error.For further information on using $SYSTEM to access these objects, refer to the Using Objectswith <strong>Caché</strong> <strong>ObjectScript</strong> chapter of Using <strong>Caché</strong> Objects. $SYSTEM can access the System<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 449


<strong>Caché</strong> <strong>ObjectScript</strong> Special VariablesAPI classes in the %SYSTEM class library, described in the The <strong>Caché</strong> Class Library sectionof Using <strong>Caché</strong> Objects.ExamplesThe following is an example of using $SYSTEM to invoke a method that returns systeminformation:WRITE $SYSTEM.OBJ.Version()returns a string such as the following:Cache Objects Version 5.1.0.708Note that this objects version is not formatted the same as the system version number containedin the $ZVERSION special variable.You can list all of the methods for the OBJ class as follows. (By changing the class name,you can use this method to get a list for any system class):DO $SYSTEM.OBJ.Help()To list information about just one method in a class, specify the method name in the Helpargument list, as shown in the following example:DO $SYSTEM.OBJ.Help("Load")The following are a few more examples of $SYSTEM that invoke methods:DO $SYSTEM.OBJ.Upgrade()DO $SYSTEM.OBJ.ShowFlags()DO $SYSTEM.CSP.DisplayConfig()WRITE !,$SYSTEM.Version.GetPlatform()WRITE !,$SYSTEM.SYS.TimeStamp()The following example calls the same methods as the previous example, using the##class(%SYSTEM) syntax form:DO ##class(%SYSTEM.OBJ).Upgrade()DO ##class(%SYSTEM.OBJ).ShowFlags()DO ##class(%SYSTEM.CSP).DisplayConfig()WRITE !,##class(%SYSTEM.Version).GetPlatform()WRITE !,##class(%SYSTEM.SYS).TimeStamp()See Also• $ISOBJECT function• $ZUTIL(131) function• $ZVERSION special variable450 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$TEST• The <strong>Caché</strong> Class Library in Using <strong>Caché</strong> Objects• Using Objects with <strong>Caché</strong> <strong>ObjectScript</strong> in Using <strong>Caché</strong> Objects$TESTContains the truth value resulting from the last command using the time-out option.$TEST$TDescription$TEST contains the truth value (1 or 0) resulting from the last command with a time-out. Itcan be set by any command or function that can return a logical condition. Commands thatcan take a time-out value include JOB, LOCK, OPEN, READ, and CLOSE.$TEST is set by the following commands, regardless of whether they are entered from programmermode or encountered in routine code:• A timed READ sets $TEST to 1 if the read completes before the time-out expires. If thetime-out expires, $TEST is set to 0.• A timed LOCK sets $TEST to 1 if the lock attempt succeeds before the time-out expires.If the time-out expires, $TEST is set to 0.• A timed OPEN sets $TEST to 1 if the open attempt succeeds before the time-out expires.If the time-out expires, $TEST is set to 0.• A timed JOB sets $TEST equal to 1 if the attempt to start the new job succeeds beforethe time-out expires. If the time-out expires, $TEST is set equal to 0.Note:$TEST is also set by the obsolete legacy version of the IF command. It is neitherset nor checked by the current block-structured IF command. When the test expressionof a legacy IF command is evaluated, $TEST is set equal to the resulting truth value.In other words, if the IF expression tests true, $TEST is set to 1. If it tests false,$TEST is set to 0 (zero).This special variable cannot be modified using the SET command. Attempting to do so resultsin a error.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 451


<strong>Caché</strong> <strong>ObjectScript</strong> Special VariablesExampleThe following code performs a timed read and uses $TEST to test for completion of the read.READ a:10GOTO:$TEST x ; received dataELSE GOTO y ; did not receive dataNotesOperations That Do Not Set $TESTJOB, LOCK, OPEN, READ, and CLOSE commands without a time-out have no effect on$TEST. Postconditional expressions also have no effect on $TEST.The block-oriented IF command (which defines a block of code by enclosing it in curlybraces) does not use $TEST in any way. Some invocations of the legacy IF command alsodo not use $TEST: IF commands without an argument, and the ELSE command have noeffect on $TEST.Unsuccessful Timed Operations<strong>Caché</strong> does not produce an error message after an unsuccessful timed operation. Your applicationmust check $TEST and then produce an appropriate message.See Also• CLOSE command• JOB command• LOCK command• OPEN command• READ command• IF command• IF (legacy version) command452 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$TLEVEL$TLEVELContains the current nesting level for transaction processing.$TLEVEL$TLDescription$TLEVEL contains the current nesting level in transaction processing. The number ofTSTART commands issued before <strong>Caché</strong> encounters a TCOMMIT or TROLLBACKdetermines the nesting level. Each TSTART command increments $TLEVEL by 1. EachTCOMMIT command decrements $TLEVEL by 1. A TROLLBACK command resets$TLEVEL to 0.This special variable cannot be modified using the SET command. Attempting to do so resultsin a error.See Also• TCOMMIT command• TROLLBACK command• TSTART command• Using <strong>ObjectScript</strong> for Transaction Processing in Using <strong>Caché</strong> <strong>ObjectScript</strong>$USERNAMEContains the user name for the current process.$USERNAMEDescription$USERNAME contains the full user name for the current process. The full user name consistsof the name and system address of the current user; for example: Mary@jupiter.com. Youcannot use the SET command or the NEW command to modify this value. However, NEW$ROLES also stacks the current $USERNAME value.Commonly, the $USERNAME value is the user name specified at connection time. However,if unauthenticated access is permitted, a user terminal or an ODBC client may connect to<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 453


<strong>Caché</strong> <strong>ObjectScript</strong> Special Variables<strong>Caché</strong> without specifying a user name. In this case, $USERNAME contains the string“UnknownUser”.When a process is created using the JOB command, it inherits the same $USERNAME and$ROLES values as its parent process.A user name can be created using the SQL CREATE USER statement and deleted using theSQL DROP USER statement. A user password can be changed using the SQL ALTERUSER statement. A user can have roles assigned to it, either by using the SQL GRANTstatement, or by using system utilities to add a role to the user. You can access the list ofroles assigned to the current process with the $ROLES special variable. A role can be revokedfrom a user using the SQL REVOKE statement.ExamplesThe following example returns the full user name for the current process.WRITE $USERNAMEThe following example returns the default schema name for the current process.WRITE $PIECE($USERNAME,"@")See Also• <strong>Caché</strong> <strong>ObjectScript</strong> $ROLES special variable• <strong>Caché</strong> SQL: CREATE USER DROP USER ALTER USER GRANT REVOKE%CHECKPRIV$XContains the current horizontal position of the cursor.$XDescription$X contains the current horizontal position of the cursor. As characters are written to a device,<strong>Caché</strong> updates $X to reflect the horizontal cursor position.Each printable character that is output increments $X by 1. A carriage return (ASCII 13) orform feed (ASCII 12) resets $X to 0 (zero).454 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$X$X is a 16-bit unsigned integer.• On non-Unicode systems, $X wraps to 0 when its value reaches 65536. In other words,if $X is 65535, the next output character resets it to 0.• On Unicode systems, $X wraps to 0 when its value reaches 16384 (the two remainingbits are used for Japanese pitch encoding).You can use the SET command to give a value to $X and $Y. For example, you may usespecial escape sequences that alter the physical cursor position without updating the $X and$Y values. In this case, use SET to assign the correct values to $X and $Y after you use theescape sequences.NotesNLS Character MappingThe National Language Support (NLS) utility $X/$Y tab defines the $X and $Y cursormovement characters for the current locale. For further details, refer to Customized NationalLanguage Translations.$X with Terminal I/OThe following table shows the effects of different characters on $X.Echoed CharacterAny printable ASCIIcharacterNonprintable characters(such as escape sequences)ASCII Code1213108932-126127-255Effect on $X$X=0$X=0$X=$X$X=$X-1$X=$X+1$X=$X+1See Using <strong>Caché</strong> <strong>ObjectScript</strong>.The S(ecret) protocol of the OPEN and USE commands turns off echoing. It also prevents$X from being changed during input, so it indicates the true cursor position.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 455


<strong>Caché</strong> <strong>ObjectScript</strong> Special VariablesBecause WRITE * does not change $X, you can send a control sequence to your terminaland $X will still reflect the true cursor position. Since some control sequences do move thecursor, you can use the SET command to set $X directly. For example, the following commandsmove the cursor to column 20 and line 10 on a Digital VT100 terminal (or equivalent)and set $X and $Y accordingly:SET dy=10,dx=20WRITE *27,*91,dy+1,*59,dx+1,*72SET $Y=dy,$X=dxANSI standard control sequences (such as escape sequences) that the device acts on but doesnot output can produce a discrepancy between the $X and $Y values and the true cursorposition. To avoid this problem use the WRITE * (integer expression) syntax and specifythe ASCII value of each character in the string. For example, instead of using:WRITE !,$CHAR(27)_"[1m"WRITE !,$Xuse this equivalent form:WRITE !,*27,*91,*49,*109WRITE !,$XAs a rule, after any escape sequence that explicitly moves the cursor, you should update $Xand $Y to reflect the actual cursor position.$X with Interprocess and Interjob CommunicationWhen you use the WRITE command to send data to either a client or server TCP device,<strong>Caché</strong> first stores the data in a buffer. It also updates $X to reflect the number of charactersin the buffer. It does not include the ASCII characters and inthis count because they are considered to be part of the record.If you flush the $X buffer with the WRITE ! command, <strong>Caché</strong> resets $X to 0 and incrementsthe $Y value by 1. If you flush the $X and $Y buffers with the WRITE # command, <strong>Caché</strong>writes the ASCII character as a separate record and resets both $X and $Yto 0.See Also• WRITE command• $Y special variable• $ZUTIL(68,22) $X Update Mode for Escape Sequences function• $ZUTIL(69,22) $X Update Mode for Escape Sequences function456 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$Y• I/O Devices and Commands in <strong>Caché</strong> I/O Device Guide• Terminal I/O in <strong>Caché</strong> I/O Device Guide• Interprocess Communication in <strong>Caché</strong> I/O Device Guide$YContains the current vertical position of the cursor.$YDescription$Y contains the current vertical position of the cursor. As characters are written to a device,<strong>Caché</strong> updates $Y to reflect the vertical cursor position.Each line feed (newline) character (ASCII 10) that is output increments $Y by 1. A form feedcharacter (ASCII 12) resets $Y to 0.$Y is a 16-bit unsigned integer. $Y wraps to 0 when its value reaches 65536. In other words,if $Y is 65535, the next output character resets it to 0.You can use the SET command to give a value to $X and $Y. For example, you may usespecial escape sequences that alter the physical cursor position without updating the $X and$Y values. In this case, use SET to assign the correct values to $X and $Y after you use theescape sequences.NotesNLS Character MappingThe National Language Support (NLS) utility $X/$Y tab defines the $X and $Y cursormovement characters for the current locale. For further details, refer to Customized NationalLanguage Translations.$Y with Terminal I/OThe following table shows the effects of different characters on $Y.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 457


<strong>Caché</strong> <strong>ObjectScript</strong> Special VariablesEchoed CharacterAny printable ASCIIcharacterASCII Code1213108932-126Effect on $Y$Y=0$Y=$Y$Y=$Y+1$Y=$Y$Y=$Y$Y=$YThe S(ecret) protocol of the OPEN and USE commands turns off echoing. It also prevents$Y from being changed during input, so it indicates the true cursor position.Because WRITE * does not change $Y, you can send a control sequence to your terminaland $Y will still reflect the true cursor position. Since some control sequences do move thecursor, you can use the SET command to set $Y directly. For example, the following commandsmove the cursor to column 20 and line 10 on a VT100-type terminal and set $X and$Y accordingly:SET dy=10,dx=20WRITE *27,*91,dy+1,*59,dx+1,*72SET $Y=dy,$X=dxANSI standard control sequences (such as escape sequences) that the device acts on but doesnot output can produce a discrepancy between the $X and $Y values and the true cursorposition. To avoid this problem, use the WRITE * statement and specify the ASCII valueof each character in the string. For example, instead of using the following code:WRITE $CHAR(27)_"[1m"use this equivalent form:WRITE *27,*91,*49,*109As a rule, after any escape sequence that explicitly moves the cursor, you should update $Xand $Y to reflect the actual cursor position.See Also• $X special variable• I/O Devices and Commands in <strong>Caché</strong> I/O Device Guide458 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZA• Terminal I/O in <strong>Caché</strong> I/O Device Guide• Interprocess Communication in <strong>Caché</strong> I/O Device Guide$ZAContains the status of the last READ on the current device.$ZADescription$ZA contains the status of the last READ on the current device.This special variable cannot be modified using the SET command. Attempting to do so resultsin a error.Notes$ZA with Terminal I/O$ZA is implemented as a sequence of bit flags, with each bit indicating a specific piece ofinformation. The following table shows the possible values, their meanings, and how to testthem.Bit01289101112Test$ZA#2$ZA\2#2$ZA\4#2$ZA\256#2$ZA\512#2$ZA\1024#2$ZA\2048#2$ZA\4096#2MeaningA arrived, whether or not breaks were enabled.The READ timed out.I/O error.<strong>Caché</strong> detected an invalid escape sequence.The hardware detected a parity or framing error.VMS only: Data overrun error.The process is disconnected from its principal device.For COM ports: CTS (Clear To Send). A signal sent fromthe modem to its computer indicating that transmission canproceed. For TCP devices: the device is functioning inServer mode.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 459


<strong>Caché</strong> <strong>ObjectScript</strong> Special VariablesBit1314151617181920212224 &25Test$ZA\8192#2$ZA\16384#2$ZA\32768#2$ZA\65536#2$ZA\131072#2$ZA\262144#2$ZA\524288#2$ZA\1048576#2$ZA\2097152#2$ZA\4194304#2$ZA\16777216#4MeaningFor COM ports: DSR (Data Set Ready). A signal sent fromthe modem to its computer indicating that it is ready tooperate. For TCP devices: the device is currently in theConnected state talking to a remote host.Ring set if TRUE.Carrier detect set if TRUE.CE_BREAK COM port error state.CE_FRAME COM port error state.CE_IOE COM port error state.CE_OVERRUN COM port error state.CE_RXPARITY COM port error state.CE_TXFULL COM port error state.TXHOLD COM port error state. Set if any of the followingfields are true in the error mask returned byClearCommError(): fCtsHold, fDsrHold, fRlsdHold,fXoffHold, fXoffSent.<strong>Caché</strong> requested DTR (Data Terminal Ready) setting:0=DTR off. 1=DTR=on. 2=DTR handshaking. When set(1), indicates readiness to transmit and receive data.While many of the conditions that $ZA shows are errors, they do not interrupt the program'sflow by trapping to $ZTRAP. (A with breaks enabled traps to $ZTRAP.) Aprogram concerned with these errors must check $ZA after every READ.COM ports use bits 12 through 15, 24 and 25 to report the status of modem control pins. Thiscan be done regardless of whether <strong>Caché</strong> modem control checking is on or off for the port.A user can enable or disable $ZA error reporting for COM ports by setting the OPEN orUSE command portstate parameter (byte 8, to be specific). If error reporting is enabled, theport error state is reported in bits 16 through 22. For further details, see Terminal I/O in <strong>Caché</strong>I/O Device Guide.$ZA With Magnetic Tape I/OWith magnetic tape I/O, the bit fields in $ZA indicate errors and special conditions. <strong>Caché</strong>updates $ZA after each command that references the magnetic tape device.460 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZAThe following table shows the meanings of the $ZA bits for magnetic tape I/O. Note the Trapcolumn. The letter Y indicates a error. If you have set the $ZTRAP variable,<strong>Caché</strong> issues the associated $ZTRAP error code.BitValueTrapMeaningNotes01YLogical Error(mixed Readsand Writes)To switch between reading and writing, eitherClose and then Open the device or issue aForward Space, Backspace, or Rewindcommand.24NWriteProtectedReflects the state of the OPEN or USEread-only parameter at all times. This bitdoes not reflect the state of the tape'sphysical write protection (write ring or writelock) because many versions of UNIX giveno notice of tape write protection until anactual write to tape is attempted. If youattempt to open a write-protected 9-track tapewithout the read-only parameter, <strong>Caché</strong> setsthis bit and opens the tape as read only. Noerror occurs.38YErrorSummaryThe error summary is the logical OR of allconditions that cause a <strong>Caché</strong> error (allconditions marked Y under Trap)532NBeginning ofTape [BOT]On UNIX systems this bit is set upon rewind,and cleared when tape is opened.664NOn Line7128YController ordrive error101024NEnd of Tape[EOT]Not supported on most UNIX platforms.1416384YTape Mark<strong>Caché</strong> sets the Tape Mark bit when itencounters a tape mark on Read, ReadBlock, Forward Space or Backspace. Thissets the Error Summary bit and traps to$ZTRAP on Read, Read Label, and ReadBlock1532768YTape NotReady<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 461


<strong>Caché</strong> <strong>ObjectScript</strong> Special VariablesSome bits indicate error conditions, while other bits indicate conditions that do not necessarilyproduce an error. To monitor these non-error conditions, your program must test the appropriatebit of $ZA after every magnetic tape operation. For example, if your program mightwrite beyond the end of the tape, it must check bit 10 (End of Tape).To test a bit, integer divide $ZA by the value listed for that bit in the table and perform amodulo 2 operation. For example, the following command checks if bit 14 (Tape Mark) isset:USE 47 IF $ZA\16384#2 {DO Endfile}where 16384 equals 2 to the 14th power and #2 indicates the modulo 2 operation. Since anynumber to the 0 power equals 1, you do not need a divisor to check bit 0 (Logical Error). Forexample:USE 47 GOTO Logerr:$ZA#2See Also• READ command• $ZUTIL(68,15) Modem Disconnect Detection function• $ZB special variable• $ZTRAP special variable• I/O Devices and Commands in <strong>Caché</strong> I/O Device Guide• Terminal I/O in <strong>Caché</strong> I/O Device Guide• Magnetic Tape I/O in <strong>Caché</strong> I/O Device Guide• Sequential File I/O in <strong>Caché</strong> I/O Device Guide$ZBContains status information for the current I/O device.$ZBDescription$ZB contains status information specific to the current I/O device following a READ operation.462 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


• When reading from a terminal, sequential file, or other character-based I/O device, $ZBcontains the terminating character of the read operation. This can be a terminator character(such as ), the final character of the input data if the read operation does notrequire a terminator character, or the null string if a terminator character is required butwas not received (for example, if the read operation timed out).• When reading from a block-based I/O device, such as magnetic tape, $ZB contains thenumber of bytes remaining in the I/O buffer. $ZB also contains the number of bytes inthe I/O buffer when writing to magnetic tape.This special variable cannot be modified using the SET command. Attempting to do so resultsin a error.$ZB and $KEY can both be used to return the READ termination character when readingfrom a character-based device or file. For character-based reads, these two special variablesare very similar, but not identical. For block-based reads and writes (such as magnetic tape)use $ZB; $KEY does not provide support for block-based read and write operations. See$KEY for further details.NotesReading from a Terminal or File$ZB contains the terminating character (or character sequence) from a read operationinvolving a terminal, sequential file, or other character-based I/O device. $ZB can containany of the following:• A termination character, such as a carriage return.• An escape sequence (up to 16 characters).• The nth character in a fixed-length READ x#n. (In this case, the $KEY special variablereturns the null string.)• The single character of READ *x.• A null string ("") after a timed READ expires.For example, consider the following variable-length read with a five-second timeout:ZbreadREAD !,"Enter number:",num:5WRITE !, numWRITE !, $ASCII($ZB)QUIT$ZB<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 463


<strong>Caché</strong> <strong>ObjectScript</strong> Special VariablesIf the user types 123 at the READ prompt and presses , <strong>Caché</strong> stores 123 in thenum variable and stores (ASCII decimal code 13, hexadecimal 0D) in $ZB. Ifthe READ times out, $ZB contains the null string; $ASCII("") returns a value of –1.$ZB on the Command LineWhen issuing commands interactively from the <strong>Caché</strong> Terminal command line, you press to issue each command line. The $ZB and $KEY special variables record thiscommand line terminator character. Therefore, when using $ZB or $KEY to return the terminationstatus of a read operation, you must set a variable as part of the same command line.For example, if you issue the command:>READ x:10from the command line, then check $ZB it will not contain the results of the read operation;it will contain the character that executed the command line. To return the resultsof the read operation, set a local variable with $ZB in the same command line, as follows:>READ x:10 SET rzb=$ZBThis preserves the value of $ZB set by the read operation. To display this read operationvalue, issue either of the following command line statements:>WRITE $ASCII(rzb); returns -1 for null string (time out),; returns ASCII decimal value for terminator character>ZZDUMP rkey; returns blank line for null string (time out); returns hexadecimal value for terminator character$ZB with Magnetic Tape I/O$ZB contains status information about the driver buffer. Specifically, it contains the numberof bytes that remain in the magnetic tape drive's internal buffer.Immediately after you read a block, <strong>Caché</strong> sets $ZB to that block's size. As you transferlogical records from the buffer to variables (with READ commands), <strong>Caché</strong> decrements the$ZB value until it reaches 0 and the next block read occurs.When you write to tape, $ZB shows the available space (in bytes) remaining in the driver'sinternal buffer. Immediately after you write a block, <strong>Caché</strong> sets $ZB to the buffer size specifiedwith the OPEN command. As you transfer logical records from <strong>Caché</strong> variables into thebuffer (with WRITE commands), <strong>Caché</strong> decrements the $ZB number until it reaches 0 andthe block write occurs.464 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


Most magnetic tape programs need not be concerned with $ZB unless they must deal withunusual formats and variable length blocks.To monitor magnetic tape operations, your program can test the appropriate bit of $ZA aftereach read and write.The following code checks both $ZA and $ZB after each magnetic tape read, and sets MTERRwhen either of these variables indicates an error. It also sets $ZTRAP when a magnetic tapeerror occurs.; $$MTIN(mtdev) = the next logical record from magtape; device mtdev.; Also returns za=$ZA and zb=$ZB; On a magtape error, mterr=1 and $$MTIN(mtdev)=""; Expects the caller to have set $ZT to trap other; errors.MTIN(io)NEW rec,curdevSET mterr=0,curdev=$IO,$ZT="MTIERR"USE ioREAD recMTIEXITSET za=$ZA,zb=$ZBUSE curdevQUIT recMTIERRIF $ZERROR["MAGTAPE" {USE curdevZQUIT 1GOTO @$ZTRAP }; Use caller's error trap.ELSE {SET $ZTRAP="",mterr=1,rec=""GOTO MTIEXIT }If a terminator completes a READ, <strong>Caché</strong> mode returns the terminator as a string in $ZB.If an escape sequence terminates a READ, <strong>Caché</strong> mode returns the ASCII escape sequenceas a string in $ZB.See Also• READ command• WRITE command• $KEY special variable• $ZA special variable• $ZEOF special variable• I/O Devices and Commands in <strong>Caché</strong> I/O Device Guide• Terminal I/O in <strong>Caché</strong> I/O Device Guide$ZB<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 465


<strong>Caché</strong> <strong>ObjectScript</strong> Special Variables• Magnetic Tape I/O in <strong>Caché</strong> I/O Device Guide• Sequential File I/O in <strong>Caché</strong> I/O Device Guide• The Spool Device in <strong>Caché</strong> I/O Device Guide$ZCHILDContains the ID of the last child process.$ZCHILD$ZCDescription$ZCHILD contains the ID of the last child process that the current process created with theJOB command. If your process hasn't used JOB to create a child process, $ZCHILD returns0 (zero).In MSM language mode, the $ZC special variable (spelled as shown) has a different use. Itis used for determining end-of-file in sequential file reads.This special variable cannot be modified using the SET command. Attempting to do so resultsin a error.Notes$ZCHILD and the Successful Starting of Jobs$ZCHILD being set does not mean that the job was successfully started. It only means thatthe process was created and the parameters were passed successfully.For example, if you use JOB to spawn a routine that does not exist, both $TEST and$ZCHILD report that the JOB command succeeded, although that new job immediately dieswith a error.$ZC in MSM Language ModeMSM language mode supports a special use of the $ZC special variable.If you have set the current language mode to MSM using $ZUTIL(55,8), the $ZC specialvariable is set during sequential file reads. This provides compatibility with the MSM $ZCvariable. (In all other language modes, $ZC is not set during file reads; $ZC is an abbreviationfor $ZCHILD and has a completely different functionality.)466 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZCHILDIn MSM language mode, a successful sequential file read sets $ZC=0.In MSM language mode, an end-of-file condition sets $ZC=–1 (negative 1). An error does not occur.However, <strong>Caché</strong> $ZC is not identical to the MSM $ZC:MSM sets its $ZC=–1 (negative 1) if the last line of the file is not terminated with thedelimiter character(s). <strong>Caché</strong> does not check for delimiter characters; it sets $ZC=0 insteadof –1 in this case.MSM sets its $ZC=1 if an I/O error occurs during a read. <strong>Caché</strong> does not support this functionality;instead, <strong>Caché</strong> issues a error.See AlsoChild processes:• JOB command• ^$JOB structured system variable• $JOB special variable• $TEST special variable• $ZPARENT special variableMSM language mode:• $ZUTIL(55) Language Mode Switch function• $ZPOS special variable• $ZEOF special variable• Sequential File I/O in <strong>Caché</strong> I/O Device Guide<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 467


<strong>Caché</strong> <strong>ObjectScript</strong> Special Variables$ZEOFContains flag indicating whether end-of-file has been reached.$ZEOFDescriptionFollowing each sequential file READ, <strong>Caché</strong> sets the $ZEOF special variable to indicatewhether or not the end of the file has been reached. This special variable is provided forcompatibility with MSM routines that use $ZC device status checking.$ZEOF can be set to the following values:–1 End-of-file reached0 Not at end-of-fileTo use this feature, you must disable the error for sequential files.• To disable this for a process, call $ZUTIL(68,40,1) for that process.• To disable this system-wide, either call $ZUTIL(69,40,1), or go to the System ManagementPortal, select System Configuration, select Advanced Settings, on the pull-downCategory list select <strong>ObjectScript</strong>. View and edit the current setting of SetZEOF. Thisoption controls the behavior when <strong>Caché</strong> encounters an unexpected end-of-file whenreading a sequential file. When set to “true” , <strong>Caché</strong> sets the $ZEOF special variable toindicate that you have reached the end of the file. When set to “false” , <strong>Caché</strong> issues an error. The default is “false” .When the end of a file is reached, rather than returning an error, the READwill return a null string, set $ZPOS=null and set $ZEOF=–1.$ZEOF does not support all of the features of the MSM $ZC function. Unlike $ZC, $ZEOFdoes not identify file delimiter characters or I/O errors. $ZEOF does not check for properfile termination with file delimiter characters. I/O errors are detected by a READ commanderror, not by $ZEOF.This special variable cannot be modified using the SET command. Attempting to do so resultsin a error.See Also• $ZUTIL(68,40) End-of-File Handling for Sequential Files function468 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZERROR• $ZUTIL(69,40) End-of-File Handling for Sequential Files function• $ZCHILD special variable• $ZPOS special variable• Sequential File I/O in <strong>Caché</strong> I/O Device Guide$ZERRORContains the name and location of the last error.$ZERROR$ZEDescription$ZERROR contains the name of the most recent error, the location of the most recent error(where applicable), and (for certain error codes) additional information about what causedthe error. $ZERROR always contains the most recent error for the appropriate languagemode.The string contained in $ZERROR can be in any of the following forms:entryref infoentryref infoentryrefinfoThe error name. The error name is always returned in all capital letters,enclosed in angle brackets. It may contain blank spaces.A reference to the line of code in which the error occurred. This consistsof the routine name and line offset within that routine, followed by a ^and the program name.This entryref follows immediately after the closingangle bracket of the error name. When invoking $ZERROR from <strong>Caché</strong>Terminal, this entryref information is not meaningful, and is therefore notreturned.Additional information specific to certain error types (see table below).This information is separated from or entryref by a blankspace. If there are multiple components to info, they are separated by acomma.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 469


<strong>Caché</strong> <strong>ObjectScript</strong> Special VariablesFor example, a program (named zerrortest) contains the following routine (named ZerrorMain)which attempts to write the contents of FRED, an undefined local variable:ZerrorMainWRITE !, $ZERRORWRITE FREDWRITE !, $ZERRORQUITIn the above example, the first $ZERROR contains a null string (""), because no errors haveoccurred. The second $ZERROR contains *FRED, specifying the name ofthe error and additional information specific to that type of error. In this case, the informationis the name of the undefined local variable FRED.Notes$ZERROR and the Program StackThe portion of the $ZERROR string contains the most recent error message. Thecontents of the entryref portion of the $ZERROR string reflect the stack level of the mostrecent error. The following terminal session attempts to call the nonsense command GOB-BLEDEGOOK, resulting in a error. It also runs ZerrorMain (specified above),resulting in the $ZERROR value . Subsequent $ZERROR values duringthis terminal session reflect this program call, as shown in the following:SAMPLES>gobbledegookSAMPLES>WRITE $ZERRORSAMPLES>DO ^zerrortestSAMPLES>WRITE $ZERRORZerrorMain+2^zerrortest *FREDSAMPLES 2d0>gobbledegookSAMPLES 2d0>WRITE $ZERROR^zerrortestSAMPLES 2d0>QUITSAMPLES>WRITE $ZERROR^zerrortestSAMPLES>gobbledegookSAMPLES>WRITE $ZERROR$ZERROR Actions when $ZTRAP is SetWhen an error occurs and $ZTRAP is set, <strong>Caché</strong> returns the error message in $ZERRORand branches to the error-trap handler specified for $ZTRAP. (For a list of the possible errortexts, refer to System Error Messages in <strong>Caché</strong> Error <strong>Reference</strong>.)470 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZERRORAdditional Information For Some ErrorsWhen certain types of errors occurs, <strong>Caché</strong> returns the error in the following format: infoThe info component contains additional information about what caused the error. The infocomponent of $ZERROR is provided at <strong>Caché</strong> 5.1 and subsequent versions.The following table gives a list of errors that include additional info and the format of thatinformation. The error code is separated from the info component by a space character.Error CodeInfo ComponentThe name of the undefined variable (including any subscriptsused). This may be a local variable, a process-private global,or a global. Local variable names are prefixed by an asterisk.The subscript reference in error.Prefixed by an asterisk, the referenced routine name.Prefixed by an asterisk, the referenced class name.Prefixed by an asterisk, the name of the referenced property,followed by a comma separator and the class name it issupposed to be in.Prefixed by an asterisk, the name of the method invoked,followed by a comma separator and the class name it issupposed to be in.The name of the global referenced and the name of the directorycontaining it, separated by a comma.The names of variables local to routines (or methods), as well as the names of undefinedroutines, classes, properties, and methods, are prefixed with an asterisk (*). Process-privateglobals are identified by their ^|| prefix. Global variables are identified by their ^ (caret) prefix.Class names are presented in their %-prefix form.The following examples show additional error information specifying the cause of the error.In each case, the specified item does not exist. Note that the info component of the generatederror is separated from the error name by a blank space. The asterisk (*) indicates a localvariable, a class, a property, or a method. The caret (^) indicates a global, and ^|| indicates aprocess-private global.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 471


<strong>Caché</strong> <strong>ObjectScript</strong> Special VariablesExamples of errors:WRITE x *xWRITE abc(2) *abc(2)WRITE ^xyz(1,1) ^xyz(1,1)WRITE ^|"samples"|xyz(1,2) ^xyz(1,2)WRITE ^||ppg(1) ^||ppg(1)WRITE ^|"^"|ppg(2) ^||ppg(2)// undefined local variable// undefined subscripted local variable// undefined global// undefined global with namespace specification// undefined process-private global// undefined process-private globalExample of a error:SET $ZUTIL(68,1,0)WRITE ^abc("") ^abc("")Examples of errors:DO ^NotThere *NotThereJOB ^NotThere *NotThereGOTO ^NotThere *NotThereExamples of object errors:WRITE $SYSTEM.XXQL.MyMethod() *%SYSTEM.XXQLWRITE $SYSTEM.SQL.MyMethod() *MyMethod,%SYSTEM.SQL *SomeProp,Package.ClassnameExample of a error:SET ^a="fruit"SET ^a(1)="apple"SET x=$ZUTIL(68,28,1) // disable global root node killsKILL ^a(1)KILL ^a// attempting to kill a global root node ^a,c:\cachesys\mgr\userPre-5.1 Error Handling CodeA consequence of adding an info component to these error codes is that pre-5.1 error handlingroutines that made assumptions about the format of the string in $ZERROR may requireredesign to work as before. For example, the following will no longer work in version 5.1:WRITE "Error line: ", $PIECE($ZERROR, ">", 2)and should be changed to be something like:WRITE "Error line: ", $PIECE($PIECE($ZERROR, ">", 2), " ", 1)472 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZHOROLOGSetting $ZERRORYou can set $ZERROR with the SET command to a value of up to 128 characters only in<strong>Caché</strong> mode.See Also• ZTRAP command• $ECODE special variable• $ZTRAP special variable• Error Handling chapter in Using <strong>Caché</strong> <strong>ObjectScript</strong>• System Error Messages in <strong>Caché</strong> Error <strong>Reference</strong>$ZHOROLOGContains the number of seconds elapsed since <strong>Caché</strong> startup.$ZHOROLOG$ZHDescription$ZHOROLOG contains the number of seconds that have elapsed since the most recent <strong>Caché</strong>startup. This is a count, which is independent of clock changes and day boundaries. The valueis expressed as a floating point number, indicating seconds and fractions of a second. Thenumber of decimal digits is platform-dependent. $ZHOROLOG truncates trailing zeros inthis fractional portion.This special variable cannot be modified using the SET command. Attempting to do so resultsin a error.Note:Because of a limitation in the Windows operating system, putting your Windowssystem into hibernate or standby mode may cause $ZHOROLOG to return unpredictablevalues. This problem does not affect $HOROLOG or $ZTIMESTAMPvalues.ExamplesThis example outputs the current $ZHOROLOG value.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 473


<strong>Caché</strong> <strong>ObjectScript</strong> Special VariablesWRITE $ZHOROLOGreturns a value such as: 1036526.244932.The following example shows how you might use $ZHOROLOG to time events and dobenchmarks. This example times an application through 100 executions, then finds the averagerun time.CycletimeSET start=$ZHOROLOGFOR i=1:1:100 { DO Myapp }SET end=$ZHOROLOGWRITE !,"Average run was ",(end-start)/100," seconds."QUITMyappWRITE !,"executing my application"; application code goes hereQUITSee Also• $ZUTIL(188) Local Date/Time with Fractional Seconds function• $HOROLOG special variable• $ZTIMESTAMP special variable$ZIOContains information about the current terminal I/O device.$ZIO$ZIDescription$ZIO contains information about the current I/O device.For a terminal device that is a <strong>Caché</strong> terminal, $ZIO contains the string “TRM:”. For a terminaldevice that is an MS-DOS console, $ZIO contains the string “CON:”.If the current terminal device is connected remotely, $ZIO contains information about theremote connection.For a terminal device connected to a LAT, $ZIO contains the following:server/port474 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZIOserverportThe LAT server nameThe LAT port nameFor a terminal device connected through TELNET, $ZIO contains the following:host/porthostportThe remote host IP address, usually in the form:nnn.nnn.nnn.nnnThe remote IP port number.If the current device is not a terminal:• If a file, $ZIO contains the file's fully-canonized pathname.• If not a file, $ZIO contains the null string.The following example returns the current device information:SET x=$CASE($ZIO,"TRM:":"a terminal","CON:":"a console","":"neither terminal nor file")WRITE "The current device is ",xThis special variable cannot be modified using the SET command. Attempting to do so resultsin a error.See Also• $IO special variable• $PRINCIPAL special variable• I/O Devices and Commands in <strong>Caché</strong> I/O Device Guide• Terminal I/O in <strong>Caché</strong> I/O Device Guide<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 475


<strong>Caché</strong> <strong>ObjectScript</strong> Special Variables$ZJOBContains job status information.$ZJOBDescription$ZJOB contains a number in which each bit represents one particular aspect of the job's status.To test $ZJOB, reference it as $ZJOB\x#2, where x is a value used to test the bit. The followingtable shows the layout of the bits, their test values, and meanings.Bit12481024Value1010101010MeaningJob started in programmer modeJob started in application modeJob started by the JOB commandJob started by signing on either in application or programmer mode enabled for all terminal lines disabled except for terminal lines for which has been explicitly enabled by OPEN or USEcommands received and pending not received. The value 8 is cleared by the OPENand USE commands and by an error trap caused by a Journaling is disabled regardless of other conditions.Journaling is enabled for this job if other conditions indicatejournaling.This special variable cannot be modified using the SET command. Attempting to do so resultsin a error.See Also• JOB command• ^$JOB structured system variable• $JOB special variable476 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZMODE• $ZCHILD special variable• $ZPARENT special variable$ZMODEContains current I/O device OPEN parameters.$ZMODEDescription$ZMODE contains the parameters specified with the OPEN or USE command for the currentdevice. The string returned contains the parameters used to open the current I/O device incanonized form. These parameter values are separated by backslash delimiters. Openparameters like "M" on TCP/IP IO are canonized to "PSTE". The "Y" and "K" parametervalues are always placed last.This special variable cannot be modified using the SET command. Attempting to do so resultsin a error.ExamplesThe following example sets parameters for the current device with the USE command. Itchecks the current parameters with $ZMODE before and after the USE command. To testwhether a specific parameter was set, this example uses the $PIECE function with thebackslash delimiter, and tests for a value using the binary contains operator ([):ZmodetestWRITE !, $ZMODEIF $PIECE($ZMODE,"\\")["S" {WRITE !, "S is set" }ELSE {WRITE !, "S is not set" }USE 0:("":"IS":$CHAR(13,10))WRITE !, $ZMODEIF $PIECE($ZMODE,"\\")["S" {WRITE !, "S is set" }ELSE {WRITE !, "S is not set" }QUITSAMPLES>DO ^zmodetestRY\Latin1\K\UTF8\S is not setSIRY\Latin1\K\UTF8\<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 477


<strong>Caché</strong> <strong>ObjectScript</strong> Special VariablesS is setSee Also• OPEN command• USE command• $IO special variable• I/O Devices and Commands in <strong>Caché</strong> I/O Device Guide$ZNAMEContains the current routine name.$ZNAME$ZNDescription$ZNAME contains the routine name of the current process. Routine names are case-sensitive.If no routine is currently executing, $ZNAME contains a null string.This special variable cannot be modified using the SET command. Attempting to do so resultsin a error.To return the routine name for a specified process, use a SYS.Process class method, as shownin the following example:ZNSPACE "%SYS"WRITE ##CLASS(SYS.Process).%OpenId($JOB).RoutineGet()The $ZNAME value can be set by the any of the following commands:• ZLOAD command• ZSAVE command• Argumentless ZREMOVE command (sets to a null string)• DO command• GOTO command478 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


See Also• $ZUTIL(67,5)—Return the routine name of a specified process legacy function$ZNSPACE$ZNSPACEContains the current namespace name.$ZNSPACEDescription$ZNSPACE contains the name of the current namespace. By setting $ZNSPACE, you canchange the current namespace.To obtain the current namespace name:WRITE $ZNSPACEYou can also obtain the name of the current namespace by invoking a system method, asfollows:WRITE $SYSTEM.SYS.NameSpace()Refer to the %SYSTEM.SYS section of the <strong>Caché</strong> Class <strong>Reference</strong> for further details.You can change the current namespace using a ZNSPACE command, a SET $ZNSPACEcommand, or the $ZUTIL(5) function. For UNIX and OpenVMS, the default namespace isestablished as a System Configuration option. For Windows systems, it is set using a commandlinestart-up option.You can use the SET command to change the value of $ZNSPACE. This sets the currentnamespace for the process. Specify the new namespace as a quoted string. You can specifyan explicit namespace ("namespace") or an implied namespace ("^system^dir" or"^^dir").Namespace names are case-insensitive. <strong>Caché</strong> always displays explicit namespace names inall uppercase letters, and implied namespace names in all lowercase letters.If you specify the current namespace, SET $ZNSPACE performs no operation and returnsno error. If you specify an undefined namespace, SET $ZNSPACE generates a error. You can test whether a namespace is defined by using $ZUTIL(90,10).This use of SET $ZNSPACE is identical to the ZNSPACE command.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 479


<strong>Caché</strong> <strong>ObjectScript</strong> Special VariablesTo obtain the namespace name of a specified process, use a SYS.Process class method, asshown in the following example:ZNSPACE "%SYS"WRITE ##CLASS(SYS.Process).%OpenId($JOB).NameSpaceGet()ExampleIn the following example, if the current namespace is not USER, a SET $ZNSPACE commandchanges the current namespace to USER. Note that because of the IF test, the namespacemust be specified in all uppercase letters.SET ns="USER"IF $ZNSPACE=ns {WRITE !,"Namespace already was ",$ZNSPACE }ELSEIF 1=$ZUTIL(90,10,ns) {WRITE !,"Namespace was ",$ZNSPACESET $ZNSPACE=nsWRITE !,"Set namespace to ",$ZNSPACE }ELSE { WRITE !,ns," is not a defined namespace" }QUITSee Also• SET command• ZNSPACE command• Configuring Namespaces in <strong>Caché</strong> System Administration Guide$ZORDERContains the value of the next global node.$ZORDER$ZODescription$ZORDER contains the value of the next global node (in $QUERY sequence, not $ORDERsequence), after the current global reference. If there is no next global node, accessing$ZORDER results in an error, indicating the last global successfullyaccessed by $ZORDER. For further details on errors, refer to $ZERROR.This special variable cannot be modified using the SET command. Attempting to do so resultsin a error.480 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


ExampleThe following example uses a WHILE loop to repeatedly call $ZORDER to traverse a seriesof subscript nodes:SET ^||a="groceries"SET ^||a(1)="fruit"SET ^||a(1,1)="apples"SET ^||a(1,2)="oranges"SET ^||a(3)="nuts"SET ^||a(3,1)="peanuts"SET ^||a(2)="vegetables"SET ^||a(2,1)="lettuce"SET ^||a(2,2)="tomatoes"SET ^||a(2,1,1)="iceberg"SET ^||a(2,1,2)="romaine"SET $ZERROR="unset"WRITE !,"last referenced: ",^||a(1,1)WHILE $ZERROR="unset" {WRITE !,$ZORDER }QUITThe above example starts with the last-referenced global (in this case, process-private globals):^||a(1,1). $ZORDER does not contain the value of ^||a(1,1), but works forward from thatpoint. Calls to $ZORDER traverse the subscript tree nodes in the following order: (1,2), (2),(2,1), (2,1,1), (2,1,2), (2,2), (3), (3,1). Each WRITE $ZORDER displays the data value ineach successive node. It then runs out of nodes and generates the following error: ^||a(3,1). Note that ^||a(3,1) is not undefined; it is specified because$ZORDER could not find another global after this one.See Also• $ORDER function• $QUERY function• $ZORDER function• $ZERROR special variable$ZORDER<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 481


<strong>Caché</strong> <strong>ObjectScript</strong> Special Variables$ZPARENTContains the ID of the parent process of the current process.$ZPARENT$ZPDescription$ZPARENT contains the ID of the parent process that created the current process with theJOB command. If the current process was not created with the JOB command, $ZPARENTcontains 0 (zero).This special variable cannot be modified using the SET command. Attempting to do so resultsin a error.See Also• JOB command• $ZCHILD special variable• $JOB special variable$ZPIContains the value of pi.$ZPIDescription$ZPI contains the value of the numeric constant Pi to eighteen decimal places(3.141592653589793238).This value is frequently used with trigonometric functions, such as the sine function $ZSIN.482 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZPOS$ZPOSContains the current file position during the reading of a sequential file.$ZPOSDescription$ZPOS contains the current file position during sequential file reads. If no sequential fileread is in progress, $ZPOS contains 0 (zero). The current file position can be set using the$ZSEEK function.By default, <strong>Caché</strong> handles an end-of-file on a sequential file by issuing an error; it does not set $ZPOS. You can configure this end-of-file behavior in a manner compatiblewith MSM. In this case, when an end-of-file is encountered, <strong>Caché</strong> does not issue anerror, but sets $ZPOS to "" (the null string), and sets $ZEOF to -1.To configure end-of-file handling, go to the System Management Portal, select SystemConfiguration, select Advanced Settings, on the pull-down Category list select <strong>ObjectScript</strong>.View and edit the current setting of SetZEOF. When set to “true” , <strong>Caché</strong> sets $ZPOS to ""(the null string), and sets $ZEOF to -1. The default is “false” , You can also establish thisbehavior system-wide by invoking $ZUTIL(69,40,1) or on the current process by invoking$ZUTIL(68,40,1).$ZPOS is not supported on VMS systems.This special variable cannot be modified using the SET command. Attempting to do so resultsin a error.See Also• READ command• $ZSEEK function• $ZUTIL(68,40) End-of-File Handling for Sequential Files function• $ZUTIL(69,40) End-of-File Handling for Sequential Files function• $ZEOF special variable• Sequential File I/O in <strong>Caché</strong> I/O Device Guide<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 483


<strong>Caché</strong> <strong>ObjectScript</strong> Special Variables$ZREFERENCEContains the current global reference.$ZREFERENCE$ZRDescription$ZREFERENCE contains the name and subscript(s) of the last global reference. This isknown as the naked indicator.The last global reference can be either a global (^myglob) or a process-private global(^||myppg). In this description of $ZREFERENCE, the word “global” refers to both typesof variables.The last global reference is the global most recently referred to by a command or a function.Because <strong>ObjectScript</strong> performs operations in left-to-right order, the last global reference isalways the rightmost global. When a command or function takes multiple arguments, theglobal specified in the rightmost argument is the last global reference. When an argumentcontains multiple global references, the rightmost specified global is the last global reference.This strict left-to-right order holds true even if parentheses are used to define the order ofoperations.<strong>Caché</strong> updates $ZREFERENCE when an explicit global reference is issued. Invoking anexpression (such as a local variable) that evaluates to a global reference does not update$ZREFERENCE.$ZREFERENCE contains the most recent global reference, even if this global referencewas not successful. When a command references an undefined global, generating an error, <strong>Caché</strong> updates $ZREFERENCE to that global reference, just as ifthe global were defined.$ZREFERENCE often contains the most recent global reference, even if the commandexecution was not successful. $ZREFERENCE is updated as each global is referenced. Forexample, a command that generates a error (attempting to divide a number by 0)updates $ZREFERENCE to the last global referenced in the command before the erroroccurred. However, a error does not update $ZREFERENCE.If the last global reference was a naked global reference, $ZREFERENCE contains theexternal, readable, full form of the current naked global reference. This is demonstrated inthe following example:484 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZREFERENCESET ^MyData(1)="fruit"SET ^MyData(1,1)="apples" ; Full global referenceSET ^(2)="oranges" ; Naked global reference,; implicitly ^MyData(1,2)WRITE !,$ZREFERENCE ; Returns "^MyData(1,2)"For further details on naked global references, see Using <strong>Caché</strong> Multi-Dimensional Storage(Globals) in Using <strong>Caché</strong> Multi-Dimensional Storage.If a command references a global variable using an extended global reference, the$ZREFERENCE value contains that extended global reference. <strong>Caché</strong> returns an extendedglobal reference in either of the following circumstances:• The current namespace differs from that of the last global reference.• The current global reference is a remote reference.For further details on global subscripts and extended global references, see Global Structurein Using <strong>Caché</strong> Multi-Dimensional Storage.Operations that Update $ZREFERENCEThe $ZREFERENCE special variable is initialized to the null string (""). Changing thecurrent namespace resets $ZREFERENCE to the null string.The following operations set $ZREFERENCE to the most recently referenced global:• A command or function that uses a global as an argument. If it uses multiple globals,$ZREFERENCE is set to the rightmost occurrence of a global.• A command that uses a global as a postconditional expression.• Following a ZWRITE, <strong>Caché</strong> sets $ZREFERENCE to the last listed subscript versionof the specified global reference.• A command or function that references an undefined global, and either generates an error, or, in the case of $INCREMENT, defines the global.Setting $ZREFERENCEYou can set this special variable using the SET command, as follows:• Set to the null string (""). Doing so deletes the naked indicator. If the next global referenceis a naked global reference, <strong>Caché</strong> issues a error.• Set to a valid global reference (defined or undefined). This causes subsequent nakedreferences to use the value you set as if it were the last actual global reference.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 485


<strong>Caché</strong> <strong>ObjectScript</strong> Special Variables$ZREFERENCE cannot be otherwise modified using the SET command. Attempting to doso results in a error.ExamplesThe following example returns the last global reference:SET ^a(1,1)="Hello" ; Full global referenceSET ^(2)=" world!" ; Naked global referenceWRITE $ZREFERENCEreturns:^a(1,2)The following example returns global references from several different commands. Note thatWRITE and ZWRITE set different representations of the same global reference.SET (^barney,^betty,^wilma,^fred)="flintstone"WRITE !,$ZREFERENCEKILL ^fliesWRITE !,$ZREFERENCEWRITE !,^fredWRITE !,$ZREFERENCE,!ZWRITE ^fredWRITE !,$ZREFERENCEreturns:^fred; last of several globals set in left-to-right order^flies; KILL sets global indicator, though no global to killflintstone; WRITE global^fred; global from WRITE^fred="flintstone" ; ZWRITE global^fred(""); global from ZWRITEThe following example stores in $ZREFERENCE the last of several global references followinga ZWRITE command. $ZREFERENCE contains ^Flintstone(2,2). This is the lastglobal reference displayed in the ZWRITE sort order, not the last global referenced prior toZWRITE.SET ^Flintstone(2,1)="Barney"SET ^Flintstone(2,2)="Betty"SET ^Flintstone(1,1)="Fred"SET ^Flintstone(1,2)="Wilma"ZWRITE ^FlintstoneWRITE !,$ZREFERENCEThe following example returns an extended global reference. Note that the namespace nameis always returned in uppercase letters:486 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZREFERENCESET ^["samples"]a(1,1)="Hello"SET ^(2)=" world!"WRITE $ZREFERENCEQUITreturns:^["SAMPLES"]a(1,2)The following example returns the last global reference. In this case, it is ^a(1), used as anargument to the $LENGTH function:SET ^a(1)="abcdefghijklmnopqrstuvwxyz"SET ^b(1)="1234567890"SET x=$LENGTH(^a(1))WRITE $ZREFERENCEQUITThe following example returns the value set for $ZREFERENCE as if it were the last globalreference. In this case, it is ^a(1,1).SET ^a(1,1)="abcdefghijklmnopqrstuvwxyz"SET ^b(1,1)="1234567890"WRITE !,^(1); Naked reference uses last globalSET $ZREFERENCE="^a(1,1)"WRITE !,$ZREFERENCEWRITE !,^(1); Naked reference uses $ZREFERENCE; value, rather than last global.The following example sets an extended global reference. Note the doubled quotation marks:KILL ^xWRITE !,$ZREFERENCESET $ZREFERENCE="^[""samples""]a(1,2)"WRITE !,$ZREFERENCESee Also• ZNSPACE command• $ZUTIL(5) Display or Switch Namespace function• $ZNSPACE special variable• Configuring Namespaces in <strong>Caché</strong> System Administration Guide• Global Structure in Using <strong>Caché</strong> Multi-Dimensional Storage• Naked Global <strong>Reference</strong> in Using <strong>Caché</strong> Multi-Dimensional Storage<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 487


<strong>Caché</strong> <strong>ObjectScript</strong> Special Variables$ZSTORAGEContains the maximum amount of memory for a job.$ZSTORAGE$ZSDescription$ZSTORAGE contains the maximum amount of memory, in Kbytes, for a job's partitionspace. This memory is available for local and global variables, stacks, and other tables. Thismemory limit does not include space for the routine object code.You can also use $ZSTORAGE to set this memory size. For example, the following statementsets the maximum memory to 24K bytes:SET $ZSTORAGE=24The maximum value for $ZSTORAGE is 16384 (which is the default value). The minimumvalue for $ZSTORAGE is 4. Larger numbers default to 16384. Smaller numbers default to4. <strong>Caché</strong> truncates any fractional portion (if present), and then rounds the integer value up tothe next even integer. Thus, input values of 127 and 128.9 would both result in 128.As a rule, you use $ZSTORAGE only as an application development aid to determine if aprogram can be moved to another platform where less memory may be available.See Also$STORAGE special variable$ZTIMESTAMPContains the current date and time in Coordinated Universal Time format.$ZTIMESTAMP$ZTSDescription$ZTIMESTAMP contains the current date and time as a Coordinated Universal Time value.This is a worldwide time and date standard; this value is very likely to differ from your localtime (and date) value.488 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZTIMESTAMP$ZTIMESTAMP represents date and time as a string with the format:ddddd,ttttt.fffWhere ddddd is an integer specifying the number of days since December 31, 1840; ttttt isan integer specifying the number of seconds since midnight of the current day, and fff is avarying number of digits specifying fractional seconds. This format is similar to $HOROLOG,except that $HOROLOG does not contain fractional seconds.Suppose the current date and time (UTC) is as follows:2004-07-23 15:17:27.984At that time, $ZTIMESTAMP has the value:59739,55047.984$ZTIMESTAMP reports the Coordinated Universal Time (UTC), which is independent oftime zone. (UTC is another name for Greenwich Mean Time (GMT).) Consequently,$ZTIMESTAMP provides a timestamp which is uniform across time zones. This may differfrom both the local time value and the local date value.The $ZTIMESTAMP time value is a decimal numeric value that counts the time in secondsand fractions thereof. The number of digits in the fractional seconds may vary from zero tonine, depending on the precision of your computer's time-of-day clock. On Windows systemsthe fractional precision is three decimal digits; on UNIX systems it is six decimal digits.$ZTIMESTAMP suppresses trailing zeroes or a trailing decimal point in this fractionalportion.The various ways to return the current date and time are compared, as follows:• $ZTIMESTAMP contains the UTC (Greenwich Mean) date and time, with fractionalseconds, in <strong>Caché</strong> storage ($HOROLOG) format. Fractional seconds are expressed inthree digits of precision (on Windows systems), or six digits of precision (on UNIX systems).• $HOROLOG contains the local, variant-adjusted date and time in <strong>Caché</strong> storage format.It does not record fractional seconds. How $HOROLOG resolves fractional secondsdepends on the operating system platform: On Windows, it rounds up any fractionalsecond to the next whole second. On UNIX, it truncates the fractional portion.• $ZUTIL(188) returns the local, variant-adjusted date and time, with fractional seconds,in <strong>Caché</strong> storage ($HOROLOG) format. Fractional seconds are expressed in six digitsof precision.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 489


<strong>Caché</strong> <strong>ObjectScript</strong> Special VariablesNote:Exercise caution when comparing local time and UTC time:• The preferred way to convert UTC time to local time is to use the $ZUTIL(193)function, supplying your local time zone offset in minutes. This function adjustsfor local time variants.• You cannot interconvert local time and UTC time by simply adding or subtractingthe value of $ZTIMEZONE * 60. This is because, in many cases, local time isadjusted for local time variants (such as Daylight Savings Time, which seasonallyadjusts local time by one hour). These local time variants are not reflected in$ZTIMEZONE.• Both the timezone offset from UTC and local time variants (such as the seasonalshift to Daylight Savings Time) can affect the date as well as the time. Convertingfrom local time to UTC time (or vice versa) may change the date as well as thetime.This special variable cannot be modified using the SET command. Attempting to do so resultsin a error.Note: $ZTIMESTAMP cannot be used on OpenVMS systems prior to Release 7.0.Invoking $ZTIMESTAMP on a VMS 6.x system generates an error.Coordinated Universal Time ConversionsYou can represent local time information as Coordinated Universal Time (UTC) using the$ZDATETIME and $ZDATETIMEH functions with tformat values 7 or 8, as shown in thefollowing example:WRITE !,$ZDATETIME($ZTIMESTAMP,1,1,2)WRITE !,$ZDATETIME($HOROLOG,1,7,2)WRITE !,$ZDATETIME($HOROLOG,1,8,2)WRITE !,$ZDATETIME($ZUTIL(188),1,7,2)WRITE !,$ZDATETIME($ZUTIL(188),1,8,2)The above $ZDATETIME functions all return the current time as Coordinated UniversalTime (rather than local time). The conversions from local time adjust for local time variantsand adjust the date accordingly, if necessary. However, the $ZTIMESTAMP display valueand the tformat 7 or 8 converted display values are not identical. The tformat values 7 and 8insert the letter “T” before, and the letter “Z” after the time value. Also, because $HOROLOGtime does not contain fractional seconds, the precision of 2 in the above example pads thosedecimal digits with zeros.490 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


You can obtain the same time stamp information as $ZTIMESTAMP by invoking a systemmethod, using either of the following syntax forms:WRITE !,$SYSTEM.SYS.TimeStamp()WRITE !,##class(%SYSTEM.SYS).TimeStamp()Refer to the $SYSTEM special variable and the “Class %SYSTEM.SYS” section of the<strong>Caché</strong> Class <strong>Reference</strong> for further details.ExampleThe following example converts the value of $ZTIMESTAMP to local time, and comparesit with two representations of local time: $ZUTIL(188) and $HOROLOG:SET stamp=$ZTIMESTAMP,clock=$HOROLOG,miliclock=$ZUTIL(188)WRITE !,"local date and time: ",$ZDATETIME(clock,1,1,2)WRITE !,"local date and time: ",$ZDATETIME(miliclock,1,1,2)WRITE !,"UTC date and time: ",$ZDATETIME(stamp,1,1,2)IF $PIECE(stamp,",",2) = $PIECE(clock,",",2) {WRITE !,"Local time is UTC time" }ELSEIF $PIECE(stamp,",") '= $PIECE(clock,",") {WRITE !,"Time difference affects date" }ELSE {SET localutc=$ZUTIL(193,stamp)WRITE !,"Converted local date and time: ",$ZDATETIME(localutc,1,1,2)}QUITThe following example compares the values returned by $ZTIMESTAMP and $HOROLOG,and shows how the time portion of $ZTIMESTAMP may be converted. (Note that in thissimple example only one adjustment is made for local time variations, such as DaylightSavings Time. Other types of local variation may cause clocksecs and stampsecs to containirreconcilable values.)SET stamp=$ZTIMESTAMP,clock=$HOROLOGWRITE !,"local date and time: ",$ZDATETIME(clock,1,1,2)WRITE !,"UTC date and time: ",$ZDATETIME(stamp,1,1,2)IF $PIECE(stamp,",") '= $PIECE(clock,",") {WRITE !,"Time difference affects date" }SET clocksecs=$EXTRACT(clock,7,11)SET stampsecs=$EXTRACT(stamp,7,11)-($ZTIMEZONE*60)IF clocksecs=stampsecs {WRITE !,"No local time variant"WRITE !,"Local time is timezone time" }ELSE {SET stampsecs=stampsecs+3600IF clocksecs=stampsecs {WRITE !,"Daylight Savings Time variant:"WRITE !,"Local time offset 1 hour from timezone time" }ELSE { WRITE !,"Cannot reconcile due to local time variant" }}QUIT$ZTIMESTAMP<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 491


<strong>Caché</strong> <strong>ObjectScript</strong> Special VariablesSee Also• $ZDATETIME function• $ZUTIL(188) Local Date/Time with Fractional Seconds function• $ZUTIL(193) Convert UTC to Local Date/Time function• $HOROLOG special variable• $ZTIMEZONE special variable$ZTIMEZONEContains the time zone offset from GMT.$ZTIMEZONE$ZTZDescription$ZTIMEZONE contains the time zone offset from GMT (Greenwich Mean Time) in minutes.This offset is expressed as a signed integer in the range -720 to 720. Time zones west of GMTare specified as positive numbers; time zones east of GMT are specified as negative numbers.(Time zones must be expressed in minutes, because not all time zone differences are in wholehours.) By default, $ZTIMEZONE is initialized to the time zone set for the computer'soperating system.Note:$ZTIMEZONE does not adjust for Daylight Savings Time or other local timevariants.You can use $ZTIMEZONE to convert a Coordinated Universal Time (UTC) date and timevalue to a local time value by using $ZUTIL(193). This function takes as input a UTC value,such as a $ZTIMESTAMP value, and a time zone offset value in minutes, such as a$ZTIMEZONE value. $ZUTIL(193) returns the corresponding date and time for the specifiedlocal time zone, with local time variants (such as Daylight Savings Time) applied whereapplicable.SET clock=$HOROLOGSET stamp=$ZUTIL(193,$ZTIMESTAMP,$ZTIMEZONE)WRITE !,"local/local date and time: ",$ZDATETIME(clock,1,1,2)WRITE !,"UTC/local date and time: ",$ZDATETIME(stamp,1,1,2)492 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZTIMEZONESetting the Time ZoneYou can use $ZTIMEZONE to set the time zone used by the current <strong>Caché</strong> process. Setting$ZTIMEZONE does not change the default <strong>Caché</strong> time zone or your computer's time zonesetting.Use the SET command to set $ZTIMEZONE to a specified signed integer number of minutes.Leading zeros and decimal portions of numbers are ignored. If you specify a non-numericvalue or no value when setting $ZTIMEZONE, <strong>Caché</strong> sets $ZTIMEZONE to 0 (GreenwichMean Time).For example, North American Eastern Standard Time (EST) is five hours west of GreenwichMean Time (GMT). Therefore, to set the current <strong>Caché</strong> process to EST you would specify300 minutes. To specify a time zone one hour east of GMT, you would specify –60 minutes.To specify GMT itself, you would specify 0 minutes.Setting $ZTIMEZONE:• affects the $HOROLOG local time value. It changes the time portion of $HOROLOG,and this change of time can also change the date portion of $HOROLOG for the currentprocess.• affects the value returned by $ZUTIL(193).• does not affect the $ZUTIL(188) local time value.• does not affect $ZTIMESTAMP or $ZHOROLOG values.• does not affect the date format conversions performed by the $ZDATE and $ZDATEHfunctions. The $ZUTIL(71) function, which sets the date in $HOROLOG to a fixedvalue, is also not affected by $ZTIMEZONE.Other Time Zone MethodsYou can obtain the same time zone information by invoking a system method, as follows:WRITE $SYSTEM.SYS.TimeZone()Refer to the “Class %SYSTEM.SYS” section of the <strong>Caché</strong> Class <strong>Reference</strong> for further details.You can return your local time variation as part of a date and time string by using the$ZDATETIME and $ZDATETIMEH functions with tformat values 5 or 6, as shown in thefollowing example:WRITE !,$ZDATETIME($HOROLOG,1,5)This returns a value such as:<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 493


<strong>Caché</strong> <strong>ObjectScript</strong> Special Variables07/23/2004T16:23:54-04:00The last part of this string (-04:00) indicates the local time variation in hours and minutesfrom Greenwich Mean Time. Note that this variation is not necessarily the time zone time.In the above case, the time zone is 5 hours west of Greenwich (-5:00), but the local timevariant (Daylight Savings Time) offsets the time zone time by one hour.ExamplesThe following example returns your current time zone:SET zone=$ZTIMEZONEIF zone=0 {WRITE !,"Your time zone is Greenwich Mean Time" }ELSEIF zone>0 {WRITE !,"Your time zone is ",zone/60," hours west of Greenwich" }ELSE {WRITE !,"Your time zone is ",(-zone)/60," hours east of Greenwich" }The following example shows that setting the time zone can change the date as well as thetime:SET zonesave=$ZTIMEZONEWRITE !,"Date in my current time zone: ",$ZDATE($HOROLOG)IF $ZTIMEZONE=0 {SET $ZTIMEZONE=720 }ELSEIF $ZTIMEZONE>0 {SET $ZTIMEZONE=($ZTIMEZONE-720) }ELSE {SET $ZTIMEZONE=($ZTIMEZONE+720) }WRITE !,"Date halfway around the world: ",$ZDATE($HOROLOG)WRITE !,"Date at Greenwich Observatory: ",$ZDATE($ZTIMESTAMP)SET $ZTIMEZONE=zonesaveThe following example determines if your local time is the same as your time zone time:SET localnow=$HOROLOG, stamp=$ZTIMESTAMPWRITE !,"local date and time: ",$ZDATETIME(localnow,1,1)SET clocksecs=$PIECE(localnow,",",2)SET stampsecs=$EXTRACT(stamp,7,11)-($ZTIMEZONE*60)IF clocksecs=stampsecs {WRITE !,"No local time variant:"WRITE !,"Local time is timezone time" }ELSE {IF clocksecs=stampsecs+3600 {WRITE !,"Daylight Savings Time variant:"WRITE !,"Local time offset 1 hour from timezone time" }ELSE { WRITE !,"Local time and time zone time are "WRITE !,(clocksecs-stampsecs)/60," minutes different" }}QUITSee Also• $ZUTIL(188) Local Time with Fractional Seconds function494 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZTRAP• $ZUTIL(193) Interconvert Universal (UTC) Time and Local Time function• $HOROLOG special variable• $ZTIMESTAMP special variable$ZTRAPContains the name of the current error trap handler.$ZTRAP$ZTDescription$ZTRAP contains the tag name and/or routine name of the current error trap handler. Thereare three ways to set $ZTRAP:• SET $ZTRAP=“location”• SET $ZTRAP=“*location”• SET $ZTRAP=“^%ET” or “^%ETN”Here location can be specified as tag (a label in the current routine), ^routine (the beginningof a specified external routine), or tag^routine (a specified label in a specified external routine).$ZTRAP supports tag+offset in some contexts (but not in procedures). This optional +offsetis an integer specifying the number of lines to offset from tag. <strong>InterSystems</strong> recommendsthat you avoid the use of a line offset when specifying location.If you specify a non-existent location in the current routine, <strong>Caché</strong> issues a errormessage.By default, error trapping is not enabled, and $ZTRAP contains the null string (""). To enableerror trapping, set $ZTRAP to the error trap handler by specifying its location. For example:IF $ZTRAP="" {WRITE !,"$ZTRAP not set" }ELSE {WRITE !,"$ZTRAP already set: ",$ZTRAPSET oldtrap=$ZTRAP }SET $ZTRAP="Etrap1^Handler"WRITE !,"$ZTRAP set to: ",$ZTRAP// program codeSET $ZTRAP=oldtrapWRITE !,"$ZTRAP restored to: ",$ZTRAP<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 495


<strong>Caché</strong> <strong>ObjectScript</strong> Special VariablesWhen an error occurs, this format unwinds the call stack and transfers control to the specifiederror trap handler.You can choose to leave the call stack as it is after the error has occurred. To do so, place anasterisk (*) before location. This form is not valid for use within procedures. It can only beused in subroutines that are not procedures, as in this example:MainSET $ZTRAP="*OnError"WRITE !,"$ZTRAP set to: ",$ZTRAP// program codeOnError// Error handling codeQUITThis format simply causes a GOTO to the tag specified in $ZTRAP; $STACK and$ESTACK are unchanged. The context frame of the $ZTRAP error handling routine is thesame as the context frame where the error occurred. Upon completion of the $ZTRAP errorhandling routine, <strong>Caché</strong> unwinds the stack to the previous context level. This form of $ZTRAPis especially useful for analyzing unexpected errors.Note that the asterisk sets a $ZTRAP option; it is not part of the location. For this reason,this asterisk does not display when performing a WRITE or ZZDUMP on $ZTRAP.The error handlers ^%ETN and ^%ET always behave as if they were preceded by an asterisk(*).To disable error trapping, set $ZTRAP to the null string (""). This clears any error trap setat the current DO stack level.When you set an error handler using $ZTRAP, this handler takes precedence over anyexisting $ETRAP error handler. <strong>Caché</strong> implicitly performs a NEW $ETRAP command andsets $ETRAP to the null string ("").Note:Use of $ZTRAP from the <strong>Caché</strong> Terminal prompt is limited to the current line ofcode. The SET $ZTRAP command and the command generating the error must bein the same line of code. <strong>Caché</strong> Terminal restores $ZTRAP to the system default atthe beginning of each command line.ExamplesThe following example sets $ZTRAP to the OnError routine in this program. It then callsSubA in which an error occurs (attempting to divide a number by 0). When the error occurs,<strong>Caché</strong> calls the OnError routine specified in $ZTRAP. OnError is invoked at the contextlevel at which $ZTRAP was set. Because OnError is at the same context level as Main,execution does not return to Main.496 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZTRAPMainNEW $ESTACKSET $ZTRAP="OnError"WRITE !,"$ZTRAP set to: ",$ZTRAPWRITE !,"Main $ESTACK= ",$ESTACK // 0WRITE !,"Main $ECODE= ",$ECODEDO SubAWRITE !,"Returned from SubA" // not executedWRITE !,"MainReturn $ECODE= ",$ECODEQUITSubAWRITE !,"SubA $ESTACK= ",$ESTACK // 1WRITE !,6/0 // Error: division by zeroWRITE !,"fine with me"QUITOnErrorWRITE !,"OnError $ESTACK= ",$ESTACK // 0WRITE !,"$ECODE= ",$ECODEQUITThe following example is identical to the previous example, with one exception: The $ZTRAPlocation is prefaced by an asterisk (*). When the error occurs in SubA, this asterisk causes<strong>Caché</strong> to call the OnError routine at the context level of SubA (where the error occurred),not at the context level of Main (where $ZTRAP was set). Therefore, when OnError completes,execution returns to Main at the line following the DO command.MainNEW $ESTACKSET $ZTRAP="*OnError"WRITE !,"$ZTRAP set to: ",$ZTRAPWRITE !,"Main $ESTACK= ",$ESTACK // 0WRITE !,"Main $ECODE= ",$ECODEDO SubAWRITE !,"Returned from SubA" // executedWRITE !,"MainReturn $ECODE= ",$ECODEQUITSubAWRITE !,"SubA $ESTACK= ",$ESTACK // 1WRITE !,6/0 // Error: division by zeroWRITE !,"fine with me"QUITOnErrorWRITE !,"OnError $ESTACK= ",$ESTACK // 1WRITE !,"$ECODE= ",$ECODEQUITSee Also• ZQUIT command• ZINSERT command• $ETRAP special variable• $ECODE special variable• $ESTACK special variable• $STACK special variable<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 497


<strong>Caché</strong> <strong>ObjectScript</strong> Special Variables• Error Handling in Using <strong>Caché</strong> <strong>ObjectScript</strong>$ZVERSIONContains a string describing the current version of <strong>Caché</strong>.$ZVERSION$ZVDescription$ZVERSION contains a string showing the version of the currently running <strong>Caché</strong> system.The following example returns the $ZVERSION string:WRITE $ZVERSIONThis returns a version string such as the following:Cache for Windows (Intel/P4) 5.1 (Build 682U) Fri Apr 1 2005 04:20:33 ESTThis string includes the type of <strong>Caché</strong> installation (product and platform, including CPUtype), the version number (5.1), the build number within that version (the “U” in the buildnumber indicates a Unicode version), and the date and time that this version of <strong>Caché</strong> wascreated. “EST” is Eastern Standard Time (the time zone for the Eastern United States), “EDT”is Eastern Daylight Savings Time.The same information can be viewed by going to the <strong>Caché</strong> Cube and selecting “About...” orby invoking a system method, as follows:WRITE $SYSTEM.Version.GetVersion()You can get the component parts of this version string by invoking other $SYSTEM.Versionmethods, which you can list by invoking:WRITE $SYSTEM.Version.Help()The $ZVERSION special variable cannot be modified using the SET command. Attemptingto do so results in a error.To return the operating system type for your Windows operating system, use $ZUTIL(100).498 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


ExampleThe following example extracts the create date from the version string to calculate how oldthe current version of <strong>Caché</strong> is, in days:SET createdate=$PIECE($ZVERSION," ",10,12)WRITE !,"Creation date: ",createdateWRITE !,"Current date: ",$ZDATE($HOROLOG,6)SET nowcount=$PIECE($HOROLOG,",")SET thencount=$ZDATEH(createdate,6)WRITE !,"This version is ",(nowcount-thencount)," days old"See Also• $SYSTEM special variable• $ZUTIL(100)—Operating System Type function• $ZUTIL(67,14)—Client Operating System legacy function$ZVERSION<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 499


Structured System VariablesA structured system variable name, or SSVN, is a nonscalar system variable that is organizedlike a global variable. SSVNs allow you to write portable programs that can retrieve informationabout system data. The same <strong>Caché</strong> <strong>ObjectScript</strong> code can retrieve system data informationfrom any <strong>Caché</strong> implementation using structured system variables.Each SSVN has a structure where subscript values are any of the following:• Entity identifiers• Literals• Attribute keywords.You provide information about entities by providing values for subscripts which are identifiersand for attribute nodes.SSVNs use the circumflex and dollar sign (^$) as a standard prefix followed by:1. An optional (extended syntax ) specification of the namespace about which you wantinformation2. One of a designated list of names.You then follow the name with one or more expressions in parentheses. These expressionsare called subscripts. The syntax is as follows:^$[|namespace|] ssvn_name(expression)Generally, you cannot use SET and KILL commands for structured system variables becausethey do not necessarily have data values. The information that structured system variablesprovide is often the existence of specific subscript values. In most cases, you can use the$DATA, the $ORDER, and the $QUERY functions to examine subscript values.<strong>Caché</strong> supports the following structured system variables:• ^$GLOBAL• ^$JOB• ^$LOCK• ^$ROUTINE<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 501


Structured System VariablesThe meaning of each of these SSVNs and use of their subscripts is explained in the followingsections.Each description identifies which functions are allowed with the particular structured systemvariable. Each description contains one or more examples about how to use structured systemvariable as arguments to the $DATA, $ORDER, and $QUERY functions to scan systemtable information.^$GLOBALProvides information about globals.^$|nspace|GLOBAL(global_name)^$|nspace|G(global_name)Parameters|nspace|or[nspace]global_nameOptional — An extended global reference, either an explicitnamespace name or an implied namespace. Must evaluate to aquoted string, which is enclosed in either square brackets([“nspace”]) or vertical bars (|“nspace”|). Namespace names arecase-insensitive; they are stored and displayed in uppercase letters.An expression that evaluates to a string containing an unsubscriptedglobal name.DescriptionYou can use ^$GLOBAL as an argument to the $DATA, $ORDER, and $QUERY functionsto get information about the existence of global variables in the current namespace (thedefault), or in a specified namespace.For more information on global variables, refer to Using <strong>Caché</strong> Multi-Dimensional Storage.ParametersnspaceThis optional parameter allows you to specify a global in another namespace by using extendedglobal reference. You can specify the namespace name either explicitly, or by specifying animplied namespace. The namespace name must be specified as a quoted string. Namespacenames are case-insensitive. You can use either bracket syntax [“USER”] or environmentsyntax |“USER”|. No spaces are allowed before or after the nspace delimiters. You can use502 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


the $ZNSPACE special variable to determine the current namespace, the $ZUTIL(90,10)function to determine if a namespace is defined, and the ZNSPACE command to change thecurrent namespace. For further information on extended global references, see Global Structurein Using <strong>Caché</strong> Multi-Dimensional Storage.global_nameAn expression that evaluates to a string containing an unsubscripted global name.ExamplesThe following examples show how to use ^$GLOBAL as an argument to the $DATA,$ORDER, and $QUERY functions.As an Argument to $DATA^$GLOBAL^$GLOBAL as an argument to $DATA returns an integer value that signifies whether theglobal name you specify exists as a ^$GLOBAL node. The integer values that $DATA canreturn are shown in the following table.Value011011MeaningGlobal name does not existGlobal name is an existing node with data but has no descendants.Global name is an existing node with no data but has descendants.Global name is an existing node with data and has descendants.The following example test for the existence of a global variable in the user's default namespace.KILL ^GBLWRITE $DATA(^$GLOBAL("^GBL"))returns 0.The following example test for the existence of a global variable in the SAMPLES namespace.SET ^GBL(1)="TEST"WRITE $DATA(^$|"SAMPLES"|GLOBAL("^GBL"))returns 10.As an Argument to $ORDER$ORDER(^$|nspace|GLOBAL( global_name),direction)<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 503


Structured System Variables^$GLOBAL as an argument to $ORDER returns the next or previous global name in collatingsequence to the global name you specify. If no such global name node exists in ^$GLOBAL,$ORDER returns a null string.The direction argument specifies whether to return the next or the previous global name. Ifyou do not provide a direction argument, <strong>Caché</strong> returns the next global name in collatingsequence to the one you specify. For further details, refer to the $ORDER function.The following subroutine searches the user's default namespace and stores the global namesin a local array named GLOBAL.GLOBSET NAME=""WRITE !,"The following globals are in ",$ZNSPACEFOR I=1:1 {SET NAME=$ORDER(^$GLOBAL(NAME))WRITE !,NAMEQUIT:NAME=""SET GLOBAL(I)=NAME}WRITE !,"All done"QUITAs an Argument to $QUERY^$GLOBAL as an argument to $QUERY returns the next global name in collating sequenceto the global name you specify. If no such global name exists as a node in ^$GLOBAL,$QUERY returns a null string.In the following example, three globals (^GBL1, ^GBL2 and ^GBL3) are present in theSAMPLES namespace.ZNSPACE "SAMPLES"SET (^GBL1,^GBL2,^GBL3)="TEST"ZNSPACE "USER"WRITE $QUERY(^$|"SAMPLES"|GLOBAL("^GBL1"))WRITE !,$QUERY(^$|"SAMPLES"|GLOBAL("^GBL2"))ZNSPACE "SAMPLES"KILL ^GBL1,^GBL2,^GBL3The first WRITE returns ^$|"SAMPLES"|GLOBAL("^GBL2")The second WRITE returns ^$|"SAMPLES"|GLOBAL("^GBL3")See Also• $DATA function• $ORDER function• $QUERY function504 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


^$JOB• ZNSPACE command• $ZNSPACE special variable• $ZUTIL(90,10) Test Whether a Namespace is Defined function• Configuring Namespaces in <strong>Caché</strong> System Administration Guide^$JOBProvides <strong>Caché</strong> process (job) information.^$JOB(job_number)^$J(job_number)Parametersjob_numberThe system-specific job number created when you enter the <strong>Caché</strong><strong>ObjectScript</strong> command. Every active <strong>Caché</strong> process has a uniquejob number. Logging in to the system initiates a job. On OpenVMSsystems, the job number is the process identification (PID) of theprocess started. On UNIX systems, the job number is the PID ofthe child process started when <strong>Caché</strong> was invoked.DescriptionYou can use the ^$JOB structured system variable as an argument to the $DATA, $ORDER,and $QUERY functions to get information about the existence of <strong>Caché</strong> jobs on the local<strong>Caché</strong> system.ExamplesThe following examples show how to use ^$JOB as an argument to the $DATA, $ORDER,and $QUERY functions.As an Argument to $DATA$DATA(^$JOB(job_number))^$JOB as an argument to $DATA returns an integer value that indicates whether the specifiedjob exists as a node in ^$JOB. The integer values that $DATA can return are shown in thefollowing table.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 505


Structured System VariablesValue01MeaningJob does not exist.Job exists.The following example tests for the existence of a <strong>Caché</strong> process.SET x=$JOBWRITE !,$DATA(^$JOB(x))The variable x is set to the job number of the current process (for example: 4294219937).The WRITE returns the boolean 1, indicating this process exists.As an Argument to $ORDER$ORDER(^$JOB(job_number),direction)^$JOB as an argument to $ORDER returns the next or previous ^$JOB job number in collatingsequence to the job number you specify. If no such job number exists as a ^$JOB node,$ORDER returns a null string.The direction argument specifies whether to return the next or the previous job number. Ifyou do not provide a direction argument, <strong>Caché</strong> returns the next job number in collatingsequence to the one you specify. For further details, refer to the $ORDER function.The following subroutine searches the <strong>Caché</strong> job table and stores the job numbers in a localarray named JOB.JOBSET PID=""FOR I=1:1 {SET PID=$ORDER(^$JOB(PID))QUIT:PID=""SET JOB(I)=PID}WRITE "Total Jobs in Job Table: ",IQUITAs an Argument to $QUERY$QUERY(^$JOB(job_number))^$JOB as an argument to $QUERY returns the next ^$JOB job number in collating sequenceto the job number you specify. If no such job number exists as a node in ^$JOB, $QUERYreturns a null string.The following example returns the first two jobs in the <strong>Caché</strong> job table. Note the use of theindirection operator (@):506 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


^$LOCKSET x=$QUERY(^$JOB(""))WRITE !,xWRITE !,$QUERY(@x)returns values for these jobs such as the following:^$JOB("4294117993")^$JOB("4294434881")See Also• JOB command• $DATA function• $ORDER function• $QUERY function• $JOB special variable• $ZJOB special variable• $ZCHILD special variable• $ZPARENT special variable^$LOCKProvides lock name information.^$|nspace|LOCK(lock_name)^$|nspace|L(lock_name)Parameters|nspace|or[nspace]lock_nameOptional — An extended global reference, either an explicitnamespace name or an implied namespace. Must evaluate to aquoted string, which is enclosed in either square brackets ([“nspace”])or vertical bars (|“nspace”|). Namespace names are case-insensitive;they are stored and displayed in uppercase letters.An expression that evaluates to a string containing a lock variablename, either subscripted or unsubscripted.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 507


Structured System VariablesDescriptionYou can use the ^$LOCK structured system variable as an argument to the $DATA,$ORDER, and $QUERY functions to return information about locks in the current namespaceor a specified namespace on the local system.ParametersnspaceThis optional parameter allows you to specify a global in another namespace by using extendedglobal reference. You can specify the namespace name either explicitly, or by specifying animplied namespace. The namespace name must be specified as a quoted string. Namespacenames are case-insensitive. You can use either bracket syntax [“USER”] or environmentsyntax |“USER”|. No spaces are allowed before or after the nspace delimiters. You can usethe $ZNSPACE special variable to determine the current namespace, the $ZUTIL(90,10)function to determine if a namespace is defined, and the ZNSPACE command to change thecurrent namespace. For further information on extended global references, see Global Structurein Using <strong>Caché</strong> Multi-Dimensional Storage.lock_nameAn expression that evaluates to a string containing a lock variable name, either subscriptedor unsubscripted, for use with the LOCK command.ExamplesThe following examples show how to use ^$LOCK as an argument to the $DATA, $ORDER,and $QUERY functions.As an Argument to $DATA$DATA(^$|nspace|LOCK(lock_name))^$LOCK as an argument to $DATA returns an integer value that specifies whether the lockname exists as a node in ^$LOCK. The integer values that $DATA can return are shown inthe following table.Value010MeaningLock name information does not existLock name information exists508 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


The following example tests for the existence of a lock name in the current namespace. Thefirst WRITE returns 10 (lock name exists), the second WRITE returns 0 (lock name does notexist):LOCK ^B(1,2) ; define lockWRITE !,$DATA(^$LOCK("^B(1,2)"))LOCK -^B(1,2) ; delete lockWRITE !,$DATA(^$LOCK("^B(1,2)"))As an Argument to $ORDER$ORDER(^$|nspace|LOCK(lock_name),direction)^$LOCK as an argument to $ORDER returns the next or previous ^$LOCK lock namenode in collating sequence to the lock name you specify. If no such lock name exists as a^$LOCK node, $ORDER returns a null string.The direction argument specifies whether to return the next or the previous lock name. If youdo not provide a direction argument, <strong>Caché</strong> returns the next lock name in collating sequenceto the one you specify. For further details, refer to the $ORDER function.The following subroutine searches the locks in the SAMPLES namespace and stores the locknames in a local array named LOCKET.LOCKARRAYSET lname=""FOR I=1:1 {SET lname=$ORDER(^$|"SAMPLES"|LOCK(lname))QUIT:lname=""SET LOCKET(I)=lnameWRITE !,"the lock name is: ",lname}WRITE !,"All lock names listed"QUITAs an Argument to $QUERY$QUERY(^$|nspace|LOCK(lock_name))^$LOCK as an argument to $QUERY returns the next lock name in collating sequence tothe lock name you specify. If there is no next lock name defined as a node in ^$LOCK,$QUERY returns a null string.In the following example, five global lock names are created (in random order) in the currentnamespace.LOCK (^B(1),^A,^D,^A(1,2,3),^A(1,2))WRITE !,"lock name: ",$QUERY(^$LOCK(""))WRITE !,"lock name: ",$QUERY(^$LOCK("^C"))WRITE !,"lock name: ",$QUERY(^$LOCK("^A(1,2)"))^$LOCK<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 509


Structured System Variables$QUERY treats all global lock variable names, subscripted or unsubscripted, as characterstrings and retrieves them in string collating order. Therefore, $QUERY(^$LOCK("")) retrievethe first lock name in collating sequence order: either ^$LOCK("^A”) or a <strong>Caché</strong>-definedlock higher in the collating sequence. $QUERY(^$LOCK("^C")) retrieves the next lock namein collating sequence after the non-existent ^C: ^$LOCK("^D”).$QUERY(^$LOCK("^A(1,2)")) retrieve ^$LOCK("^A(1,2,3)”) which follows it in collationsequence.See Also• LOCK command• $DATA function• $ORDER function• $QUERY function• $ZNSPACE special variable• $ZUTIL(90,10) Test Whether a Namespace is Defined function• Configuring Namespaces in <strong>Caché</strong> System Administration Guide^$ROUTINEProvides routine information.^$|nspace|ROUTINE(routine_name)^$|nspace|R(routine_name)Parameters|nspace|or[nspace]routine_nameOptional — An extended global reference, either an explicitnamespace name or an implied namespace. Must evaluate to aquoted string, which is enclosed in either square brackets([“nspace”]) or vertical bars (|“nspace”|). Namespace names arecase-insensitive; they are stored and displayed in uppercaseletters.An expression that evaluates to a string containing the name ofa routine.510 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


DescriptionYou can use the ^$ROUTINE structured system variable as an argument to the $DATA,$ORDER, and $QUERY functions to return routine information from the current namespace(the default) or a specified namespace.ParametersnspaceThis optional parameter allows you to specify a global in another namespace by using extendedglobal reference. You can specify the namespace name either explicitly, or by specifying animplied namespace. The namespace name must be specified as a quoted string. Namespacenames are case-insensitive. You can use either bracket syntax [“USER”] or environmentsyntax |“USER”|. No spaces are allowed before or after the nspace delimiters. You can usethe $ZNSPACE special variable to determine the current namespace, the $ZUTIL(90,10)function to determine if a namespace is defined, and the ZNSPACE command to change thecurrent namespace. For further information on extended global references, see Global Structurein Using <strong>Caché</strong> Multi-Dimensional Storage.routine_nameAn expression that evaluates to a string containing the name of a routine.ExamplesThe following are examples of using ^$ROUTINE as an argument to the $DATA, $ORDER,and $QUERY functions.As an Argument to $DATA$DATA(^$|nspace|ROUTINE(routine_name))^$ROUTINE^$ROUTINE as an argument to $DATA returns an integer value that specifies whether theroutine_name exists as a node in ^$ROUTINE. The integer values that $DATA can returnare shown in the following table.Value01MeaningRoutine name does not existRoutine name existsThe following example tests for the existence of a routine in the default namespace:<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 511


Structured System VariablesXECUTE "ZREMOVE"XECUTE "ZSAVE ROU"WRITE !,$DATA(^$ROUTINE("^ROU"))XECUTE "ZSAVE ROU"WRITE !,$DATA(^$ROUTINE("^ROU"))As an Argument to $ORDER$ORDER(^$|nspace|ROUTINE( routine_name),direction)^$ROUTINE as an argument to $ORDER returns the next or previous routine name incollating sequence to the routine name you specify. If no such routine name exists as a nodein ^$ROUTINE, $ORDER returns a null string.The direction argument specifies whether to return the next or the previous routine name. Ifyou do not provide a direction argument, <strong>Caché</strong> returns the next routine name in collatingsequence to the one you specify. For further details, refer to the $ORDER function.The following subroutine searches the USER namespace and stores the routine names in alocal array named ROUTINE.SET rname=""FOR I=1:1 {SET rname=$ORDER(^$|"USER"|ROUTINE(rname))QUIT:rname=""SET ROUTINE(I)=rnameWRITE !,"Routine name: ",rname}WRITE !,"All routines stored"QUITAs an Argument to $QUERY$QUERY(^$|nspace|ROUTINE(routine_name))^$ROUTINE as an argument to $QUERY returns the next routine name in collating sequenceto the routine name you specify. The specified routine name does not have to exist. If thereis no routine name later in the collating sequence, $QUERY(^$ROUTINE) returns a nullstring.In the following example, two $QUERY functions return the next routine after the specifiedroutine name in the USER namespace.SET rname=""WRITE !,"1st routine: ",$QUERY(^$|"USER"|ROUTINE(rname))SET rname="%m"WRITE !,"1st ",rname, " routine: ",$QUERY(^$|"USER"|ROUTINE(rname))QUITSee Also• $DATA function512 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


^$ROUTINE• $ORDER function• $QUERY function• $ZNSPACE special variable• $ZUTIL(90,10) Test Whether a Namespace is Defined function• Configuring Namespaces in <strong>Caché</strong> System Administration Guide<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 513


System and Other FunctionsThe following are reference pages for system and other functions, including the $ZUTILutility functions. Many of these functions are used to return or set configuration, locale, andplatform parameters, and to support Unicode characters. These functions supplement the<strong>Caché</strong> <strong>ObjectScript</strong> general functions described earlier in this document. The names of all ofthese supplemental functions begin with “$Z”. Functions are listed in alphabetical order.Further introductory information on function syntax and conventions is provided at thebeginning of the general functions reference pages. Additional information on <strong>Caché</strong> functionscan be found in the Functions chapter of Using <strong>Caché</strong> <strong>ObjectScript</strong>.$ZBOOLEANBitwise logical operation function.$ZBOOLEAN(arg1,arg2,bit_op)$ZB(arg1,arg2,bit_op)Parametersarg1arg2bit_opThe first argument. An integer or a string, or a variable or expression thatresolve to an integer or string. Cannot be a floating point number.The second argument. An integer or a string, or a variable or expressionthat resolve to an integer or string. Cannot be a floating point number.An integer indicating the operation to be performed (see table below.)Permitted values are 0 through 15, inclusive.Description$ZBOOLEAN performs the bitwise logical operation specified by bit_op on two arguments,arg1 and arg2. $ZBOOLEAN returns the results of the bitwise combination of arg1 andarg2, as specified by the bit_op value. You can view the results using the ZZDUMP command.$ZBOOLEAN performs its operations on either character strings or numbers. For characterstrings, it performs logical AND and OR operations on each character in the string. For<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 515


System and Other Functionsnumbers, it performs a logical AND and OR operation on the entire number as a unit. Toforce the evaluation of a numeric string as a number, preface the string with a plus sign (+).The bitwise operations includes 16 possible Boolean combinations of arg1 and arg2. Thefollowing table lists these combinations.Bit Mask inbit_op0123456789101112131415Operation Performed0arg1 & arg2 (logical AND)arg1 & ~arg2arg1~arg1 & arg2arg2arg1 ^ arg2 (logical XOR (exclusive or))arg1 ! arg2 (logical OR (inclusive or))~(arg1 ! arg2)~(arg1 ^ arg2)~arg2 (logical NOT)arg1 ! ~arg2~arg1 (logical NOT)~arg1 ! arg2~(arg1 & arg2)-1 (one's complement of 0)Where:& is logical AND! is logical OR~ is logical NOT^ is exclusive ORFor further details, see Operators in Using <strong>Caché</strong> <strong>ObjectScript</strong>.516 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


All $ZBOOLEAN operations parse both arg1 and arg2, including bit_op values 0, 3, 5, 10,12, and 15.The $ZBOOLEAN arg1 and arg2 parameters can resolve to one of the following types:• An integer. A positive or negative whole decimal number of up to 18 digits. No charactersother than the numbers 0–9 and, optionally, one or more leading plus and minus signsare permitted. Leading zeros are ignored.• A string. Enclosed in quotation marks, a string of any length with any contents is permitted.Note that the string “123” and the integer 123 are not the same. A null string is permitted,but if arg2 is the null string, $ZBOOLEAN always returns the value of arg1, regardlessof the bit_op value.• A signed string. A string preceded by a plus or minus sign is parsed as an integer,regardless of the string's contents. Signed strings are subject to the same length restrictionas integers. A signed null string is equivalent to zero.It is strongly recommended that arg1 and arg2 either both resolve to an integer or both resolveto a string. Generally, arg1 and arg2 should be the same data type; combining an integer anda string in a $ZBOOLEAN operation does not give a useful result in most cases.Parametersarg1The first argument in the bitwise logical expression. For strings, the length of the returnedvalue is always the same as the length of this argument.arg2The second argument in the bitwise logical expression.bit_op$ZBOOLEANThe bitwise logical operation to be performed, specified as a numeric code from 0 to 15,inclusive. Because this code is handled as a bit mask, a value of 16=0, 17=1, 18=2, etc.The bit_op values 0 and 15 return a constant value, but they also evaluate the arguments. Ifarg1 is an integer (or signed string), bit_op 0 returns 0, and bit_op 15 returns –1 (the one'scomplement of 0.) If arg1 is a string, bit_op 0 returns a low value (hex 00) for each characterin arg1, and bit_op 15 returns a high value (hex FF) for each character in arg1. If arg2 is thenull string (""), both operations return the literal value of arg1.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 517


System and Other FunctionsThe bit_op values 3, 5, 10 and 12 perform a logical operation on only one of the arguments,but they evaluate both arguments.• bit_op=3 always returns the value of arg1, regardless of the value of arg2.• bit_op=5 returns the value of arg2 when the two arguments have the same data type.However if one argument is a string and the other argument is an integer (or signed string)results are unpredictable. If arg2 is the null string $ZBOOLEAN always returns the literalvalue of arg1.• bit_op=10 returns the one's complement value of arg2 if both arguments are integers. Ifarg1 is a string, the operation returns a high order character for each character in arg1..If arg2 is a string, and arg1 is an integer, the bitwise operation is performed on the arg2string. If arg2 is the null string $ZBOOLEAN always returns the literal value of arg1.• bit_op=12 returns the one's complement value of arg1 if it is an integer (or signed string),for any value of arg2 except the null string. If arg1 is a string, the operation returns theone's complement (as a hex value) of each character in arg1. If arg2 is the null string$ZBOOLEAN always returns the literal value of arg1.ExamplesThe following three examples all illustrate the same AND operation. These examples ANDthe ASCII values of lowercase letters with the ASCII value of the underscore character,resulting in the ASCII values of the corresponding uppercase letters.WRITE $ZBOOLEAN("abcd","_",1)displays ABCD.The lowercase "a" = [01100001] (ASCII decimal 97)The underscore character "_" = [01011111] (ASCII decimal 95)The uppercase "A" = [01000001] (ASCII decimal 65)The following example performs the same AND operation as the previous example, but usesthe ASCII decimal values of the arguments. The function $ASCII("a") returns the decimalvalue 97 for the first argument:WRITE $ZBOOLEAN($ASCII("a"),95,1)displays 65.The following example performs the same AND operation, using a $CHAR value as thesecond argument:518 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZBOOLEANWRITE $ZBOOLEAN("a",$CHAR(95),1)displays A.The following examples illustrate logical OR:WRITE $ZBOOLEAN(1,0,7)displays 1.WRITE $ZBOOLEAN(1,1,7)displays 1.WRITE $ZBOOLEAN(2,1,7)displays 3.WRITE $ZBOOLEAN(2,2,7)displays 2.WRITE $ZBOOLEAN(3,2,7)displays 3.The following logical OR examples demonstrate the difference between string comparisonsand number comparisons:WRITE $ZBOOLEAN(64,255,7)compares the two values as numbers and displays 255.WRITE $ZBOOLEAN("64","255",7)compares the two values as strings and displays 65.WRITE $ZBOOLEAN(+"64",+"255",7)the plus signs force the comparison of the two values as numbers, and displays 255.The following examples illustrate exclusive OR:WRITE $ZBOOLEAN(1,0,6)displays 1.WRITE $ZBOOLEAN(1,1,6)displays 0.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 519


System and Other FunctionsWRITE $ZBOOLEAN(2,1,6)displays 3.WRITE $ZBOOLEAN(2,2,6)displays 0.WRITE $ZBOOLEAN(3,2,6)displays 1.WRITE $ZBOOLEAN(64,255,6)displays 191.The following example shows a 4-byte entity with all bytes set to 1:WRITE $ZBOOLEAN(5,1,15)displays -1.The following example will set x to 3 bytes with all bits set to 1:SET x=$ZBOOLEAN("abc",0,15)WRITE !,$LENGTH(x)WRITE !,$ASCII(x,1)," ",$ASCII(x,2)," ",$ASCII(x,3)The first WRITE displays 3; the second WRITE displays 255 255 255.NotesInteger ProcessingBefore $ZBOOLEAN performs the bitwise operation, it interprets each numeric value aseither an 8-byte or a 4-byte signed binary value, depending on size. $ZBOOLEAN alwaysinterprets a numeric value as a series of bytes. The boolean operation uses these bytes as astring argument. The result type is the same as the type of arg1.If either arg1 or arg2 is numeric and cannot be represented as an 8-byte signed integer (largerthan 18 decimal digits), a error results. If both arg1 and arg2 are numericand one of them requires 8 bytes to be represented, then both values are interpreted as 8-bytebinary values.After the previous transformations are complete, the given Boolean combination is appliedbit by bit to arg1 and arg2 to yield the result. The result returned is always the same lengthas arg1 (after the above transformations of numeric data). If the length of arg2 is less than520 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


the length of arg1, then arg2 is repeatedly combined with successive substrings of arg1 inleft to right fashion.$ZBOOLEAN always interprets the numeric value as a series of bytes in little-endian order,with the low-order byte first, no matter what the native byte order of your machine is.Internal Structure of $ZBOOLEAN Values$ZBOOLEANThe following table lists the internal rules for $ZBOOLEAN. You do not need to understandthese rules to use $ZBOOLEAN; they are presented here for reference purposes only.There are four possible states of any two bits being compared from within arg1 and arg2. TheBoolean operation generates a true result (=1) if and only if bit_op has the bit mask shownin the table.Bit in arg1Bit in arg2Bit Mask in bit_opDecimalBit Mask in bit_op Binary0081000014010010200101110001EQV and IMP Logical Operators$ZBOOLEAN does not directly support EQV and IMP logical operators. These can be createdby combining simpler logical operations. These logical operators are defined as follows:• EQV is a logical equivalence between two expressions. It is logically identical to ((~arg1)& (~arg2)) ! (arg1 & arg2).• IMP is a logical implication between two expressions. It is logically identical to ~((~arg1)! arg2).See Also• ZZDUMP command• Operators in Using <strong>Caché</strong> <strong>ObjectScript</strong><strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 521


System and Other Functions$ZCONVERTString conversion function.$ZCONVERT(string,mode,trans)$ZCVT(string,mode,trans)ParametersstringmodetransThe string to convert, specified as a quoted string. This string can bespecified as a value, a variable, or an expression.A letter specifying the type of case conversion, specified as a quoted string.Optional — The translation table to use.Description$ZCONVERT converts a string from one form to another. The nature of the conversiondepends on the parameters you use.$ZCONVERT Returns a Converted String$ZCONVERT(string, mode) returns string with the characters converted as specified bymode. The conversions are of two types:• Case conversion• Encoding translationCase conversion changes the case of each letter character in the string. You can change allletter characters in a string to their lowercase, uppercase, or titlecase form. Characters thatare already in the specified case, and characters with no case (usually any non-letter character)in the string are passed through unchanged. To output a literal quote character (“) within astring, input two quote characters (““). For further case conversion options, including non-ASCII and customized case conversion, refer to Customized National Language Translations.Encoding translation translates string between the internal encoding style used on your systemand another encoding style. You can perform input translation; that is, translate string froman external encoding style to the encoding style of your system. You can also perform outputtranslation; that is, translate string from the encoding style of your system to an externalencoding style. For further I/O translation options, including non-ASCII and customizedtranslation, refer to Customized National Language Translations.522 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZCONVERTThe values you can use for mode are as follows:Mode CodeU or uL or lT or tI or iO or oMeaningUppercase translation: Convert all characters in string to uppercase.Lowercase translation: Convert all characters in string to lowercase.Titlecase translation: Convert all characters in string to titlecase.Titlecase is only meaningful for those alphabets (principally EasternEuropean) that have three forms for a letter: uppercase, lowercase,and titlecase. For all other letters, titlecase translation is the same asuppercase translation.Perform input encoding translation on a specified string. For thetwo-argument form, the translation is performed using the currentprocess I/O translation handle. If a current process I/O translationhandle has not been defined, <strong>Caché</strong> performs translation based onthe default process I/O translation table name.Perform output encoding translation on a specified string. For thetwo-argument form, the translation is performed using the currentprocess I/O translation handle. If a current process I/O translationhandle has not been defined, <strong>Caché</strong> performs translation based onthe default process I/O translation table name.If mode is a null string or any value other than the valid characters, you receive a error.When you specify case translation, the two-argument form of $ZCONVERT(string ,"L") isthe functional equivalent of the following form of the $TRANSLATE function:$TRANSLATE(string,"ABC...XYZ","abc...xyz")Titlecase TranslationTitlecase (“T”) mode converts every letter in the string to its titlecase form. Titlecase doesnot selectively uppercase letters based on their position in a word or string. Titlecase is thecase that a letter is represented in when it is the first character of a word in a title. For standardLatin letters, the titlecase form is the same as the uppercase form.Some languages (for example, Croatian) represent particular letters by two letter glyphs. Forexample, “lj” is a single letter in the Croatian alphabet. This letter has three forms: lowercase“lj”, uppercase “LJ”, and titlecase “Lj”. $ZCONVERT titlecase translation is used for thistype of letter conversion.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 523


System and Other FunctionsEncoding Translation$ZCONVERT(string, mode, trans) performs either an input encoding translation or an outputencoding translation on string. In the three-argument form, the mode values you can use areeither "I" or "O". You must define the mode value. The trans value can be a numeric characteror a string that specifies the translation table or translation handle to use.ParametersstringThe string can be specified as a value, a variable, or an expression.modeA letter specifying the type of encoding translation, as shown in the previous table.transThe translation table to use. The trans value can be:• An integer value describing a process I/O translation object (0 for the current process I/Otranslation object.)• A string value describing an I/O translation table name (null string for the default processI/O translation table name.)• A Named table. A named table can be defined in a locale and points to one or two translationtables. Use a named table to define a specific system-to/from-device encoding.Supplied translation tables include HTML, which adds (output mode) or removes (inputmode) HTML escape characters to a string, and URL, which adds (output mode) orremoves (input mode) URL parameter escape characters to a string.• "" (null string), which will use the default process I/O translation table name. (Forequivalent functionality, see the $$GetPDefIO^%NLS() function of the %NLS utility.)ExamplesThe following example returns "HELLO":WRITE $ZCONVERT("Hello","U")The following example returns "hello":WRITE $ZCVT("Hello","L")The following example returns "HELLO":524 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZCRCWRITE $ZCVT("Hello","T")The following example uses the concatenate operator (_) to append and case-convert anaccented character:WRITE "CACH"_$CHAR(201),!, $ZCVT("CACH"_$CHAR(201),"L")returns:CACHÉcachéThe following example converts the angle brackets in the string to HTML escape charactersfor output, returning “&lt;TAG&gt;”WRITE $ZCVT("","O","HTML")Note that how these angle brackets display depends on the output device; try running thisprogram here and then running it from the Terminal prompt.See Also• $ASCII function• $CHAR function• $ZSTRIP function• Pattern Matching operators in Using <strong>Caché</strong> <strong>ObjectScript</strong>• More information on locales in Customized National Language Translations$ZCRCChecksum function.$ZCRC(string,mode,expression)ParametersstringmodeexpressionA string.The checksum method to use.Optional — The initial "seed" value.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 525


System and Other FunctionsDescriptionThe value returned by $ZCRC depends on the parameters you use.• $ZCRC(string,mode) computes and returns a checksum on string. The value of modedetermines the type of checksum $ZCRC computes.• $ZCRC(string,mode,expression) computes and returns a checksum on string using themethod specified by mode. expression supplies an initial "seed" value for running CRCcalculations on multiple strings.ParametersstringA byte string. Can be specified as a value, a variable, or an expression. Only use a byte stringor you will receive a error.modeThe checksum method to use. All checksum methods can be used with 8-bit (ASCII) or 16-bit Unicode (wide) characters. Legal values for mode are:Mode01234567ComputesAn 8-bit byte sumAn 8-bit XOR of the bytesA 16-bit DataTree CRC-CCITTA 16-bit DataTree CRCA 16-bit CRC for XMODEM protocolsA correct 16-bit CRC-CCITTA correct 16-bit CRCA correct 32-bit CRCexpressionAn argument that is an initial "seed" value. $ZCRC adds expression to the checksum generatedfor string. This allows you to run $ZCRC calculations on multiple strings sequentially andobtain the save checksum value as if you had concatenated those strings and run $ZCRC onthe resulting string.526 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


ExamplesThe $ZCRC function in this example returns the byte sum of 131.$ZCYCWRITE $ZCRC("AB",0)The checksum is derived as follows:WRITE $ASCII("A")+$ASCII("B")= 65+66 = 131See Also• $ZCYC function$ZCYCCyclical-redundancy check for data integrity.$ZCYC(string)$ZC(string)ParametersstringA string.Description$ZCYC(string) computes and returns the cyclical-redundancy check value for the string. Itallows two inter-communicating programs to check for data integrity.The sending program transmits a piece of data along with a matching check value that itcalculates using $ZCYC. The receiving program verifies the transmitted data by using $ZCYCto calculate its check value. If the two check values match, the received data is the same asthe sent data.$ZCYC calculates the check value by performing an exclusive OR (XOR) on the binaryrepresentations of all the characters in the string.Use caution when transmitting data between 8-bit and UNICODE (16-bit) implementationsof <strong>Caché</strong>; if a data string does not contain any wide characters, the cyclical-redundancy checkvalues should match.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 527


System and Other FunctionsNote that the $ZCYC value of an 8-bit string is identical to the $ZCRC mode 1 value.ParametersstringA string. Can be specified as a value, a variable, or an expression. String values are enclosedin quotation marks.ExampleIn this example, the first $ZCYC returns 65; the second returns 3; and the third returns 64.SET x= $ZCYC("A"); 1000001 (only one character; no XOR )SET y= $ZCYC("AB"); 1000001 XOR 1000010 -> 0000011SET z= $ZCYC("ABC"); 1000001 XOR 1000010 -> 0000011 | 1000011 -> 100000WRITE !,"x=",x," y=",y," z=",zSee Also• $ZCRC function$ZFInvokes non-<strong>Caché</strong> <strong>ObjectScript</strong> programs or functions from <strong>Caché</strong> <strong>ObjectScript</strong> routines.$ZF("function_name",args)Parametersfunction_nameargsThe name of the function you want to call.Optional — A set of argument values passed to the function.DescriptionThe various forms of the $ZF function allow you to invoke non-<strong>Caché</strong> <strong>ObjectScript</strong> programs(such as shell or operating system commands) or functions from <strong>Caché</strong> <strong>ObjectScript</strong> routines.You can define interfaces or links to functions written in other languages into <strong>Caché</strong> and callthem from <strong>Caché</strong> <strong>ObjectScript</strong> routines using $ZF.$ZF can also be used to:528 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZF• Spawn a child process to execute a program or command: $ZF(–1) and $ZF(–2).• Load a Dynamic Link Library (DLL) then execute functions from that library: $ZF(–3),$ZF(–4), $ZF(–5), and $ZF(–6).These implementations of $ZF take a negative number as the first parameter. They aredescribed in their own reference pages.Parametersfunction_nameThe name of the function you want to call enclosed in quotation marks, or a negative number.argsThe args parameters are in the form: arg1, arg2, arg3, ...argn. The arguments can consist ofsuch items as descriptions of how arguments are passed and the entry point to the C functionyou are calling.NotesCalling UNIX System Services with $ZF<strong>Caché</strong> supports error checking functions for use with UNIX system calls from $ZF. Thesecalls allow you to check for asynchronous events and to set an alarm handler in $ZF. Byusing these UNIX functions you can distinguish between real errors, interrupts,and calls that should be restarted.The function declarations are included in cdzf.h and are described in the following table:Declarationint sigrtclr();int dzfalarm();PurposeClears retry flag.Establishes newSIGALRM handler.NotesShould be called once before usingsigrtchk()On entry to $ZF, the previous handler isautomatically saved. On exit, it is restoredautomatically. A user program should notalter the handling of any other signal.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 529


System and Other FunctionsDeclarationint sigrtchk();PurposeChecks forasynchronous events.NotesShould be called whenever one of the followingsystem calls fails: open(), close(),read(), write(), ioctl(), pause(), any call thatfails when the process receives a signal. Itreturns a code indicating the action the usershould take:-1 = Not a signal. Check for I/O error. Seecontents of errno variable.0 = Other signal. Restart operation frompoint at which it was interrupted.1 = SIGINT/. Exit from $ZF with aSIGTERM "return 0." The System trapsthese signals appropriately.In a typical $ZF function used to control some device, you would code something like this:IF ((fd = open(DEV_NAME, DEV_MODE)) < 0) {; Set some flags; Call zferror; return 0;}The open system call can fail if the process receives a signal. Usually this situation is not anerror and the operation should be restarted. Depending on the signal, however, you mighttake other actions. So, to take account of all the possibilities, consider using the following Ccode:sigrtclr();WHILE (TRUE) {IF (sigrtchk() == 1) { return 1 or 0; }IF ((fd = open(DEV_NAME, DEV_MODE)) < 0) {switch (sigrtchk()) {case -1:/* This is probably a real device error */; Set some flagsCall zferrorreturn 0;case 0:/* A innocuous signal was received. Restart. */; continue;case 1:/* Someone is trying to terminate your job. */Do cleanup workreturn 1 or 0;}}ELSE { break; }/* Code to handle the normal situation: *//* open() system call succeeded */530 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


Remember you must not set any signal handler except through dzfalarm().Calling OpenVMS System Services with $ZFYou can also call OpenVMS system services with $ZF. You define an interface to each non-<strong>Caché</strong> <strong>ObjectScript</strong> routine in a file named CZF.MAR. You can also use $ZF to call OpenVMSSystem Service Routines, invoke DCL Command Procedures, or other high-level languageroutines.$ZF adheres to the VAX Procedure Calling and Condition Handling Standard as describedin the Digital Equipment Corporation publication OpenVMS Programming Interfaces: Callinga System Routine. While all OpenVMS compilers are supposed to adhere to this convention,some compilers may not.You can use $ZF to call DSM intrinsic functions which emulate DSM $ZCalls for VMSSystem Services. For example, you can call $ZF(“GETSYI”) to get system information fora DSM cluster node member.The available DSM intrinsic functions are: GETJPI (job and process information); GETDVI(device characteristics); GETSYI (system information); SETSYM (sets DCL symbol value);GETSYM (returns DCL symbol value); DELSYM (deletes DCL symbol value); CRELOG(creates logical name); TRNLNM (translates logical name); DELLOG (deletes logical name);GETUAI (returns account authorization parameters); GETMSG (returns status code messagetext); SETPRN (sets name of the calling process); SETPRI (sets base priority for a process);OPCOM (sends message to the operator); MOUNT (mounts a device); DISMOUNT (dismountsa device); DIRECTORY (returns the default directory); PARSE (parses a file name);GETFILE (returns file information). For specific function calls for DSM compatibility andconversion, refer to the Using the $ZF Function Calls for DSM article.Translating Strings between Encoding Systems<strong>Caché</strong> supports input-output translation via a $ZF argument type, t (or T), which can bespecified in the following formats:$ZFArgumenttt//t/name/PurposeSpecifies the current process I/O translation object.Specifies the default process I/O translation table name.Specifies a particular I/O translation table name.$ZF conveys the translated string to the external procedure via a counted-byte string placedin the following C structure:<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 531


System and Other Functionstypedef struct zarray {unsigned short len;unsigned char data[1]; /* 1 is a dummy value */} *ZARRAYP;This is also the structure used for the b (or B) argument type.The following $ZF sample function performs a round trip conversion:#include cdzf.hextern int trantest();ZFBEGINZFENTRY("TRANTEST","t/SJIS/ T/SJIS/",trantest)ZFENDint trantest(inbuf,outbuf);ZARRAYP inbuf;/* Buffer containing string that was converted frominternal <strong>Caché</strong> encoding to SJIS encoding before itwas passed to this function */ZARRAYP outbuf; /* Buffer containing string in SJIS encoding that willbe converted back to internal <strong>Caché</strong> encoding beforeit is passed back into the <strong>Caché</strong> environment */{int i;/* Copy data one byte at a time from the input argument bufferto the output argument buffer */for (i = 0; i < inbuf->len; i++)outbuf->data[i] = inbuf->data[i];/* Set number of bytes of data in the output argument buffer */outbuf->len = inbuf->len;}return 0; /* Return success */Note:Conceptually speaking, data flows to and from a $ZF external procedure, as if theexternal procedure were a device. The output component of an I/O translation is usedfor data that is passed to an external procedure because the data is “leaving” the<strong>Caché</strong> environment. The input component of an I/O translation is used for data thatis received from an external procedure because the data is “entering” the <strong>Caché</strong>environment.If the output component of an I/O translation is undefined and your application attempts topass anything but the null string using that I/O translation, <strong>Caché</strong> issues an error, because itdoes not know how to translate the data.If the input component of an I/O translation is undefined and an argument of type stringassociates that I/O translation with a $ZF output argument, <strong>Caché</strong> issues an error, becausean output argument with an undefined translation is purposeless.532 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZFZero-Terminated and Counted Unicode StringsThe $ZF function supports argument types for zero-terminated Unicode strings and countedUnicode strings. These are supported even in versions of <strong>Caché</strong> that do not use Unicodecharacters internally.The argument types for zero-terminated Unicode strings and counted Unicode strings havethe following codes:ArgumentwsPurposePointer to a zero-terminated Unicode character string.Pointer to a counted Unicode character string.For both argument types, the C data type of the Unicode character is an unsigned short. Apointer to a zero-terminated Unicode string is declared as follows:unsigned short *p;A pointer to a counted Unicode string is declared as a pointer to the following C structure:typedef struct zwarray {unsigned short len;unsigned short data[1]; /* 1 is a dummy value */} *ZWARRAYP;For example:ZWARRAYP *p;The len field contains the length of the Unicode character array.The data field contains the characters in the counted Unicode string. The maximum size ofa Unicode string is the maximum $ZF string size, which is an updateable configurationparameter that defaults to 32767.Each Unicode character is two bytes long. This is important to consider when declaringUnicode strings as output arguments, because <strong>Caché</strong> reserves space for the longest string thatmay be passed back. When using the default string size, the total memory consumption fora single Unicode string argument is calculated as follows:32767 maximum characters * 2 bytes per character = 65534 total bytes.This is close to the default maximum memory area allocated for all $ZF arguments, whichis 67584. This maximum $ZF heap area is also an updateable configuration parameter.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 533


System and Other FunctionsError MessagesWhen the $ZF heap area is exhausted, $ZF generates an error. When the $ZF String Stack is exhausted, $ZF generates a error.When $ZF is unable to allocate a buddyblock, it generates a error.Execution from Child Processes and DLLsThe $ZF function can take a negative number as its first parameter. These negative numbersspecify functions that support spawned child processes and Dynamic-Link Libraries (DLLs).Each of these $ZF functions is described in a separate reference page.See Also• $ZF(-1) function• $ZF(-2) function• $ZF(-3) function• $ZF(-4) function• $ZF(-5) function• $ZF(-6) function• Calling Out of <strong>Caché</strong> in Using <strong>Caché</strong> <strong>ObjectScript</strong>• $ZF Function Calls for DSM$ZF(-1)Executes a program or command as a spawned child process and waits for the child processto return.$ZF(-1,progname)ParametersprognameThe command or program to be executed as a child process.Description$ZF(-1) permits a <strong>Caché</strong> <strong>ObjectScript</strong> process to invoke a command of the host operatingsystem. It executes the program or command specified in progname as a spawned child process534 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


from the current console. It waits for the process to return. It returns the child process exitstatus. It returns -1 if a child process could not be forked.On UNIX and VMS systems, $ZF(-1) with no specified parameter launches the default shell.On Windows systems, the progname parameter is mandatory. For further details, see IssuingOperating System Commands from <strong>Caché</strong> in Using <strong>Caché</strong> <strong>ObjectScript</strong>.If the pathname supplied in progname contains a space character, pathname handling isplatform-dependent. VMS permits space characters in pathnames; no special processing isrequired. UNIX permits space characters in pathnames, but a pathname containing spacesmust be enclosed in double quote (“) characters. Windows does not support spaces in pathnames;spaces must be stripped from the supplied pathname. The $ZUTIL(147) functionhandles spaces in pathnames as appropriate to the host platform.$ZF(-1) requires the %System_Callout:U privilege.At the programmer prompt, you can perform the same operations as $ZF(-1) by using anexclamation point (!) or a dollar sign ($) as the first character, followed by the command youwish to execute as a child process. For further details, see Issuing Operating System Commandsfrom <strong>Caché</strong> in Using <strong>Caché</strong> <strong>ObjectScript</strong>.ExampleThe following example uses $ZUTIL(147) to handle a pathname for $ZF(-1). A pathnamecontaining spaces is handled as appropriate for the host platform. A pathname that does notcontain spaces is passed through unchanged.SET x=$ZF(-1,$ZUTIL(147,"C:\\MyTest.txt"))See Also• $ZF(-2) function• $ZUTIL(147) function• Calling Out of <strong>Caché</strong> in Using <strong>Caché</strong> <strong>ObjectScript</strong>$ZF(-1)<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 535


System and Other Functions$ZF(-2)Executes a program or command as a spawned child process and returns immediately.$ZF(-2,progname)ParametersprognameThe command or program to be executed as a child process.Description$ZF(-2) executes the program specified in progname as a spawned child process from thecurrent console. It returns immediately after spawning the child process and does not waitfor the process to terminate. Input and output devices default to the null device.$ZF(-2) does not return the child process exit status. Instead, $ZF(-2) returns zero if the childprocess was created successfully, or -1 if a child process could not be forked. $ZF(-2) permitsa program invoked from <strong>Caché</strong> to continue execution even if <strong>Caché</strong> is terminated.$ZF(-2) closes the parent process principal device (specified in $PRINCIPAL) before executingthe command. This is done because the child process executes concurrently with theparent. If $ZF(-2) did not close $PRINCIPAL, output from the parent and the child wouldbecome intermingled. When using $ZF(-2) you should redirect I/O in the command if youwish to recover output from the child process. For example:SET x=$ZF(-2,"ls -l > mydir.txt")If the pathname supplied in progname contains a space character, pathname handling isplatform-dependent. VMS permits space characters in pathnames; no special processing isrequired. UNIX permits space characters in pathnames, but a pathname containing spacesmust be enclosed in double quote (“) characters. Windows does not support spaces in pathnames;spaces must be stripped from the supplied pathname. The $ZUTIL(147) functionhandles spaces in pathnames as appropriate to the host platform.$ZF(-2) is a privileged operation, which requires the %System_Callout:U privilege.See Also• $ZF(-1) function• $ZUTIL(147) function• $PRINCIPAL special variable536 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZF(-3)• Calling Out of <strong>Caché</strong> in Using <strong>Caché</strong> <strong>ObjectScript</strong>$ZF(-3)Loads a Dynamic-Link Library (DLL) and executes a library function.$ZF(-3,dll_name,func_name,args)Parametersdll_namefunc_nameargsThe name of the dynamic-link library (DLL) to load, specified as aquoted string. When a DLL is already loaded, dll_name can bespecified as a null string ("").Optional — The name of the function to execute within the DLL,specified as a quoted string.Optional — A comma-separated list of arguments to pass to thefunction.DescriptionUse $ZF(-3) to load a Dynamic-Link Library (DLL) and execute the specified function fromthat DLL. $ZF(-3) returns the function's return value.$ZF(-3) can be invoked in any of the following ways:To just load a DLL:SET x=$ZF(-3,"mydll")To load a DLL and execute a function located in that DLL:SET x=$ZF(-3,"mydll","$$myfunc",1)Loading a DLL using $ZF(-3) makes it the current DLL, and automatically unloads the DLLloaded by a previous invocation of $ZF(-3).To execute a function located in a DLL loaded by a previous $ZF(-3), you can speed executionby specifying the current DLL using the null string, as follows:SET x=$ZF(-3,"","$$myfunc2",1)To explicitly unload the current DLL (loaded by a previous $ZF(-3) call):SET x=$ZF(-3,"")<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 537


System and Other Functions$ZF(-3) can load only one DLL. Loading a DLL unloads the previous DLL. You can alsoexplicitly unload the currently loaded DLL, which would result in no currently-loaded DLL.(However, note that $ZF(-3) loads and unloads do not affect $ZF(-4) loads and unloads, asdescribed below.)The DLL name specified can be a full pathname, or a partial pathname. If a partial pathname,<strong>Caché</strong> canonicizes it to the current directory. Generally, DLLs are stored in the binary directory(“bindir”). To locate the binary directory, call the $SYSTEM.Util.BinaryDirectory() method.For further details, refer to the %SYSTEM.Util class in the <strong>Caché</strong> Class <strong>Reference</strong>.NotesDynamic-Link LibrariesA DLL is a binary library that contains routines that can be loaded and called at runtime.When a DLL is loaded, <strong>Caché</strong> finds a function named GetZFTable() within it. IfGetZFTable() is present, it returns a pointer to a table of the functions located in the DLL.Using this table, $ZF(-3) calls the specified function from the DLL.$ZF(-3) and $ZF(-4)Calls to $ZF(-3) can only load one DLL at a time; loading a DLL unloads the previous DLL.To load multiple DLLs concurrently, use $ZF(-4). Loading or unloading a DLL using $ZF(-3)has no effect on DLLs loaded using $ZF(-4).See Also• $ZF(-4) function• $ZF(-5) function• Calling Out of <strong>Caché</strong> in Using <strong>Caché</strong> <strong>ObjectScript</strong>.538 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZF(-4)$ZF(-4)Loads Dynamic-Link Libraries (DLLs).$ZF(-4,n,dll_name,func_name)$ZF(-4,n,dll_index,dll_name)Parametersndll_namedll_indexfunc_nameA code for the type of operation to perform: 1=load DLL by name.2=unload DLL by name. 3=look up function in DLL. 4=unload DLL byindex. 5=create an entry in the system DLL index table. 6=delete anentry in the system DLL index table. 7=create an entry in the processDLL index table. 8=delete an entry in the process DLL index table.Optional — The name of the dynamic-link library (DLL). Used withn=1, 2, 3, 5, or 7.Optional — A user-defined index to a dynamic-link library (DLL) in aDLL index table. Must be a unique, positive, non-zero integer. Thenumbers 1024 through 2047 are reserved for system use. Used withn=4, 5, 6, 7, or 8.Optional — The name of the function to look up within the DLL. Usedonly when n=3.Description$ZF(-4) can be used to establish an ID value for a DLL or for a function within a DLL. TheseID values are used by $ZF(-5) to execute a function.$ZF(-4) can be used to establish an index to a DLL index table. These index values are usedby $ZF(-6) to execute a function.Use the combination of $ZF(-4) and $ZF(-5) or $ZF(-4) and $ZF(-6) to load multiple DLLsand call functions from them. However, if you only wish to call functions from one DLL,you can use $ZF(-3) to load that DLL and call its functions.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 539


System and Other FunctionsEstablishing ID ValuesTo load a DLL and return its ID, use the following syntax:dll_id=$ZF(-4,1,dll_name)To look up a function from a DLL loaded by $ZF(-4,1), and return an ID for that function,use the following syntax:func_id=$ZF(-4,3,dll_id,func_name)To execute a function located by $ZF(-4,3), use $ZF(-5).To unload a specific DLL loaded by $ZF(-4,1), use the following syntax:$ZF(-4,2,dll_id)To unload all DLLs loaded by $ZF(-4,1), use the following syntax:$ZF(-4,2)Establishing Index ValuesTo index a DLL in the system DLL index table, use the following syntax:$ZF(-4,5,dll_index,dll_name)To index a DLL in the process DLL index table, use the following syntax:$ZF(-4,7,dll_index,dll_name)To look up and execute a function indexed by $ZF(-4,5) or $ZF(-4,7), use $ZF(-6).540 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZF(-5)To unload an indexed DLL, use the following syntax:$ZF(-4,4,dll_index)To delete an index entry in the system DLL index table, use the following syntax:$ZF(-4,6,dll_index)To delete an index entry in the process DLL index table, use the following syntax:$ZF(-4,8,dll_index)To delete all index entries in the process DLL index table, use the following syntax:$ZF(-4,8)For a detailed description of how to use $ZF(-4) and $ZF(-6), refer to Calling Out of <strong>Caché</strong>in Using <strong>Caché</strong> <strong>ObjectScript</strong>.See Also• $ZF(-3) function• $ZF(-5) function• $ZF(-6) function• Calling Out of <strong>Caché</strong> in Using <strong>Caché</strong> <strong>ObjectScript</strong>$ZF(-5)Executes a DLL function loaded using $ZF(-4).$ZF(-5,dll_id,func_id,args)Parametersdll_idfunc_idargsThe ID value for the dynamic-link library (DLL), as supplied by $ZF(-4).The ID value of the function within the DLL as supplied by $ZF(-4).Optional — One or more arguments passed to the called function.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 541


System and Other FunctionsDescriptionTo execute a function located in a DLL loaded using $ZF(-4), use the following syntax:return=$ZF(-5,dll_id,func_id,args)See Also• $ZF(-4) function• Calling Out of <strong>Caché</strong> in Using <strong>Caché</strong> <strong>ObjectScript</strong>$ZF(-6)Executes a DDL function indexed using $ZF(-4).$ZF(-6,dll_index,func_ID,args)Parametersdll_indexfunc_IDargsA user-specified index to a DLL file name in the DLL index tables, from$ZF(-4).Optional — The ID value of the function within the DLL as supplied by$ZF(-4). If omitted, call verifies the validity of DLL_index, loads theimage, and returns the image location.Optional — The argument(s) to pass to the function, if any, specifiedas a comma-separated list.Description$ZF(-6) provides a fast Dynamic Link Library (DLL) function interface using a user-definedindex for a DLL file name. You establish this user-defined index in $ZF(-4) by assigning aninteger (dll_index) to uniquely associate with a dll_name. You can place this entry in eithera process DLL index table, or a system DLL index table.Both $ZF(-5) and $ZF(-6) can be used to execute a function from a DLL. which has beenlocated by $ZF(-4).For a detailed description of how to use $ZF(-6), refer to Calling Out of <strong>Caché</strong> in Using<strong>Caché</strong> <strong>ObjectScript</strong>.542 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


See Also• $ZF(-3) function• $ZF(-4) function• $ZF(-5) function• Calling Out of <strong>Caché</strong> in Using <strong>Caché</strong> <strong>ObjectScript</strong>$ZINCREMENT$ZINCREMENTAdds a specified increment to the existing value of a global or local variable.$ZINCREMENT(variable,num)ParametersvariablenumThe variable whose value is to be incremented.Optional — The numeric increment you want to add to variable. If youdo not specify num for the second argument, <strong>Caché</strong> defaults toincrementing variable by 1.Description$ZINCREMENT is an alias of $INCREMENT. Please refer to $INCREMENT for informationon its usage.See Also• $INCREMENT function<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 543


System and Other Functions$ZISWIDEChecks whether a string contains any 16-bit wide characters.$ZISWIDE(string)$ZIS(string)ParametersstringA string of one or more characters, enclosed in quotation marks.Description$ZISWIDE is a boolean function used to check whether a string contains any 16-bit widecharacter values. It returns one of the following values:01All characters have ASCII values 255 or less (8-bit characters). A null string ("")also returns 0.One or more characters have an ASCII value greater than 255 (wide characters).Note that in a Unicode version of <strong>Caché</strong>, all characters are 16-bits in length. $ZISWIDEchecks the character values to determine if they are in the ASCII range (0-255), and thuscould be represented by 8 bits, or in the wide character range (256-65535) and thus use all16 bits of the Unicode character.ExampleThe first two examples test strings that contain all narrow (8-bit) character values and return0. The third example tests a string containing a wide character value (the second character),and therefore, returns 1:WRITE !,$ZISWIDE("abcd")WRITE !,$ZISWIDE($CHAR(71,83,77))WRITE !,$ZISWIDE($CHAR(71,300,77))See Also• $ZPOSITION function• $ZWASCII function• $ZWCHAR function• $ZWIDTH function544 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZLASCII$ZLASCIIReturns the numeric interpretation of a four-byte string.$ZLASCII(string,position)$ZLA(string,position)ParametersstringpositionA string that can be specified as a value, a variable, or an expression.Optional — A starting position in the string. The default is 1.DescriptionThe value $ZLASCII returns depends on the parameters you use.• $ZLASCII(string) returns a numeric interpretation of a four-byte string, starting withthe first character position of string.• $ZLASCII(string,position) returns a numeric interpretation of a four-byte string beginningat the starting position specified by position.Notes$ZLASCII, $ZWASCII, and $ASCII$ZLASCII(string) is similar to $ASCII except that it operates on 32-bit double words insteadof 8-bit bytes. To operate on 16-bit words, use the $ZWASCII function.$ZLASCII(string,position) is the functional equivalent of:$ASCII(string,position+3)*256 + $ASCII(string,position+2)*256 +$ASCII(string,position+1)*256 + $ASCII(string,position)$ZLASCII and $ZLCHARThe $ZLCHAR function is the logical inverse of the $ZLASCII function. For example:SET x=$ZLASCII("abcd")WRITE !,xSET y=$ZLCHAR(x)WRITE !,yGiven “abcd” $ZLASCII returns 1684234849. Given 1684234849 $ZLCHAR returns “abcd”.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 545


System and Other FunctionsSee Also• $ASCII function• $ZLCHAR function• $ZWASCII function$ZLCHARReturns the requested four-byte string.$ZLCHAR(n)$ZLC(n)ParameternA positive integer that can be specified as a value, a variable, or an expression.Description$ZLCHAR returns a four-byte string for n.Notes$ZLASCII and $ZLCHARThe $ZLASCII function is the logical inverse of $ZLCHAR. For example:SET x=$ZLASCII("abcd")WRITE !,xSET y=$ZLCHAR(x)WRITE !,yGiven “abcd” $ZLASCII returns 1684234849. Given 1684234849 $ZLCHAR returns “abcd”.$ZLCHAR, $ZWCHAR, and $CHAR$ZLCHAR is similar to the $CHAR function, except that it operates on 32–bit double wordsrather than 8–bit bytes. To operate on 16–bit words, use the $ZWCHAR function.$ZLCHAR is the functional equivalent of the following form of $CHAR:SET n=$ZLASCII("abcd")WRITE !,nWRITE !,$CHAR(n#256,n\256#256,n\(256**2)#256,n\(256**3))546 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


Given “abcd” $ZLASCII returns 1684234849. Given 1684234849, this $CHAR statementreturns “abcd”.See Also• $CHAR function• $ZLASCII function• $ZWCHAR function$ZNAME$ZNAMEValidates the specified name string as a legal identifier.$ZNAME(string,n,lang)ParametersstringnlangThe name to evaluate, specified as a quoted string.Optional — An integer code specifying the type of name validation toperform. The default is 0.Optional — An integer code specifying the language mode to use whenvalidating string. The default is to use the current language mode.Description$ZNAME returns 1 (true) if the string parameter is a legal identifier. Otherwise, $ZNAMEreturns 0 (false). The optional n parameter determines what type of name validation to performon the string. If this parameter is omitted, the validation defaults to local variable name conventions.The optional lang parameter specifies what language mode conventions to applyto the validation.The valid identifier characters for your locale are defined in the National Language Support(NLS) Identifier locale setting; they are not user-modifiable. Refer to Customized NationalLanguage Translations for further details on NLS.$ZNAME only performs character validation; it does not perform string length validationfor identifiers.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 547


System and Other FunctionsParametersstringA quoted string to validate as a legal identifier name. The characters a valid string can containdepend both on the type of identifier to validate (specified by n), the language mode (lang),and the definition of your locale. By default, the following are valid identifier characters in<strong>Caché</strong>:• Uppercase letters: A through Z (ASCII 65–90)• Lowercase letters: a through z (ASCII 97–122)• Letters with accent marks: (ASCII 192–255, exclusive of ASCII 215 and 247)• Digits: 0 through 9 (ASCII 48–57) subject to positional restrictions for some identifiers• The percent sign: % (ASCII 37) subject to positional restrictions for some identifiersnAn integer code specifying the type of name validation to perform:548 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZNAMEValue0123456MeaningValidate a local variable name.Validate a routine name.Validate a tag (label) name.Validate a global name.Validate a fully-qualified class name.Validate a method name.Validate a property nameRestricted CharactersFirst character only: %Subsequent characters only: digits0–9Subsequent characters only:digits 0–9First character only: %First character only: %Subsequent characters only: digits0–9First character only: %Subsequent characters only: digits0–9First character only: %Subsequent characters only: digits0–9First character only: %Subsequent characters only: digits0–9If n = 0 (or not specified), an identifier that passes validation may be used for any type of<strong>Caché</strong> <strong>ObjectScript</strong> name, except routine names. The first character of a valid identifier mustbe either a percent sign (%) or a valid letter character. The second and subsequent charactersof a valid identifier must be either a valid letter character or a digit.If n = 1, an identifier that passes validation may be used for routine names. In <strong>Caché</strong><strong>ObjectScript</strong> routine names, the first character must be either a percent sign (%) or a validletter character. The second and subsequent characters of a routine name may be either apercent sign (%), a valid letter character, or a digit. Thus, routine names differ from othertypes of names because they can include a percent sign (%) anywhere in the name.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 549


System and Other FunctionslangAn integer code specifying the language mode to use for validation. <strong>Caché</strong> applies the conventionsof the specified language mode to the validation without changing the current languagemode. The default is for $ZNAME to use the language mode conventions of the currentlanguage mode. To determine or to change the current language mode, and for a list ofavailable language mode, see the $ZUTIL(55) function.ExamplesThe following example shows the $ZNAME function validating the expressions as true (1).The last example succeeds because with n = 1, $ZNAME performs validation for routinenames; routine names can have a percent sign as any character of the name.WRITE !,$ZNAME("A")WRITE !,$ZNAME("A1")WRITE !,$ZNAME("%A1",0)WRITE !,$ZNAME("%A1",1)WRITE !,$ZNAME("A%1",1)The following example fails validation (returns 0) because the first character of a local variablename cannot be a digit.WRITE $ZNAME("1A")The following example fails validation because with n = 0, $ZNAME performs a local variablename validation; such names cannot contain a percent sign unless it is the first character ofthe name:WRITE $ZNAME("A%1",0)The following example shows the full set of valid identifier characters for local variablenames. These valid identifier characters include the letter characters ASCII 192 throughASCII 255 (with the exceptions of ASCII 215 and ASCII 247, which are arithmetic symbols):FOR n=1:1:500 {IF $ZNAME("A"_$CHAR(n),0) & $ZNAME($CHAR(n),0){WRITE !,$ZNAME($CHAR(n))," ASCII code=",n," Char.=",$CHAR(n) }ELSEIF $ZNAME($CHAR(n),0){WRITE !,$ZNAME($CHAR(n))," ASCII code=",n," 1st Char.=",$CHAR(n) }ELSEIF $ZNAME("A"_$CHAR(n),0){WRITE !,$ZNAME("A"_$CHAR(n))," ASCII code=",n," Subseq. Char.=",$CHAR(n) }ELSE { }}WRITE !,"All done"NotesNot all legal identifiers may be used for global variable names; wide characters cannot beused in global variable names.550 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


A valid label name may have a digit as its first character. Therefore, you must specify n=2when validating a label name, rather than using $ZNAME default validation.SQL identifiers may include punctuation characters (underscore (_), at sign (@), pound sign(#), and dollar sign ($)) that are not valid characters in <strong>Caché</strong> <strong>ObjectScript</strong> identifiers. SQLroutine names may not include the percent sign (%) at any location other than the first character.For further details, see Identifier in the <strong>Caché</strong> SQL <strong>Reference</strong>.See Also• $ZUTIL(55) function• Cache <strong>ObjectScript</strong> symbols table• Cache SQL symbols table$ZNEXT$ZNEXTReturns a full reference to the next array node.$ZNEXT(global-reference)Parameterglobal-referenceA subscripted global array node. The subscript is requiredbecause it provides the starting point. You cannot specifyjust the array name.Description$ZNEXT returns a full reference to the array node defined next in the collating sequenceafter the specified array node. $ZNEXT accepts a naked global reference. For further details,see Naked Global <strong>Reference</strong> in Using <strong>Caché</strong> Multi-Dimensional Storage.$ZNEXT is similar to the $QUERY function except that $ZNEXT uses “–1” as the startingpoint and failure code, while $QUERY uses the null string ("").ExamplesThe following example uses $ZNEXT to list the subscripts of a global:<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 551


System and Other FunctionsZNSPACE "samples"SET x=^CinemaooFilmCategoryI(-1)LoopSET a=$ZNEXT(x)IF a=-1 {WRITE !,"All done"QUIT }ELSE {SET x=aWRITE !,aGOTO Loop }The following example uses $QUERY to list the subscripts of a global:ZNSPACE "samples"SET x=^CinemaooFilmCategoryI("")LoopSET a=$QUERY(x)IF a="" {WRITE !,"All done"QUIT }ELSE {SET x=aWRITE !,aGOTO Loop }See Also• $QUERY function$ZORDERReturns the full reference for the next array node subscript.$ZORDER(variable)ParametervariableName of a subscripted local or global variable, or the null string. It canbe a value, a variable, or an expression.Description$ZORDER returns the full reference for the next array node subscript that follows the nodeindicated by the variable parameter. The variable can be a local or global subscripted arraynode. The returned subscript is at the same level as the one for the specified variable. If thereis no subsequent array node at the variable's node level, $ZORDER returns the null string("").552 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZORDER is provided for backward compatibility only. It is identical to the $QUERYfunction. New programs should use $QUERY instead of $ZORDER.Notes$ZORDER and the Naked Indicator$ZORDER can be used with a naked global reference. If the naked indicator is undefined,$ZORDER generates a error. If the naked indicator references the last elementin an array, $ZORDER generates an error.When you attempt to use the naked indicator after $ZORDER has generated an error at the end of an array, the naked indicator references the last element in thearray.See Also• $QUERY function$ZPOSITION$ZPOSITIONReturns the number of characters in an expression that can fit within a specified field width.$ZPOSITION(expression,field,pitch)ParametersexpressionfieldpitchA string expression.An integer expression that specifies field width.Optional — A numeric expression that specifies the pitch value touse for full-width characters. The default is 2. Other permissiblevalues are 1, 1.25, and 1.5.Description$ZPOSITION is a DSM-J function available in <strong>Caché</strong> <strong>ObjectScript</strong>. $ZPOSITION returnsthe number of characters in expression that can fit within the field value. The pitch valuedetermines the width to use for full-width characters. All other characters receive a defaultwidth of 1 and are considered to be half-width. Because half-width characters count as 1,field also expresses the number of half-width characters that fit in field.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 553


System and Other Functions$ZPOSITION adds the widths of the characters in the expression one at a time until thecumulative width equals the value of field or until there are no more characters in expression.The result is thus the number of characters that will fit within the specified field valueincluding any fractional part of a character that would not completely fit.Note:$ZPOSITION can be abbreviated as $ZP in DSM-J mode. This abbreviation cannotbe used in <strong>Caché</strong> mode.ExamplesIn the following example, assume that the variable string contains two half-width charactersfollowed by a full-width character.WRITE $ZPOSITION(string,3,1.5)returns 2.6666666666666666667.In the above example, the first two characters in string fit in the specified field width withone left over. The third character in string, a full-width character with a width of 1.5 (determinedby the pitch argument), would not completely fit, although two thirds (1/1.5) of thecharacter would fit. The fractional part of the result indicates that fact.In the following example, string is now a string that contains a full-width character followedby two half-width characters. The result returned is 2.5:WRITE $ZPOSITION(string,3,1.5)The results are now different. This is because the first two characters, which have a combinedwidth of 2.5, would completely fit with .5 left over. Even so, only half of the third character(.5/1) would fit.Finally, if string is a string that contains three half-width characters then all three characterswould completely (and exactly) fit, and the result would be 3:WRITE $ZPOSITION(string,3,1.5)Note:Full-width characters are determined by examining the pattern-match table loadedfor your <strong>Caché</strong> process. Any character with the full-width attribute is considered tobe a full-width character. The special ZFWCHARZ patcode can be used to checkfor this attribute (for example, char?1ZFWCHARZ). See the description of the $X/$YTab in Customized National Language Translations for more information about thefull-width attribute.554 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


See Also• $ZWIDTH function$ZPREVIOUS$ZPREVIOUSReturns the previous array node subscript for the specified variable.$ZPREVIOUS(variable)$ZP(variable)ParametervariableName of local or global array variable or the null string. It can be specifiedas a value, a variable, or an expression.Description$ZPREVIOUS returns the previous array node subscript for the specified variable.$ZPREVIOUS is similar to the $ORDER function, except that it returns the previous, ratherthat the next, subscript in the collation sequence.You can use it to traverse a global in reverse subscript order. To start at the last subscript ona given level, specify the null string for the subscript reference. $ZPREVIOUS returns thenull string after it returns the first subscript on the root level.As with $ORDER, you can use $ZPREVIOUS on both local and global variables.Use of $ZPREVIOUS is discouraged. Rather, use the form $ORDER(variable,-1).ExampleGiven the array node definitions shown, and starting with the last subscript, $ZPREVIOUSreturns the following results:SET ^ABC(1)=1SET ^ABC(2)=2SET ^ABC(3)=3SET x=$ZPREVIOUS(^ABC("")) ; 3WRITE !,"Third is ",xSET x=$ZPREVIOUS(^ABC(x)) ; 2WRITE !,"Second is ",xSET x=$ZPREVIOUS(^ABC(x)) ; 1WRITE !,"First is ",xSET x=$ZPREVIOUS(^ABC(x)) ; ""WRITE !,"Top is ",x<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 555


System and Other FunctionsSee Also• $ORDER function• $ZNEXT function• $ZREFERENCE special variable$ZSEARCHReturns the full file specification, pathname and filename, of a specified file.$ZSEARCH(target)$ZSE(target)ParametertargetA filename, a pathname, or a null string. May contain one or more * or ?wildcard characters.Description$ZSEARCH returns the full file specification (pathname and filename) of a specified targetfile. The file name may contain wild cards so that $ZSEARCH can return a series of fullyqualified pathnames that satisfy the wild carding.If the target parameter does not specify a pathname, $ZSEARCH searches the currentworking directory. $ZSEARCH applies the rules in its matching process in the followingorder:1. $ZSEARCH scans the target to see if it is surrounded with percent characters (%). If$ZSEARCH finds such text, it treats the string as an environment variable. $ZSEARCHperforms name translation on the string.2. $ZSEARCH scans the string that results from the previous step to find the final slashcharacter. If $ZSEARCH finds a final slash, it uses the string up to, but not including,the final slash as the path or directory to be searched. If $ZSEARCH does not find afinal slash, it searches the current working directory, which is determined by the currentnamespace.3. If $ZSEARCH found a final slash in the previous step, it uses the portion of the targetstring following the final slash as the file name search pattern. If $ZSEARCH did not556 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


find a final slash in the previous step, it uses the whole string that results from Step 1 asthe file name search pattern.The file name search pattern can be any legal file name string or a file name wildcardexpression. The first file name that matches the search pattern is returned as the $ZSEARCHfunction value. Which is the first matching file is platform-dependent (as described in theNotes section).If the next invocation of $ZSEARCH specifies the null string as the target, $ZSEARCHcontinues with the previous target and returns the next file name that matches the searchpattern. When there are no more files that match the search pattern, $ZSEARCH returns anull string.The $ZSEARCH function returns the full pathname of an existing file or directory. The$ZUTIL(12) function returns the full pathname of a specified file or directory; dependingon options selected, it can optionally verify the existence of the file, and either preserveuppercase letters in the pathname or convert all letters to lowercase. $ZUTIL(12) cannot usewildcards.Wildcards$ZSEARCH$ZSEARCH allows the use of the following wildcard expressions within the quoted targetstring.Wildcard*?MatchMatches any string of zero or more characters.Matches any single character. On VMS systems, this wildcard is the %character.These wildcards follow the host platform's usage rules. On Windows, $ZSEARCH performsa case-independent search, then returns the actual case of the located file or directory. Forexample, “j*” can match “JOURNAL”, “journal”, or “Journal”; the actual directory name is“Journal”, which is what is returned.On Windows and UNIX systems you can also use the following standard pathname symbols:a single dot (.) to specify the current directory, or a double dot (..) to specify its parent directory.These symbols can be used in combination with wildcard characters.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 557


System and Other FunctionsParameterstargetThe following are the available types of values for the target parameter:Target Typepath namefile namenull string ("")DescriptionAn expression that evaluates to a string specifying the path to the fileor group of files you want to list.A file name. The default location is the current dataset.Returns the next matching file name from the previous $ZSEARCH.ExamplesThe following Windows examples find all files ending with “.DAT” as a file extension inthe SAMPLES namespace.ZNSPACE "SAMPLES"SET file=$ZSEARCH("*.DAT")WHILE file'="" {WRITE !,fileSET file=$ZSEARCH("")}WRITE !,"That is all the matching files"QUITreturns:c:\cachesys\mgr\samples\CACHE.DATThe following Windows example finds all files beginning with the letter “c” in the SAMPLESnamespace.ZNSPACE "SAMPLES"SET file=$ZSEARCH("c*")WHILE file'="" {WRITE !,fileSET file=$ZSEARCH("")}WRITE !,"That is all the matching files"QUITreturns:c:\cachesys\mgr\samples\CACHE.DATc:\cachesys\mgr\samples\cache.lck558 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


NotesDirectory LockingIn order to give accurate results, the process keeps the directory open until $ZSEARCH hasreturned all files in the directory (that is, until $ZSEARCH returns a null string, or a new$ZSEARCH is started). This may prevent other operations, such as deleting the directory.When you start a $ZSEARCH you should always repeat the $ZSEARCH("") until it returnsa null string. An alternative, if you do not want to retrieve all files, is to issue $ZSEARCHwith a file name that you know does not exist, such as $ZSEARCH(-1).Windows SupportFor Windows, the target parameter is a standard file specification, which may contain wildcardcharacters (* and ?). On Windows systems, the * wildcard can be used to match a dot, butthe ? wildcard cannot. Within a name element, ? wildcards cannot match zero characters;however, at the end of a name element trailing ? wildcards are ignored when they match zerocharacters.If you do not specify a directory, the current working directory is used. $ZSEARCH returnsthe first matching entry in the directory in alphabetical order. It returns the full file specificationor fully qualified pathname.When performing a search, Windows 2000 and NT check only the first three characters of afilename extension suffix. Therefore, $ZSEARCH *.txt would return not only a.txt andfred.txt, but also a.txt2, fred.txta, and so forth.UNIX SupportFor UNIX, the target parameter is a standard UNIX file specification, which may containwildcard characters (* and ?). If you do not specify a directory, the current working directoryis used.For UNIX, $ZSEARCH returns the first active entry in the directory. Since UNIX does notkeep the directory entries in alphabetical order, the returned values are not in alphabeticalorder. Unlike Windows platforms, the $ZSEARCH function does not return the full filespecification or fully qualified pathnames, unless the current working directory is used.VMS Support$ZSEARCHFor VMS, the target parameter is a standard VMS file specification, which may containwildcard characters (* and %). If you do not specify a directory, the current working directoryis used. For VMS, there is no substitution of environment variables or scanning for a slashcharacter in the target.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 559


System and Other FunctionsFor VMS, $ZSEARCH returns the first active entry in the directory. $ZSEARCH returnsthe full file specification, including device and directory.See Also• $ZUTIL(12) — Translate file name to canonical form function• $ZUTIL(15) — Translate RMS file name to canonical form function$ZSEEKEstablishes a new offset into the current sequential file.$ZSEEK(offset,mode)ParametersoffsetmodeThe offset into the current file.Optional — An integer value that determines the relative position of theoffset. The default is 0.Description$ZSEEK establishes a new offset into the current device. The current device must be asequential file. If the current device is not a sequential file, $ZSEEK generates a error.The mode parameter determines the point from which offset is based. Called without parameters,$ZSEEK returns the current position in the fileIf there is no specifically set current device, $ZSEEK assumes that the device is the principaldevice.ParametersoffsetThe offset (in characters) from the point established by mode.modeThe valid values are:560 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZSORT012Offset is relative to the beginning of the file (absolute).Offset is relative to the current position.Offset is relative to the end of the file.If you do not specify a mode value, $ZSEEK assumes a mode value of 0.See Also• OPEN command• CLOSE command• I/O Devices and Commands in <strong>Caché</strong> I/O Device Guide• Sequential File I/O in <strong>Caché</strong> I/O Device Guide$ZSORTReturns the next subscript in the array of the specified subscripted variable.$ZSORT(variable,direction)ParametersvariabledirectionA subscripted local or global variable. The subscript is required; youcannot specify just the array name.Optional — The subscript order in which to traverse the target array.Use 1 (the default) for ascending subscript order and -1 for descendingsubscript order.Description$ZSORT returns the next subscript in the subscripted variable. The variable parameter canspecify a subscripted local or global variable. $ZSORT is identical to the $ORDER functionin <strong>Caché</strong>.See Also• $ORDER function• $ZORDER function<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 561


System and Other Functions$ZSTRIPRemoves types of characters and individual characters from a specified string.$ZSTRIP(string,action,remchar,keepchar)ParametersstringactionremcharkeepcharThe string to be stripped.What to strip from string, specified as an action to be performed and themasks to be used. Specified as a quoted string.Optional — A string of additional specific characters to remove that arenot covered by the action parameter's mask code.Optional — A string of specific characters to not remove that aredesignated for removal by the action parameter's mask code.DescriptionThe $ZSTRIP function removes types of characters and individual characters from thespecified string. You specify the general types or position of the characters to remove throughthe action parameter. You can modify the effects of the action by specifying individualcharacters to remove or keep through the remchar and keepchar parameters.For further information, refer to the Pattern Matching Operators section of Using <strong>Caché</strong><strong>ObjectScript</strong>.ParametersactionA string indicating what characters to strip, specified as an action code followed by one ormore mask codes.Action Codes*Strip leading characters that match the masks.Strip trailing characters that match the masks.Strip all characters that match the masks.Strip leading and trailing characters that match the mask specification.562 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZSTRIPMask CodesEAPCNLUWStrip everything.Strip all alphabetic characters.Strip punctuation characters, including blank spaces.Strip control characters (0-31, 127-159).Strip numeric characters.Strip lowercase alphabetic characters.Strip uppercase alphabetic characters.Strip whitespaces ($C(9), $C(32), $C(160)).You can also place a Unary Not (') before a mask character to mean don't remove charactersof this type. All masks without a Unary Not must precede the masks with a Unary Not. Maskcodes can be specified as uppercase or lowercase characters.remcharAdditional characters to remove. For example, if you specified in the action parameter thatyou want to remove all numeric characters ("*N"), but also wanted to remove lowercase t,you would add the string “t” as the remchar parameter.keepcharSpecific characters not to remove. For example, if you specified that you wanted to removeall white spaces and alphabetic characters (*WA), but preserve uppercase M, you would addthe string “M” as the keepchar parameter.ExamplesThe following example creates a string, then strips out all alphabetic characters, except lowercasecharacters ('L). As a result, the string still contains the lowercase characters k, d, andp:SET str="kd p0932832 "_$CHAR(9)_"DD$#)($#J"WRITE $ZSTRIP(str,"*A'L")returns: kd p0932832 $#)($#The following example creates the same string, then strips out all white spaces and allalphabetic characters, except lowercase characters ('L). However, the example uses theremchar parameter to strip the lowercase d while preserving all other lowercase characters:<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 563


System and Other FunctionsSET str="kd p0932832 "_$CHAR(9)_"DD$#)($#J"WRITE $ZSTRIP(str,"*WA'L","d")returns: kp0932832$#)($#The following example again creates the same string, then strips out all white spaces and allalphabetic characters, except lowercase characters ('L). In this case, the example does notspecify a remchar parameter value (but does specify the delimiting commas), but does specifythe keepchar parameter to preserve uppercase D:SET str="kd p0932832 "_$CHAR(9)_"DD$#)($#J"WRITE $ZSTRIP(str,"*WA'L",,"D")returns: kdp0932832DD$#)($#The following example generates a error. A mask without a Unary Not (W)is not allowed to follow a mask with a Unary Not ('U):SET str="kd p0932832 "_$CHAR(9)_"DD$#)($#J"WRITE $ZSTRIP(str,"*A'UW",,$CHAR(9))See Also• $EXTRACT function• $ZCONVERT function• Pattern Matching operators in Using <strong>Caché</strong> <strong>ObjectScript</strong>564 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(4)$ZUTIL(4)Terminates a <strong>Caché</strong> process.$ZUTIL(4,pid,flag)$ZU(4,pid,flag)ParameterspidflagThe process ID (pid) of the <strong>Caché</strong> process you wish to terminate.Optional — A positive or negative integer.A negative integer flag governs process termination operations.You can specify a value of -65 to force termination when theprocess to be terminated is a system daemon, or is in an unresolvedtransaction state. Other negative integer values arereserved for internal use only.A positive integer is used as an exit status code that <strong>Caché</strong> returnsto the host operating system upon termination. These values canbe used in shell procedures. The standard values for exit statuscodes are 0 for UNIX and Windows systems, and 1 for VMSsystems.DescriptionThe $ZUTIL(4) function causes the specified process to terminate and returns execution tothe operating system command level (OpenVMS DCL command level, UNIX shell or Windowsprogram manager). $ZUTIL(4) returns a numeric value indicating success or failure(see table below). When a process issues $ZUTIL(4) against itself, $ZUTIL(4) completesexecution, including issuing its return code, before terminating the process.One common reason for failure of $ZUTIL(4,pid) is that the specified pid is the process IDof a <strong>Caché</strong> system daemon process. To terminate a system daemon process, you can specify$ZUTIL(4,pid,-65). This optional -65 option permits termination of system daemon processes.The optional -65 option also has an effect on termination processing of non-daemon processes.If a process is a halt or rollback state, issuing $ZUTIL(4,pid) returns the -4 error code, andtransaction integrity is maintained. Issuing $ZUTIL(4,pid,-65) terminates the process; <strong>Caché</strong>does not roll back the open transaction, but does release all transaction locks. This may leavea transaction in an inconsistent state.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 565


System and Other FunctionsReturn Values$ZUTIL(4) returns the following values:Value10-1-2-3-4MeaningSuccess. $ZUTIL(4) successfully caused the process to exit.Failure. The process is a system daemon process, such as Write Daemon.Neither $ZUTIL(4) nor the RESJOB utility (which uses it) can terminate asystem daemon, unless you specify $ZUTIL(4,pid,-65).Failure. The process is non-responsive.Failure. The process is inactive, a ghost or "dead" process.Failure. The process is not a <strong>Caché</strong> process. It is not on the <strong>Caché</strong> job table.Failure. The process has an open transaction that is currently in a halt orrollback state and cannot be terminated unless you specify $ZUTIL(4,pid,-65).ExamplesThe following example causes process number 1584 to exit:SET procid=1584SET x=$ZUTIL(4,procid)IF x=1 { WRITE "Success: ",procid," terminated" }ELSEIF x=0 {WRITE "Failure: ",procid," is a daemon",!WRITE "Use the $ZUTIL(4,pid,-65) syntax" }ELSEIF x=-3 { WRITE "Process ",procid," not recognized" }ELSEIF x=-4 { WRITE "Process ",procid," in halt or rollback" }ELSE { WRITE "Failure: $ZUTIL(4) returned ",x," for ",procid }NotesTo determine the process IDs of all currently running processes, go to the System ManagementPortal, and select the Processes option.OpenVMS: $ZUTIL(4,pid) is the internal function called by the RESJOB utility.See Also• HALT command• JOB command566 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(5)$ZUTIL(5)Returns current namespace or switches to another namespace.$ZUTIL(5,current)$ZU(5,current)ParameterscurrentOptional — Namespace to be made current, enclosed in quotation marks.DescriptionThis function can be used to return a job's current namespace or to switch a job's currentnamespace to another namespace:• To return the job's current namespace, use $ZUTIL(5) with no argument.• To change the current namespace, use $ZUTIL(5) with the namespace name as the secondargument.After you issue $ZUTIL(5,current), <strong>Caché</strong> draws routines and globals from the <strong>Caché</strong>database in this new namespace. Your effective working namespace also changes.ParameterscurrentThis field specifies the namespace that will be made current. Enclose the namespace namein double quotes. The namespace you use can be an explicit namespace or an impliednamespace. An implied namespace is a directory path or OpenVMS file specification precededby two caret characters: either "^^dir" (on the current system), or "^system^dir".Namespace names are case-insensitive. <strong>Caché</strong> always displays explicit namespace names inall uppercase letters, and implied namespace names in all lowercase letters.Notes$ZUTIL(5,current) retains the information <strong>Caché</strong> needs to return from routines in the newnamespace. When a routine in the new namespace quits, it returns correctly to the routinethat called it, which may return to its caller in the same or other namespaces, and so on.Subsequent routine calls, however, continue to refer to the namespace named in$ZUTIL(5,current).<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 567


System and Other FunctionsThus, if you issue $ZUTIL(5,current) and then issue OPEN for a sequential file withoutspecifying a namespace, the operating system either:• Finds the file in current• Creates the file in current if the file does not existIf you issue $ZUTIL(5,current) in a subroutine, the original routine finishes; however,routines called are taken from the new namespace, current. When you halt from <strong>Caché</strong>, yournamespace reverts to the one you were in when you entered <strong>Caché</strong>.If you incorporate $ZUTIL(5,current) into a library routine from the system manager'snamespace (%SYS), you give all programmers access to all namespaces regardless of theirUIC or privilege level.When using $ZUTIL(5) to change the current namespace, <strong>Caché</strong> clears the global vectors.However, when issuing a $ZUTIL(5,current), where current is the current namespace (inother words, not changing the namespace), <strong>Caché</strong> does not clear global vectors. If you wishto clear global vectors without changing the current namespace, use $ZUTIL(69,43,1) beforecalling $ZUTIL(5).If you wish to have a process reference the routines in another namespace, without changingthe current namespace, use $ZUTIL(20) or $ZUTIL(39).See Also• ZNSPACE command• $ZUTIL(20) Specify namespace to search for routines function• $ZUTIL(39) Specify namespace to search for % routines function• $ZUTIL(68,43) Disable or Enable Clearing of Global Vectors for the Current Processfunction• $ZUTIL(69,43) Disable or Enable Clearing of Global Vectors System-wide function• $ZUTIL(90,10) Test Whether a Namespace is Defined function• $ZNSPACE special variable• Configuring Namespaces in <strong>Caché</strong> System Administration Guide568 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(9)$ZUTIL(9)Broadcasts a message to a specified device.$ZUTIL(9,terminal,message,timeout)$ZU(9,terminal,message,timeout)$ZUTIL(9,"",message,loglevel)$ZU(9,"",message,loglevel)ParametersterminalmessagetimeoutloglevelA terminal name, specified as a quoted string, or the null string.The message to send, specified as a quoted string.Optional — An integer specifying the number of seconds to wait beforetimeout.Optional — A numeric code indicating which logging level option touse.Description$ZUTIL(9) has two syntactic forms. The first sends a message to the specified terminal, andcan optionally time out. The second sends a message to the operator console (specified bythe null string), and also logs the message.• $ZUTIL(9,"",message) passes the message to the operator console, logging it in theconsole log file. By default, the console log file is cconsole.log, which can be accessedvia the System Management Portal System Logs option. This default console log filelocation is configurable. Go to the System Management Portal, select Configuration, thenselect Advanced Settings. On the pull-down Category list select Miscellaneous. Viewand edit the current setting of ConsoleFile. By default this setting is blank, routing consolemessages to cconsole.log. If you change this setting, you must restart <strong>Caché</strong> for thischange to take effect.• $ZUTIL(9,terminal,message) passes the message to the specified terminal. If youspecify your own principal device, your message appears on your terminal screen.$ZUTIL(9) does not add any carriage control to the message it sends. To include any carriagecontrol (carriage returns or line feeds), you must include them in the message, using$CHAR(10) and $CHAR(13).<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 569


System and Other FunctionsParametersterminalThe device name of the terminal to which you want to send a message, specified as a quotedstring. Specify the null string ("") to send the message to the system console.messageThe message to send, specified as a quoted string.timeoutOptional (used with named terminal only) — A timeout in seconds. If $ZUTIL(9) is not ableto send the message during the period of the timeout, it ceases attempts to send the messageafter the timeout expires.loglevelOptional (used with operator console only) — The log level you want to assign to the message.You can use the following values:• 0 = Send the message to the following locations: Operator console log file, <strong>Caché</strong> console.• 1 = Send the message to the following locations: Operator console log file, <strong>Caché</strong> console,System-wide operator console facility. 1 is the default.ExamplesIn the following example, $ZUTIL(9) sends the message GOOD MORNING on a separateline to the terminal /dev/tty07. ($CHAR(13) is a carriage return, $CHAR(10) is a line feed.)SET X=$ZUTIL(9,"/dev/tty07",$CHAR(13)_$CHAR(10)_"GOOD MORNING"_$CHAR(13)_$CHAR(10))In the following example, $ZUTIL(9) sends the message you specify on a separate line tothe operator console. ($CHAR(13) is a carriage return, $CHAR(10) is a line feed.)READ "Operator message? ",mymess,!SET X=$ZUTIL(9,"",$CHAR(13)_$CHAR(10)_mymess)Notes$ZUTIL(94) complements $ZUTIL(9). $ZUTIL(9) sends a message to a specified devicewhile $ZUTIL(94) sends a message to the principal device of a specified process. Be surethat you use the right function for the right purpose. If you send a process id to $ZUTIL(9)or a terminal device name to $ZUTIL(94), you receive a error.570 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


To view messages in the Console Log File, go to the System Management Portal. UnderOperations, select System Logs. Then click on View Console Log to display the log contents.The example above (with carriage return / line feed) writes a message such as the followingin the Console Log:02/24-10:40:13:547 ( 2444) 0GOOD MORNINGSee Also• $ZUTIL(94) Broadcast a Message to a Specified Process function• Terminal I/O in Using <strong>Caché</strong> <strong>ObjectScript</strong>$ZUTIL(12)$ZUTIL(12)Translates logical device name or file name to canonical form.$ZUTIL(12,name,canon,case)$ZU(12,name,canon,case)ParametersnamecanoncaseOptional — A string expression specifying a directory name, namespace name,or logical device name to be canonized. If not specified, the default is thesystem manager's directory.Optional — An integer flag that specifies how canonization is performed.Available value are 0, 1, 2, and 3. The default is 0.Optional — Windows only: A boolean flag that specifies whether to returnname in all lowercase letters (the default) or to preserve uppercase letters. 1= preserve any uppercase letters in name, and (if necessary) convert the diskdrive name to uppercase. 0 = convert name (including disk drive name) to alllowercase letters (the default).Description$ZUTIL(12) converts the file name or logical device name specified by the expression nameto canonical form. It expands a partial path name to a full path name for a specified file ordirectory, the current directory, or the current namespace.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 571


System and Other FunctionsYou can use the wildcard options of the $ZSEARCH function to locate an existing directoryand return its full path name. You can use $ZUTIL(140) to create a new directory, or toreturn information about an existing file or directory.Directory PathnamesThe following rules govern the expansion of directory pathnames:• $ZUTIL(12) (with no arguments) returns the current system manager's directory pathname.For example: c:\cachesys\mgr\.• $ZUTIL(12,"") or $ZUTIL(12,"c:") returns the current namespace pathname. Forexample: c:\cachesys\mgr\user\.• $ZUTIL(12,"fred") returns the current namespace pathname for the specified directory.For example: c:\cachesys\mgr\user\fred\.• $ZUTIL(12,"\fred") returns the specified directory as a top-level directory. For example:c:\fred\.• Pathnames can use a single dot (.) to indicate the current directory, or a double dot (..)to indicate its parent directory. Thus $ZUTIL(12,".") returns the current namespacedirectory: c:\cachesys\mgr\user\, and $ZUTIL(12,"..") returns the parent directory ofthe current namespace directory: c:\cachesys\mgr\.Device NamesDevice names are handled much like directory names:• $ZUTIL(12,$PRINCIPAL) returns the current namespace pathname for the specifieddevice. For example: c:\cachesys\mgr\user\|trm|:|1876\.• $ZUTIL(12,"\"_$PRINCIPAL) returns the specified device as a top-level directory.For example: c:\|trm|:|1876\.The canon Flag$ZUTIL(12,name,canon) determines the action to be performed based on the value of canon.Valid values are:572 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(12)0123Canonize name as a file name without checking for a valid name. Thus:c:\cachesys\mgr\user\fred.Windows: Canonize name as a directory name without checking for a valid name.Thus: c:\cachesys\mgr\user\fred\. This is the default.OpenVMS: Returns null if it is an invalid name (existing or not).UNIX: Returns null if it is not a file or special device such as a raw partition.If name refers to an existing directory, canonize name and return the full pathname.Otherwise, return null.If name refers to an existing directory or a special device that can contain a <strong>Caché</strong>database, canonize name and return the full pathname. Otherwise, return null.The case FlagOn Windows systems, the default canonical form returned is entirely in lowercase letters,regardless of the case of name. Because Windows and <strong>Caché</strong> <strong>ObjectScript</strong> are case-insensitive,this is usually irrelevant. However, this may affect some Windows applications (such as Java)which are case-sensitive.To preserve uppercase letters on Windows systems, specify a case flag with a value of 1.This has the following effects:• The drive letter is always converted to uppercase.• If the directory does not exist on your system, $ZUTIL(12) follows the capitalizationyou specified. Letters specified as uppercase remain in uppercase.• If the directory exists on your system, $ZUTIL(12) follows the capitalization conventionsof the directory itself, rather than the capitalization in the string you specified.For example, if you specify:SET x=$ZUTIL(12,"\cAcHeSys\mGr\vIsiToR\fReD",0,1)WRITE xIt will return: C:\CacheSys\Mgr\vIsiToR\fReD\, deriving the case of the existing directories inthis pathname (C:\CacheSys\Mgr) from the file system, and deriving the case of the nonexistentdirectories (vIsiToR\fReD\) from the input string.The case flag is accepted on non-Windows systems, but performs no operation.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 573


System and Other FunctionsExamplesThe following example returns the canonical form pathname of the system manager's currentdirectory, the current namespace, and the current device. Note that on Windows systems,canonical forms are all lowercase:WRITE !,$ZUTIL(12) ; current mgr directoryWRITE !,$ZUTIL(12,"") ; current namespaceWRITE !,$ZUTIL(12,$IO) ; current deviceThe following example returns the canonical form of the pathname of the non-existent file“Fred”, and the invalid filename “Fr@d”:WRITE !,"flag O: ",$ZUTIL(12,"Fred",0),!,$ZUTIL(12,"Fr@d",0)WRITE !,"flag 1: ",$ZUTIL(12,"Fred",1),!,$ZUTIL(12,"Fr@d",1)WRITE !,"flag 2: ",$ZUTIL(12,"Fred",2),!,$ZUTIL(12,"Fr@d",2)WRITE !,"flag 3: ",$ZUTIL(12,"Fred",3),!,$ZUTIL(12,"Fr@d",3)Flag 0 returns a canonical form for “Fred” and “Fr@d” as file names. Flag 1 returns thecanonical form for “Fred” and “Fr@d” as directory names. Note that file name validation isnot performed. Flag 2 and Flag 3 return the null string because “Fred” does not exist.You can use indirection, as in this example:SET NEWNAM=$ZUTIL(12,@IDNAME)For more information, refer to Indirection in Using <strong>Caché</strong> <strong>ObjectScript</strong>.In the following UNIX example, if /us/bill/ is a valid name, then:WRITE $ZUTIL(12,"^^/us/bill//",2)returns and canonizes the reference, treating it the same as /us/bill/.If ttyp0 is a valid terminal device, but ttyp00 is not, the following statement returns a canonizedname:WRITE $ZUTIL(12,"/dev/ttyp0",3)returns: /dev/ttyp0However, the following statement does not:WRITE $ZUTIL(12,"/dev/ttyp00",3)This statement returns the null string.See Also• $ZSEARCH function574 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(15)• $ZUTIL(140) Return File Attributes, Create or Delete a Directory function• Configuring <strong>Caché</strong> in <strong>Caché</strong> System Administration Guide$ZUTIL(15)Translates RMS file name to canonical form.$ZUTIL(15,devname)$ZU(15,devname)ParametersdevnameA RMS file name.DescriptionOpenVMS: Use this form of $ZUTIL to translate the RMS file name specified by devnameto canonical form.ExampleWRITE $ZUTIL(15,LOGIN.COM)returns LARRY$DUA0:[SYSM.NEW]LOGIN.COM;1See Also• $ZUTIL(12) Translate file name to canonical form function• RMS and Sequential File I/O in the <strong>Caché</strong> I/O Device Guide<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 575


System and Other Functions$ZUTIL(18)Sets undefined variable handling for the current process.$ZUTIL(18,n)$ZU(18,n)ParametersnOptional — A numeric code that determines how <strong>Caché</strong> treats an undefinedvariable. If you omit n, $ZUTIL(18) returns the current value without changing it.DescriptionUse $ZUTIL(18) to define how undefined variables are to be handled in the current process.The value you specify for n determines the behavior of <strong>Caché</strong> when it encounters an undefinedvariable. Setting n changes this behavior for local, process-private global, and global variables;it has no effect on special variables.By default, if a process makes reference to an undefined variable it produces an error. This system-wide default behavior is configurable. Go to the System ManagementPortal, select System Configuration, select Advanced Settings, on the pull-down Categorylist select <strong>ObjectScript</strong>. View and edit the current setting of UndefVarBehavior. The defaultis 0. You can override this default system-wide by using the $ZUTIL(69,0) function.$ZUTIL(18) only affects variables invoked by the current process. $ZUTIL(69,0) onlyaffects variables invoked by subsequent processes; it does not affect the current process.You can call $ZUTIL(18) to return the current setting. When calling $ZUTIL(18,n) thevalue returned is the previous setting, not the value set by the function call.You can use the $GET function to return a default value when a specified variable is undefined.Setting $ZUTIL(18) has no effect on $GET. You can use the ZWRITE command todisplay defined variables that have a null string value; ZWRITE does not display undefinedvariables that return a null string.ParametersnA numeric code that specifies how <strong>Caché</strong> treats an undefined variable in the current process:576 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(18)012Issues the error for any undefined variable.Returns a null string for a reference to an undefined variable with subscripts, andissues the error for undefined variables without subscripts.Returns a null string (instead of issuing an error) for any undefinedvariable.Integers larger than 2 or smaller than –1 are ignored as no-ops. A value of –1 sets $ZUTIL(18)to 2.NotesThe $DATA function tests if a specified variable is defined. It returns 0 if the variable isundefined.The $GET function returns a default value if a specified variable is undefined. The basicform of $GET returns a null string if the specified variable is undefined.The $ZUTIL(18) function defines handling behavior for all undefined variables: local variables,process-private globals, and globals. Setting $ZUTIL(18) has no effect on $DATA or$GET.You can use the ZWRITE command to display defined variables that have a null string value;ZWRITE does not display undefined variables that return a null string.ExamplesIn the following example, <strong>Caché</strong> by default issues an error when encounteringan undefined variable. $ZUTIL(18) overrides that default for the local process.WRITE !,"system:",$ZUTIL(69,0)," local:",$ZUTIL(18)SET x=$ZUTIL(18,2)WRITE !,"system:",$ZUTIL(69,0)," local:",$ZUTIL(18)NEW fredIF fred="" {WRITE !,"null string for undefined variable" }ELSE {WRITE !,$GET(fred,"undefined variable not null") }In the following example, $ZUTIL(18,1) sets undefined variable handling to return a nullstring for defined subscripts (such as ^||X(A,B,C)) of an undefined process-private global^||X. The ZWRITE command is used to show variables set to a null string.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 577


System and Other FunctionsSET A="Fred",B="Barney",C="Wilma"WRITE !,$ZUTIL(18,1)WRITE !,"system:",$ZUTIL(69,0)," local:",$ZUTIL(18),!SET D=^||X(A,B,C)SET E=^||X(1,2,"HELLO")ZWRITE D,EWRITE !,$GET(^||X,"^||X is not defined")In the following example, $ZUTIL(18,2) returns a null string for the undefined variable J.WRITE !,$ZUTIL(18,2)WRITE !,"system:",$ZUTIL(69,0)," local:",$ZUTIL(18)WRITE !,$GET(J,"Variable is undefined")WRITE !,J,"No UNDEFINED error issued"See Also• $ZUTIL(69,0) Set Undefined Variable Handling System-wide function• ZWRITE command• $DATA function• $GET function$ZUTIL(20)Specifies the namespace(s) that contains the routine dataset.$ZUTIL(20,new,second,third)$ZU(20,new,second,third)ParametersnewsecondthirdSpecify the primary namespace that contains the routine dataset.Optional — Specify the second namespace to search for routines.Optional — Specify the third namespace to search for routines.DescriptionTo change the source from which you want to draw routines, use this form of $ZUTIL tospecify the namespace that contains the routine dataset in which the routines you want to useare located.Enclose the namespace in double quotes. The namespace you specify can be either an explicitnamespace or an implied namespace. An implied namespace is a directory path or OpenVMS578 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(20)file specification preceded by two caret characters: either "^^dir" (on the current system),or "^system^dir".To understand $ZUTIL(20), you need to keep the following in mind. When a job starts, ituses routines in the current namespace. After you issue $ZUTIL(20,new), all subsequentroutines come from new.To determine the current namespace, use the $ZNSPACE special variable or $ZUTIL(5). Tochange the current namespace, use the ZNSPACE command or $ZUTIL(5).If you issue $ZUTIL(20,new,second,third), all subsequent routines located in new also comefrom new. If <strong>Caché</strong> does not find a routine in new, <strong>Caché</strong> looks for the routine in second. If<strong>Caché</strong> does not find the routine in second, <strong>Caché</strong> looks for the routine in third, and so on.Note:Using routines in second is VERY slow! You should use second as an aid to programdevelopment, not as a normal running procedure.To use second as a development aid, make new your development area and second as a storagearea of routines that work. When you issue ZSAVE, the routine you save always goes intonew, even if you loaded it from second. As you edit and file routines, they appear in newwithout affecting the library in second, and subsequent calls for the routines get the newversion from new.For % routines, refer to $ZUTIL(39).ParametersnewSpecify the primary namespace that contains the routine dataset. If used alone, this is thenamespace that will be searched for all routines. If used in conjunction with second and third,new will be the first namespace searched for routines.Enclose the namespace in double quotes. The namespace you specify can be either an explicitnamespace or an implied namespace (a directory path or OpenVMS file specification precededby two circumflex characters).secondSpecify the second namespace to search for routines. If <strong>Caché</strong> doesn't find a routine in new,it will search for it in second. Specify the same as new.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 579


System and Other FunctionsthirdSpecify the third namespace to search for routines. If <strong>Caché</strong> doesn't find a routine in new orsecond, it will search for it in third. Specify the same as new.NotesKeep the following points in mind when you use $ZUTIL(20).• Issuing $ZUTIL(20) without specifying other parameters does not change the currentnamespace.• The $ZUTIL(20) return value is the primary (default) namespace for routine access thatwas set before you called the function.• Calling $ZUTIL(20) with parameters always clears previous settings.• Calling $ZUTIL(20) with a null string as a parameter ($ZUTIL(20,""), resets the currentnamespace for routine access to the default namespace.• Calling $ZUTIL(20,n), where n is an integer, issues a error.• The command does not affect globals; the original namespace still defines access privilegesfor globals. Your job uses globals in the current namespace unless you make explicit orimplicit references to globals in other namespaces. In other words, the routines comefrom new (or from second or third), while the globals come from the job's currentnamespace.See Also• ZNSPACE command• $ZUTIL(5) Display or Switch Namespace function• $ZUTIL(90,4) Start Up in a Specified Namespace function• $ZUTIL(90,10) Test Whether a Namespace is Defined function• $ZNSPACE special variable• Configuring Namespaces in <strong>Caché</strong> System Administration Guide580 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(21)$ZUTIL(21)Returns the location of process-private globals or deletes all process-private globals.$ZUTIL(21,flag)$ZU(21,flag)ParametersflagOptional — A boolean flag. 0 returns the location of process-privateglobals. 1 deletes all process-private globals. The default is 0.DescriptionUse $ZUTIL(21) to handle the process-private globals for the current process. $ZUTIL(21,0)returns the location of the process-private globals database in the form sfn^dir. If no processprivateglobals are defined, this defaults to 15999^0. For further information on System FileNumbers (sfn), refer to $ZUTIL(49). $ZUTIL(21,1) deletes all process-private globals definedfor the current process. It returns 1 upon successful completion, 0 upon error. $ZUTIL(21,1)returns 1 even if no process-private globals were defined.ExampleWRITE !,$ZUTIL(21,0)," before ppgs"SET ^||a=123SET ^||a(1,1)="John Doe"WRITE !,$ZUTIL(21,0)," after defining ppgs"WRITE !,$ZUTIL(21,1)WRITE !,$ZUTIL(21,0)," after deleting ppgs"See Also• $ZUTIL(49) — Obtain database label information function• Variables in Using <strong>Caché</strong> <strong>ObjectScript</strong><strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 581


System and Other Functions$ZUTIL(39)Specifies a search path for percent (%) routines.$ZUTIL(39,sys1,sys2,sys3)$ZU(39,sys1,sys2,sys3)Parameterssys1sys2sys3Specify a namespace name to use as the search path for percent (%) routines.Optional — Specify a namespace name to use as the second search path forpercent (%) routines.Optional — Specify a namespace name to use as the third search path forpercent (%) routines.Description$ZUTIL(39) specifies one or more namespaces to use as a search path for percent (%) routines,and thereby establishes an alternate system manager's namespace. After issuing $ZUTIL(39),when you call percent routines, <strong>Caché</strong> search for these routines in the namespace(s) specifiedby $ZUTIL(39), rather than the default system manager's namespace.A percent routine is a routine whose name begins with a percent sign character. This namingconvention is commonly used for system routines found in the system manager's namespaceand available to all users. The default system manager's namespace is %SYS.After issuing $ZUTIL(39), <strong>Caché</strong> uses up to the maximum of three path specifications tofind percent routines when they are called. If <strong>Caché</strong> cannot locate a percent routine in the<strong>Caché</strong> database in sys1, it then searches sys2 (if you specified this parameter.) If the percentroutine is not in the <strong>Caché</strong> database insys2, <strong>Caché</strong> then searches sys3 (if you specified thisparameter.)You can use a null string as a search specification to indicate the default system manager'snamespace. After resetting the search path to the default system manager's namespace, subsequentcalls to $ZUTIL(39) returns ^^c:\cachesys\mgr\.A call to $ZUTIL(39) with no parameters returns the current namespace to search for percentroutines. A call to $ZUTIL(39) with any number of parameters returns the namespace namefor percent routine searches that existed prior to that $ZUTIL(39) call. $ZUTIL(39) onlyreturns one namespace name (sys1), even if you have established sys2 and sys3.582 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(39)Note:Your system's performance suffers significantly when <strong>Caché</strong> must load a routinefrom sys2 or sys3. For this reason, use these for program testing only. For example,if you change a few percent routines, you may want to test them in a namespacewhere users are not currently running.A typical use of the $ZUTIL(39) function would be to run a set of % routines that are differentfrom the ones in the system manager's namespace. For example, you might want to run adifferent version of the <strong>InterSystems</strong> relational database application generator (RDBMSproduct). Or, you might want to develop % routines in a development environment withoutaffecting the routines in the system manager's namespace.Note:OpenVMS: A process can use $ZUTIL(39) only if its UIC matches that of theoriginal system manager's CACHE.DAT file. Otherwise, <strong>Caché</strong> issues a error.When a process switches namespaces using $ZUTIL(5) or the ZNSPACE command,$ZUTIL(39) information is normally reset. The only exception to this is when the processswitches from an implied namespace to an implied namespace, in which case $ZUTIL(39)settings are preserved. An implied namespace is a directory path or OpenVMS file specificationpreceded by two caret characters: "^^dir".Parameterssys1Specify the search path for percent (%) routines. If used alone, this is the search path thatwill be searched for all routines. If used in conjunction with sys2 and sys3, sys1 will be thefirst search path searched for routines. You can specify a null string as to indicate the defaultsystem manager's namespace.sys2Specify the second search path for percent (%) routines. If <strong>Caché</strong> doesn't find a routine insys1, it will search for it in sys2. You can specify a null string as to indicate the default systemmanager's namespace.sys3Specify the third search path for percent (%) routines. If <strong>Caché</strong> doesn't find a routine in sys1or sys2, it will search for it in sys3. You can specify a null string as to indicate the defaultsystem manager's namespace.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 583


System and Other FunctionsExampleWRITE !,"Initial setting: ",$ZUTIL(39)WRITE !,$ZUTIL(39,"^^c:\cachesys\mgr\samples\",""); note use of implied namespace with ^^WRITE !,"New setting: ",$ZUTIL(39)See Also• ZNSPACE command• $ZUTIL(5) Display or Switch Namespace function• $ZUTIL(20) Specify the namespace that contains the routine dataset function• $ZUTIL(68,43) Sets clearing of global vectors for the current process function• $ZUTIL(69,43) Sets clearing of global vectors system-wide function• $ZNSPACE special variable• Configuring Namespaces in <strong>Caché</strong> System Administration Guide$ZUTIL(49)Obtains database label information.$ZUTIL(49,dir,flag)$ZU(49,dir,flag)ParametersdirflagName of a directory which contains a <strong>Caché</strong> .DAT database file. A quotedstring containing a fully-qualified pathname.Optional — A flag that specifies what type of database information to return.Permitted values are: 0 = database header information; 1 = cluster lockinformation; 2 = file expansion time; or 3 = directory location.DescriptionUse the various forms of $ZUTIL(49) to return label information about a database. Youspecify the pathname of the directory containing the database, not the name of the databasefile itself.584 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(49) with no parameters returns the header information for the manager's directory.$ZUTIL(49,dir,flag) returns the type of information specified by flag from the dir directory.This information is returned as a string of comma-separated items. The first item of thisreturned string is either the system file number (sfn) or a negative number indicating that thespecified directory does not exist, is not mounted, or can't be read.You can use the wildcard options of the $ZSEARCH function to determine the pathnamesof .DAT files on your system.ParametersdirThe fully-qualified pathname of the directory which contains the <strong>Caché</strong> .DAT database file.Specify dir as a quoted string. The dir parameter must be present to specify a flag parameter.If you omit the dir parameter, $ZUTIL(49) (with no arguments) returns the header informationfor the system manager's directory (for example: c:\cachesys\mgr\). You can specify dir as anull string ("") to return information on the current directory (for example:c:\cachesys\mgr\user\).On Windows and UNIX systems you can also use the following standard pathname symbols:a single dot (.) to specify the current directory, or a double dot (..) to specify its parent directory.Alternately, you can specify the system file number (sfn), which is an index to gfiletab, asthe dir parameter value for most flag values. This system file number can be obtained froma prior call to $ZUTIL(49) which specified the directory name as the dir parameter.flagA flag that specifies what type of database information to return.$ZUTIL(49)Value0123DescriptionReturn the database header information as a comma-separated string. Thisis the default if no flag parameter is specified.Return cluster lock information as a comma-separated string. Do not use thisflag value when specifying a system file number for dir.Return the most recent database file expansion time (in $HOROLOG format).This value is returned as the second item in a comma-separated string.Returns the directory location as the string sys^dir, where sys is the remotesystem number (0 if local), and dir is the directory name. This flag value canonly be used when specifying a system file number (sfn) for dir.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 585


System and Other FunctionsDatabase Header Information$ZUTIL(49), $ZUTIL(49,dir) and $ZUTIL(49,dir,0) all return the database header information,returned as a comma-separated list of values. The following table lists the values thatthese forms of $ZUTIL(49) can return for each part of this comma-separated list:ListedItem123456DescriptionThis part contains either the file name status flag (if file header info cannotbe obtained) or the system file number:-3: This flag indicates that dir specified a file name that is too long or hasinvalid file name syntax. No other information is returned.-2: This flag indicates that dir specified a file that does not exist or cannotbe read. No other information is returned.-1: This flag indicates that dir specified a file that exists, but is currentlydismounted. No other information is returned.255 or 15999:These numbers are too large to be actual system file numbers.They indicate that the specified directory is not mounted. No other informationis returned. 15999 is returned by <strong>Caché</strong> version 5.0 and subsequent versions;255 is returned by <strong>Caché</strong> versions prior to 5.0.Other numbers: The system file number (index into gfiletab) of the file. Ifzero (0), this indicates the System Manager's directory. These values arefollowed by a comma-separated list of header information items, as shownbelow.<strong>Caché</strong> block size, in bytes. Either 2048 or 8192.User Identification Code (UIC), the decimal value of the two bytes of theprotection code assigned to the <strong>Caché</strong> database file. For example, A UICof [1,4] is represented by the decimal number 260 (256 + 4). 0 if noprotection. (The OpenVMS operating system assigns a UIC; At <strong>Caché</strong>version 5.1 (and subsequent), <strong>Caché</strong> security no longer sets or uses a UICvalue.)Current size of the <strong>Caché</strong> database file in megabytes. (1MB = 1024 * 1024bytes)Number of blocks by which <strong>Caché</strong> expands the database when it runs outof room.Maximum total number of blocks that can be allocated for this database. 0= limited only by GMaxBlks.586 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(49)ListedItem78910111213141516through25DescriptionRelative block number where global directory begins, counting from 1.Cannot be changed once set.Relative block number where new global pointers will begin to be allocated,counting from 1.Currently unused; default is 0.Currently unused; default is 0.Relative block number where new global data will be added, counting from1.Freeze on database error indicator. 0 = Freeze writes on error enabled. 1= Freeze writes on error disabled.Default global collation sequence for the database. 0 through 4 are priorIntersystems products (ISM); 5 is <strong>Caché</strong> standard; 10 through 127 are forcollation sequences for languages other than English. 128 through 255 arestring-only collation sequences that correspond to the 0 through 127assignments.Thus 133 is the <strong>Caché</strong> standard string-only collation sequence.System file number, regardless of whether the file is currently mounted ordismounted.Total number of virtual volumes in the volume set.These values are for internal reference only.An examples of database header information is as follows:ZNSPACE "%SYS"SET dir=$ZUTIL(168) ; determine <strong>Caché</strong> directorySET dbdir=dir_"cachelib"WRITE $ZUTIL(49,dbdir,0)which returns a string of 24 comma-separated values (such as the following), each item correspondingto the items in the table above:1,8192,0,90,0,0,3,16,0,0,50,1,5,1,1,320,4228,1,1123751162,1,2,11520,62464,1,<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 587


System and Other FunctionsCluster Lock InformationIf you specify a flag value of 1, $ZUTIL(49,dir,1) returns the cluster lock information fordir for the database. The returned string consists of four comma-separated parts:sfn,cfn,locktype,lockidListed ItemsfncfnlocktypelockidDescriptionThe system file number (index into gfiletab) of the file. If zero (0), thisindicates the System Manager's directory. Negative numbers indicatethat the specified directory does not exist, is not mounted, or can't beread (see the first item in the Database Header Information table).Cluster File Number (CFN) if the directory is a cluster-mounteddatabase. Otherwise (non-USECLUSTER systems) returns zero (0).The locktype status if the directory is cluster-mounted: S=shared,X=exclusive, N=null, U=unknown. Otherwise returns zero (0).Lock ID of the distributed lock manager if the directory iscluster-mounted. Otherwise returns zero (0).An examples of database cluster lock information is as follows:ZNSPACE "%SYS"SET dir=$ZUTIL(168) ; determine <strong>Caché</strong> directorySET dbdir=dir_"cachelib"WRITE $ZUTIL(49,dbdir,1)which returns the following string of 4 comma-separated values, corresponding to the rowsof the table above:1,0,0,0,Note:Do not specify a system file number (sfn) for dir for $ZUTIL(49,dir,1).For Tru64 UNIX, the lockid is of the form: “seqn:hndl”.588 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


File Expansion TimeIf you specify a flag value of 2, $ZUTIL(49,dir,2) returns the date and time that the lastdatabase file expansion occurred, in $HOROLOG format. The returned string consists ofthree comma-separated parts:sfn,expanddate,expandtime$ZUTIL(49)Listed ItemsfnexpanddateexpandtimeDescriptionThe system file number (index into gfiletab) of the file. If zero (0),this indicates the System Manager's directory. Negative numbersindicate that the specified directory does not exist, is not mounted,or can't be read (see the first item in the Database HeaderInformation table).The date of the last file expansion, expressed as the date half ofa $HOROLOG value.The time of the last file expansion, expressed as the time half ofa $HOROLOG value.An examples of database expansion time information is as follows:ZNSPACE "%SYS"SET dir=$ZUTIL(168) ; determine <strong>Caché</strong> directorySET dbdir=dir_"cachetemp"WRITE $ZUTIL(49,dbdir,2)which returns the following string of 3 comma-separated values, corresponding to the rowsof the table above:2,59161,40560<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 589


System and Other FunctionsDirectory LocationIf you specify a flag value of 3, and specify a system file number for the dir argument,$ZUTIL(49,dir,3) returns the remote system number and the directory pathname. The returnedstring separates these two parts with a caret (^):sys^dirListedItemsysdirDescriptionThe remote system number where the specified sfn is located. If zero (0),this indicates the directory is located on the local system.The pathname of the file that corresponds to the specified sfn.If the specified system file number refers to a non-existent file, this form of $ZUTIL(49)returns -2. (See the first item in the Database Header Information table for details on negativereturn values.)An examples of database location information is as follows:WRITE $ZUTIL(49,2,3)which returns a string such as the following. Because it is a locally mounted database, thefirst component in this case is zero:0^c:\cachesys\mgr\cachetemp\See Also• $VIEW function• $ZSEARCH function• $HOROLOG special variable590 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(55)$ZUTIL(55)Returns or changes the current language mode.$ZUTIL(55,n)ParametersnOptional — A numeric code specifying what language mode to set.DescriptionUse this form of $ZUTIL to examine or change the current language mode.To return the current state of the language mode switch without changing it, issue $ZUTIL(55)without the n parameter, as follows:WRITE $ZUTIL(55)To change the language mode, issue $ZUTIL(55,n). This changes the language mode andreturns the previous language mode value.You can use $ZUTIL(55) to change the language mode at the programmer prompt. (Use thecomplete $ZUTIL spelling, as the $ZU abbreviation is not valid in all language modes.)When <strong>Caché</strong> executes a routine, it automatically changes the language mode to the routine'slanguage mode. A DO command or a $$ extrinsic function temporarily changes the languagemode to that of the called routine. <strong>Caché</strong> then restores the previous language mode when theroutine terminates. Therefore, you need not (and cannot) change the language mode duringruntime execution of a routine.The ZLOAD command changes the language mode to the loaded routine's language mode.However, ZLOAD does not restore the previous language mode upon termination of theroutine. One use of $ZUTIL(55) is to set the language mode following a ZLOAD operation.$ZUTIL(55) can change the process' language mode at any time. However, when executinga routine you should only do this under XECUTE, and restore before leaving the XECUTEoperation. This technique is commonly used to set language mode when compiling a routine.The object code (tokens, mcode, etc.) for a routine is generated at compile time according tothe language mode in effect at that time. This language mode determines the routine's runtimebehavior, except for a few cases where language mode is tested at runtime.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 591


System and Other FunctionsAny form of indirection (for example, an XECUTE command, or the @ indirection operator)is evaluated at run time according to the current language mode. This language mode maynot be the same as the language mode of the running routine.ParametersnThis switch determines which language will be set:n= 0n= 1n= 2n= 5n= 6n= 7n= 8Set language mode to <strong>Caché</strong> and return the value for the previous state of theswitch. <strong>Caché</strong> is the default mode for the switch.Set language mode to DSM-11 and return the value for the previous state ofthe switch.Set language mode to Open M [DTM] and return the previous state of the switch.Set language mode to DSM for OpenVMS an return the value for the previousstate of the switch.Set language mode to DSM-J (Japanese) for OpenVMS and return the valuefor the previous state of the switch.Set language mode to DTM-J (Japanese) for OpenVMS and return the valuefor the previous state of the switch.Set language mode to MSM and return the value for the previous state of theswitch. MSM mode changes the use of the $ZC ($ZCHILD) special variable.NotesKeep the following points in mind when you use $ZUTIL(55):• When you are in <strong>Caché</strong> mode, you can abbreviate $ZUTIL to $ZU. You cannot use thisabbreviation in other language modes.• If you change the language mode with the $ZUTIL(55,n) switch so that it does not matchthat of the loaded routine, and then attempt to do a ZINSERT, you will get a error message.See Also• XECUTE command• ZLOAD command592 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(56,2)• $ZCHILD special variable• Open M Language Compatibility in Using <strong>Caché</strong> <strong>ObjectScript</strong>$ZUTIL(56,2)Locates source file and line of code for last <strong>Caché</strong> <strong>ObjectScript</strong> error.$ZUTIL(56,2)$ZU(56,2)DescriptionUse this form of $ZUTIL to locate the source file and the line of the last <strong>Caché</strong> <strong>ObjectScript</strong>error that occurred.The name of the last <strong>Caché</strong> <strong>ObjectScript</strong> error that occurred is contained in the $ZERRORspecial variable.See Also• $ZERROR special variable$ZUTIL(62,1)Returns syntax check of code.$ZUTIL(62,1,code)$ZU(62,1,code)ParameterscodeA string expression specifying a line of <strong>Caché</strong> <strong>ObjectScript</strong> code. If the codeincludes quote characters, these quote characters must be doubled (forexample, "WRITE ""result:"",a").<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 593


System and Other FunctionsDescriptionYou can use $ZUTIL(62,1) to check the syntax of a line of <strong>Caché</strong> <strong>ObjectScript</strong> code, specifiedas a quoted string. If code contains a syntax error, $ZUTIL(62,1) returns a string with thefollowing format:nn,,textornn,,textWhere nn is the character position number (counting from 0) that evoked the error, is a literal (returned in a terminal session, otherwise omitted), and text is an errormessage, such as “Invalid command”, “Invalid function name”, “Invalid expression”, “Invalidspecial variable”, or “Expected space”. $ZUTIL(62,1) returns the first syntax error detected;the line of code may contain additional syntax errors.If no syntax error exists, $ZUTIL(62,1) returns the null string.ExamplesIn following example, $ZUTIL(62,1) checks the syntax of a line of code and, finding nosyntax error, returns the null string:SET err=$ZUTIL(62,1," SET x=1 HANG 5")IF err="" { WRITE "syntax correct" }ELSE { WRITE err }QUITNote that leading blanks are ignored when checking syntax; you may include or omit leadingblanks.In following example, $ZUTIL(62,1) checks the syntax of a line of code and finds a syntaxerror (SET cannot use the '= operator).SET err=$ZUTIL(62,1," SET x'=1")IF err="" { WRITE "syntax correct" }ELSE { WRITE err }QUITIt returns: 9,,Error in SET command. Note that the apostrophe character is at position 9,counting from 0 (and including the four leading blanks).The following example tests several lines of program code, and returns a syntax error foreach:594 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(67)TestLinesSET a="WRING "; not a commandSET b="WRITE $FRED " ; not a special variableSET c="QUIT: "; postconditional missingSET d="HANG"; argument missingSET e="WRITE $FRED() " ; not a functionSET f="$ZPI "; line must begin with commandTopSET num=97 ; ASCII code for "a"SET x=$CHAR(num)LoopWHILE num


System and Other Functions• $ZUTIL(67,0) Return Activity State of a Specified Process• $ZUTIL(67,1) Return Activity State of a Specified Process, and Reset• $ZUTIL(67,4) Return Process State of a Specified Process• $ZUTIL(67,5) Return Routine Name of a Specified Process• $ZUTIL(67,6) Return Namespace Name of a Specified Process• $ZUTIL(67,7) Return Current Device Name of a Specified Process• $ZUTIL(67,8) Return Number of Lines Executed for a Specified Process• $ZUTIL(67,9) Return Number of Global <strong>Reference</strong>s for a Specified Process• $ZUTIL(67,10) Return Job Type of a Specified Process• $ZUTIL(67,11) Return User Name that Invoked a Specified Process• $ZUTIL(67,12) Return System Name Running a Client Process• $ZUTIL(67,13) Return Executable File Name of a Client Process• $ZUTIL(67,14) Return Operating System Running a Client Process• $ZUTIL(67,15) Return IP Address of a Client Process$ZUTIL(68)Sets or clears configuration options for the current process.$ZUTIL(68,subfunc,n)$ZU(68,subfunc,n)ParameterssubfuncnAn integer specifying which $ZUTIL(68) subfunction to invoke.Optional — The value used to set the invoked subfunction, either aboolean value, or occasionally a numeric code. If this parameter isomitted, the $ZUTIL(68) subfunction returns its current value.DescriptionThe $ZUTIL(68) subfunctions set or clear process flags for the current process.596 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


Although all of the $ZUTIL(68) subfunctions control a different aspect of process operation,all of them have the following operating characteristics in common:• Whenever you issue a call to $ZUTIL(68,subfunc) without specifying the n parameter,$ZUTIL(68,subfunc) returns the current setting of the subfunc switch.• Whenever you make a call to $ZUTIL(68,subfunc,n), the function sets the switch to thenew value specified by n and displays the previous switch value.Almost all of the $ZUTIL(68) flags can also be set system-wide using the corresponding$ZUTIL(69) subfunctions. The one exception is $ZUTIL(68,25).Many of these flags take a configurable system-wide default. These defaults are configuredusing various System Management Portal System Configuration Advanced Settings.Subfunctions$ZUTIL(68)The following table shows the $ZUTIL(68) subfunctions recognized by <strong>Caché</strong>. For eachsubfunction the meaning and default are also given.Subfunction Number and Operation$ZUTIL(68,1) — Null Subscript Mode Process Switch$ZUTIL(68,2) — Default OPEN Mode for Sequential Files$ZUTIL(68,3) — Automatic Sequential File Creation Mode ProcessDefault$ZUTIL(68,5) — Argumentless BREAK Process Switch$ZUTIL(68,6) — Reliable SET Networking Mode Process Switch$ZUTIL(68,7) — External <strong>Reference</strong> Mode Process Switch$ZUTIL(68,11) — Read Line Recall Mode Process Switch$ZUTIL(68,15) — Modem Disconnect Detection$ZUTIL(68,21) Synchronous Transaction Commit Mode$ZUTIL(68,22) — $X Update Mode for Escape Sequences$ZUTIL(68,25) — Dynamically Set or Remove Batch Status$ZUTIL(68,26) — Set or Clear Default Display of Current NamespaceDefaultSetting000100100platformdependent01 (Windowsonly) 0 (Allothers)<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 597


System and Other FunctionsSubfunction Number and Operation$ZUTIL(68,27) — Enable/Disable Network Hardening for the CurrentProcess$ZUTIL(68,28) — Control Root (Unsubscripted) Node Kills$ZUTIL(68,30) — Set Error-Handling Behavior (to allow use of DSMlanguage-mode error-handling)$ZUTIL(68,32) — Set Date Range and Invalid Date Behavior$ZUTIL(68,34) — Process Interruptible by Asynchronous Errors$ZUTIL(68,39) — Disable or Enable Caching$ZUTIL(68,40) — End-of-File Handling for Sequential Files (to supportporting of MSM routines)$ZUTIL(68,42) — $JOB Format for Process$ZUTIL(68,43) — Disable or Enable Clearing of Global Vectors (whencalling $ZUTIL(5).)$ZUTIL(68,45) — Truncate Numbers During String-to-NumberConversion (to support porting of MSM routines)$ZUTIL(68,51) — Namespace Default Directory Assignment$ZUTIL(68,63) — Disable or Enable “e” as Exponent SymbolDefaultSetting100010000001Note:$ZUTIL(69) uses many of the same subfunction numbers as $ZUTIL(68). Systemwidesubfunction options that cannot be changed on a per-job basis cause a error if you attempt to use them with $ZUTIL(68).See Also• $ZUTIL(69) Set System-wide Flags and Defaults functions598 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(68,1)$ZUTIL(68,1)Enables or disables use of null subscripts for the current process.$ZUTIL(68,1,n)$ZU(68,1,n)ParametersnA boolean that specifies the null subscript mode setting for the current process.DescriptionThe $ZUTIL(68,1) function enables or disables a mode that allows setting and referencingglobals with null subscripts within the current process.If null subscripted globals are not enabled (n=0), attempting to set a null subscripted variable,such as SET ^x("")=99, or to reference a null subscript, such as WRITE ^x(""), results ina error. For details on error format, refer to the $ZERRORspecial variable.If null subscripted globals are enabled (n=1), you can set a null subscripted variable, such asSET ^x("")=99, just like any other variable. Referencing an undefined null subscriptedvariable results in a error.Invoking $ZUTIL(68,1) without specifying n returns the current switch setting.ParametersnA boolean switch that specifies the null subscript mode setting for the current process.01Disables setting/referencing null subscripted globals (the default).Enables setting/referencing null subscripted globals.Note:This feature helps you convert applications that use null subscripts. <strong>InterSystems</strong>recommends that you not use it for new development.This system-wide default behavior can be configured using the $ZUTIL(69,1) function. Forfurther details, see $ZUTIL(69,1) — Null Subscript Mode System Default.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 599


System and Other FunctionsExampleThe following example tests the null subscript mode. If null subscripts are enabled for thecurrent process, it creates some.NullSubsTestSET b=$ZUTIL(68,1)IF b=1 {WRITE !,"null subscripts enabled locally",!UseNullSubsSET ^x("")=99,^x(0)=0,^x(1)=1ZWRITE ^xQUIT }ELSE {WRITE !,"will enable null subscripts"SET y=$ZUTIL(68,1,1) ; enable for current processWRITE !,"null subscripts now enabled locally"GOTO UseNullSubs}QUITSee Also• $ZUTIL(69,1) — Null Subscript Mode System Default function$ZUTIL(68,2)Sets sequential file open mode for the current process.$ZUTIL(68,2,n)$ZU(68,2,n)ParametersnThe boolean value that specifies the process-specific default mode for sequentialfiles on OPEN.DescriptionThe $ZUTIL(68,2) function specifies the open mode for sequential files opened by the currentprocess. When the current process issues an OPEN command for a sequential file, that fileis opened either in read-only mode (R) or read/write mode (RW). Calling $ZUTIL(68,2)specifies this open mode for the current process, overriding the system-wide default setting.On VMS systems, the default value is 1. On all other platforms, the default value is 0.Invoking $ZUTIL(68,2) without specifying n returns the current switch setting.600 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


This system-wide default behavior can be configured using the $ZUTIL(69,2) function. Forfurther details, see $ZUTIL(69,2) — Default Open Mode for Sequential Files.ParametersnThe boolean value that specifies the default mode for sequential files on OPEN for the currentprocess. 0 means read-only (R) is the default. 1 means read and write (RW) is the default.ExampleThe following example sets the open mode default, then opens a sequential file:SET x=$ZUTIL(68,2)IF x=0 {SET y=$ZUTIL(68,2,1)WRITE !,"Set the open mode to:",$ZUTIL(68,2)}ELSE {WRITE !,"Open mode was already set to:",$ZUTIL(68,2)}OPEN "c:\myfiles\seqtest1":("NRW"):5; ...QUITSee Also• $ZUTIL(69,2) — Set Open Mode for Sequential Files System-wide function• OPEN command• Sequential File I/O in <strong>Caché</strong> I/O Device Guide$ZUTIL(68,3)$ZUTIL(68,3)Sets automatic sequential file creation option for the current process.$ZUTIL(68,3,n)$ZU(68,3,n)ParametersnThe boolean value that specifies whether a sequential file is automatically createdon OPEN.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 601


System and Other FunctionsDescriptionThis $ZUTIL(68,3) function specifies if a sequential file is created automatically in responseto an OPEN command that specifies a file that does not already exist. In <strong>Caché</strong>, if you attemptto open a file in "W" or "RW" mode, but that file does not yet exist, the default behavior isplatform-dependent. On Windows and UNIX systems, the default is for <strong>Caché</strong> to hang untilthe file is actually created, or until the process is resolved by a timeout expiration or by callingthe RESJOB utility. On OpenVMS systems, the default is to create a new sequential file.This system-wide default behavior can be configured using the $ZUTIL(69,3) function. See$ZUTIL(69,3) — Automatic File Creation Mode System Default.Setting $ZUTIL(68,3) causes <strong>Caché</strong> to create a sequential file automatically when you issuethe OPEN command in "W" or "RW" mode for a file that does not already exist. This$ZUTIL(68,3) setting governs all sequential file opens in the current process.The system-wide or current-process default behavior can be overridden for individual OPENcommands using the “E” (or /CREATE) mode parameter. The OPEN mode parameters arelisted in Sequential File I/O in the <strong>Caché</strong> I/O Device Guide.Invoking $ZUTIL(68,3) without specifying n returns the current switch setting.ParametersnThe switch that specifies whether or not a file is created when the process attempts to opena nonexistent file. 0 specifies that automatic new file creation is disabled. 1 specifies thatautomatic new file creation is enabled. The system default setting is 0.ExampleSET x=$ZUTIL(69,3),y=$ZUTIL(68,3)WRITE !,"system-wide auto-create on open:",xWRITE !,"current process auto-create on open:",yIF y=0 {SET z=$ZUTIL(68,3,1)WRITE !,"Set the process auto-create option to:",$ZUTIL(68,3)}ELSE {WRITE !,"Auto-create on open was already set to:",$ZUTIL(68,3)}OPEN "c:\myfiles\seqtest2":("RW"):5; ...QUITSee Also• $ZUTIL(69,3)— Automatic File Creation Mode System Default function602 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(68,5)• OPEN command• Sequential File I/O in <strong>Caché</strong> I/O Device Guide$ZUTIL(68,5)Enables or disables processing of argumentless BREAK commands for the current process.$ZUTIL(68,5,n)$ZU(68,5,n)ParametersnThe boolean value that specifies whether or not argumentless BREAK commandsare enabled for the current process.DescriptionThe $ZUTIL(68,5) function enables or disables the processing of argumentless BREAKcommands on a per-process basis. By default, <strong>Caché</strong> does process argumentless BREAKcommands.<strong>InterSystems</strong> provides this capability for compatibility with non-<strong>Caché</strong> products. This switchmakes it easier for you to port code from an Open M [DSM] system to other <strong>InterSystems</strong>implementations. $ZUTIL(68,5) simulates the behavior of the DSM commands ZBREAKON and ZBREAK OFF.This system-wide default behavior can be configured using the $ZUTIL(69,5) function. Referto $ZUTIL(69,5) — Argumentless BREAK System Default.Invoking $ZUTIL(68,5) without specifying n returns the current switch setting.ParametersnThe switch that specifies the default behavior of argumentless BREAK. 0 specifies that <strong>Caché</strong>treats an argumentless BREAK as a no-op. 1 specifies that <strong>Caché</strong> executes BREAK onargumentless BREAK. 1 is the default.See Also• BREAK command<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 603


System and Other Functions• $ZUTIL(69,5) Argumentless BREAK System Default function• Debugging chapter in Using <strong>Caché</strong> <strong>ObjectScript</strong>$ZUTIL(68,6)Enables or disables reliable SET networking mode for the current process.$ZUTIL(68,6,n)$ZU(68,6,n)ParametersnThe boolean value that specifies whether or not Reliable SET Networking mode isenabled for the current process.DescriptionUse $ZUTIL(68,6) to enable or disable Reliable SET Networking mode for the current process.When Reliable SET mode is enabled, each request of a SET, KILL, or LOCK commandthat results in a network error message such as , , or waits for a reply before proceeding. When Reliable SET mode is disabled, the localsystem ignores errors incurred by SET, KILL, and LOCK requests.You can switch Reliable SET mode on and off as often as you wish, even in the middle of astream of requests.The system default is Reliable SET mode disabled (0). This system-wide default behaviorcan be configured using the $ZUTIL(69,6) function. Refer to $ZUTIL(69,6) — ReliableSET Networking Mode System Default.Invoking $ZUTIL(68,6) without specifying n returns the current switch setting.ParametersnThe value that specifies if the Reliable SET mode is on or off. 0 disables Reliable SET modeas a default. The system default setting is 0. 1 enables Reliable SET mode as a default.604 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


See Also• KILL command• LOCK command• SET command• $ZUTIL(69,6) Reliable SET Networking Mode System Default function$ZUTIL(68,7)$ZUTIL(68,7)Retains or strips extended global reference from globals returned to the current process.$ZUTIL(68,7,n)$ZU(68,7,n)ParametersnThe boolean value that specifies whether or not extended global references areretained for the current process.DescriptionThe $ZUTIL(68,7) function specifies that if the first argument of a call to the $QUERYfunction or $NAME function contains an extended global reference, the return value alsocontains an extended global reference.For further information on extended global references, see Extended Global <strong>Reference</strong>s inUsing <strong>Caché</strong> Multi-Dimensional Storage.Invoking $ZUTIL(68,7) without specifying n returns the current switch setting.This function overrides the system default for the current process. The system-wide defaultbehavior is configurable. Go to the System Management Portal, select System Configuration,select Advanced Settings, on the pull-down Category list select <strong>ObjectScript</strong>. View and editthe current setting of QueryStripsExtendedRef. The default is “false” . To override this defaultsystem-wide, you can use $ZUTIL(69,7).<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 605


System and Other FunctionsParametersnA boolean switch to set the default setting. 0 specifies to retain the extended global reference;this enables reference-in-kind as a default. 1 specifies to strip the extended global referenceand return just the global; this disables reference-in-kind as a default. The system defaultsetting is 0.The 1 value for n is provided for backward compatibility.See Also• $NAME function• $QUERY function• $ZUTIL(69,7) Strip Extended Global <strong>Reference</strong>s System-wide function$ZUTIL(68,11)Enables or disables read line recall for the current process.$ZUTIL(68,11,n)$ZU(68,11,n)ParametersnThe boolean value that specifies whether read line recall mode is enabled for thecurrent process.DescriptionThe $ZUTIL(68,11) function enables or disables read line recall for the current process.This system-wide default behavior can be configured using the $ZUTIL(69,11) function.Refer to $ZUTIL(69,11) — Read Line Recall Mode System Default.You can also enable read line recall for a device, overriding the current status of this feature.To do so, you include the R protocol in an OPEN or USE command for that device. SeeTerminal I/O in <strong>Caché</strong> I/O Device Guide for details on using protocols.Invoking $ZUTIL(68,11) without specifying n returns the current switch setting.606 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


ParametersnThe boolean switch that controls read line recall mode.$ZUTIL(68,15)01Disables read line recall mode.Enables read line recall mode. The system default setting is 1.See Also• $ZUTIL(69,11) Read Line Recall Mode System Default function• Terminal I/O in <strong>Caché</strong> I/O Device Guide$ZUTIL(68,15)Enables or disables I/O device disconnect detection for the current process.$ZUTIL(68,15,n)$ZU(68,15,n)ParametersnThe boolean value that specifies whether <strong>Caché</strong> detects I/O disconnection.DescriptionThe $ZUTIL(68,15) function determines how <strong>Caché</strong> responds to the disconnection of theprincipal I/O device being accessed from the current process. When set to 1, the processreceives a error when a disconnect is detected during a <strong>Caché</strong> <strong>ObjectScript</strong> READor WRITE command to the device. This is known as “error on disconnect.” When set to 0,the process exits without reporting an error to the application when a disconnect is detected.The default is 0.You should be aware that when error on disconnect is enabled, a process continues to executeafter its principal device has been disconnected. It is the responsibility of the application todetect the disconnect condition and exit gracefully. Use care when enabling error on disconnect.The application must be prepared to recognize the error and handle it appropriatelyin error traps.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 607


System and Other FunctionsError on disconnect is only applicable to TCP devices and to terminal devices where a disconnectcan be recognized. Examples are modem controlled terminals and Windows Telnet,Windows LAT, and Windows local cterm (TRM:) connections. Error on disconnect is onlyapplicable to the principal device.You can also test the $ZA special variable to check for terminal disconnection. When bit 11of $ZA for the principal device is set, the principal device has disconnected.This function overrides the system-wide I/O device disconnect detection default. To set thesystem-wide default behavior, go to the System Management Portal, select Configuration,then select Advanced Settings. On the pull-down Category list select Terminal. View andedit the current setting of ErrorOnDisconnect. When 1 (true), <strong>Caché</strong> issues a errorif a disconnect occurs. If 0 (false), no error is issued. The default is 0. To override this defaultsystem-wide, you can use $ZUTIL(69,15) — I/O Device Disconnect Detection SystemDefault.Invoking $ZUTIL(68,15) without specifying n returns the current switch setting.ParametersnThe value that specifies whether <strong>Caché</strong> detects I/O device disconnection.01Disables disconnection detection (the default).Enables disconnection detection.See Also• $ZUTIL(69,15) I/O Device Disconnect Detection System Default function• $ZA special variable• Terminal I/O in <strong>Caché</strong> I/O Device Guide608 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(68,21)$ZUTIL(68,21)Sets synchronous commit mode for the current process.$ZUTIL(68,21,n)$ZU(68,21,n)ParametersnA boolean value that specifies whether or not synchronous transaction commit modeis enabled for the current process.DescriptionYou can use $ZUTIL(68,21) to set the synchronous transaction commit mode for the currentprocess. This enables or disables synchronizing TCOMMIT with the corresponding journalwrite operation. Every TCOMMIT command requests a flush of the journal data involved inthat transaction to disk. When $ZUTIL(68,21) is enabled (set to 1) a TCOMMIT does notcomplete until the journal data write operation completes. When set to 0, TCOMMIT doesnot wait for the write operation to complete.Invoking $ZUTIL(68,21) without specifying n returns the current switch setting.$ZUTIL(68,21) can be used when synchronous transaction commit mode is turned off systemwide(usually to improve performance), but the current process requires synchronouscommit—for example, when interfacing with another system.You can use $ZUTIL(69,21) to set the synchronous transaction commit mode system-wide.Setting $ZUTIL(69,21) changes the system configuration setting and is persistent across<strong>Caché</strong> shutdowns and startups.This system configuration setting can also be changed using the System Management Portal.Select Configuration, then select Advanced Settings. On the pull-down Category list selectTransactions. View and edit the current setting of SynchronousCommit. The default is “false”.ParametersnThe boolean switch that determines the default mode for synchronous transaction commit: 0= TCOMMIT completion does not wait for journal file write completion. 1 = TCOMMITcompletion waits for the journal file write operation to complete. The default is 0.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 609


System and Other FunctionsSee Also• TCOMMIT command• $ZUTIL(69,21) Set synchronous commit mode systemwide function$ZUTIL(68,22)Sets handling of escape sequences when $X is updated for the current process.$ZUTIL(68,22,n)$ZU(68,22,n)ParametersnThe numeric code that specifies the $X update mode for the current process. Thismode should correspond to your computer platform and Intersystems software.DescriptionThe $ZUTIL(68,22) function specifies how <strong>Caché</strong> handles escape sequences when updatingthe $X special variable. When reading a string containing an escape sequence, various Inter-Systems products handle updating the $X special variable differently. You can control theway <strong>Caché</strong> updates $X when writing a string containing an escape sequence. Default behaviorsfor various implementations (including non-<strong>InterSystems</strong> ones) are:• UNIX parses the ANSI-standard escape sequence and counts the rest of the non-escapecharacters in the string against $X.• Alpha VMS does not count any more characters in the string against $X after encounteringan escape character ($CHAR(27)).• Open M [DSM] counts all characters in a string, including the escape character, against$X.• MSM counts all characters in the string, except for the escape character, against $X.To alter the system default setting for $X updating, see $ZUTIL(69,22) — $X Update Modefor Escape Sequences.Invoking $ZUTIL(68,22) without specifying n returns the current switch setting.610 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


Parametersn$ZUTIL(68,25)This argument of $ZUTIL(68,22,n) specifies the method of updating $X for an individualprocess:0123Specifies UNIX and Windows default behavior.Specifies Open M [DSM] default behavior.Specifies MSM default behavior.Specifies Alpha/VAX default behavior.On UNIX and Windows systems, the default value is 0; on OpenVMS (VAX and Alpha)systems, the default value is 3.See Also• $ZUTIL(69,22) $X Update Mode for Escape Sequences function• $X special variable$ZUTIL(68,25)Sets batch or interactive status for the current process.$ZUTIL(68,25,n)$ZU(68,25,n)ParametersnThe boolean value that specifies whether batch or interactive status is active for thecurrent process.DescriptionThe $ZUTIL(68,25,n) function specifies either batch or interactive status for the currentprocess. This allows you to balance resources more effectively.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 611


System and Other FunctionsWhen a new <strong>Caché</strong> process is created, its batch status is 0 (it is categorized as an interactiveprocess). The following code sets its batch status to 1 (categorized as a batch process), whichlessens its resource usage.SET flag=$ZUTIL(68,25,1)WRITE !,"Batch status--former:",flag," current:",$ZUTIL(68,25)As with all $ZUTIL(68) functions, the value returned is the previous setting value, not thenew setting.Once a process has been set in batch status, it keeps that status until it terminates, or untilyou explicitly return it to interactive status as follows:SET flag=$ZUTIL(68,25,0)WRITE !,"Batch status--former:",flag," current:",$ZUTIL(68,25)Invoking $ZUTIL(68,25) without specifying n returns the current switch setting.ParametersnThe boolean switch that controls the status of the issuing process:01Clears batch status and gives the process interactive status. The system defaultsetting is 0.Gives the process batch status.ExampleYou can employ the following sequence of commands to:• Save the current status value• Set a potentially different status• Call a routine or subroutine• Restore the original status612 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(68,26)BatchStatusSET oldflag=$ZUTIL(68,25) ; record inital statusIF oldflag=0 {WRITE !,"Already in Interactive mode"; call interactive routine}ELSE {SET flag=$ZUTIL(68,25,0)WRITE !,"Set to Interactive mode"; call interactive routine}SET newflag=$ZUTIL(68,25,oldflag); restore initial status and return current statusIF oldflag'=newflag {WRITE !,"batch status changed" }ELSE {WRITE !,"batch status unchanged" }QUITThere is not a corresponding $ZUTIL(69) (system-wide) function for $ZUTIL(68,25).See Also• JOB command$ZUTIL(68,26)Sets namespace display in programmer prompt for the current process.$ZUTIL(68,26,n)$ZU(68,26,n)ParametersnThe boolean value that specifies whether <strong>Caché</strong> includes the current namespacename in the terminal prompt for the current process.DescriptionThe $ZUTIL(68,26) function specifies whether the process' current namespace name appearsin the programmer-mode prompt for <strong>Caché</strong> Terminal. The current namespace name is containedin the $ZNSPACE special variable. The current namespace name can be an explicit namespaceor an implied namespace.Issuing $ZUTIL(68,26,1) sets the switch for the current process, so that the namespace nameis displayed. Issuing $ZUTIL(68,26,0) clears the switch for the current process, so that thenamespace name is not displayed. To set this switch for the current process from the programmerprompt, use the XECUTE command, as follows:<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 613


System and Other FunctionsUSER>XECUTE "SET x=$ZUTIL(68,26,0)">If you call $ZUTIL(68,26) without specifying n, $ZUTIL(68,26) returns the current switchsetting.The initial value of this switch depends on the both the system platform and the system-widedefault setting. The system default setting is 1 for Windows systems, and 0 for all otherplatforms.To control whether the current namespace name appears by default as part of the prompt forall processes on the system, use any one of the following:• Go to the System Management Portal, select System Configuration, select AdvancedSettings, on the pull-down Category list select <strong>ObjectScript</strong>. View and edit the currentsetting of PromptShowsNamespace.• $ZUTIL(69,26) — Enable/Disable System Namespace Display Default function.• The %ZSTART user-defined system startup routine (ZSTU startup routines are alsosupported).You can also set various values, including the current namespace, as the terminal prompt forthe current process using $ZUTIL(186).ParametersnThe boolean value that specifies whether <strong>Caché</strong> displays the current namespace as part ofthe process' programmer mode prompt.01Specifies that the current namespace does not appear.Specifies that the current namespace does appear.ExampleThe following example tests the namespace name status, and sets it to display the currentnamespace at the programmer prompt, if necessary.614 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(68,27)SET x=$ZUTIL(68,26)IF x=0 {SET y=$ZUTIL(68,26,1)WRITE !,"Prompt changed to display namespace"}ELSE {WRITE !,"Prompt already displays namespace"}See Also• $ZUTIL(69,26) Set Terminal Prompt Display of Current Namespace System-widefunction• $ZUTIL(186) Set Terminal Prompt Display Values for the Current Process function• XECUTE command• ZNSPACE command• $ZNSPACE special variable$ZUTIL(68,27)Sets or clears network hardening for the current process.$ZUTIL(68,27,n)$ZU(68,27,n)ParametersnThe boolean value that specifies whether <strong>Caché</strong> enables or disables networkhardening for the current process.DescriptionThe $ZUTIL(68,27) function overrides the system-wide network hardening setting for thecurrent process.Invoking $ZUTIL(68,27) without specifying n returns the current switch setting.$ZUTIL(68,27,n) overrides any system-wide setting. Thus, you can activate network hardeningfor a process even if it is deactivated system-wide. You can also deactivate networkhardening for a process even if it is activated system-wide. To enable or disable networkhardening system-wide, set the $ZUTIL(69,27) — Enable/Disable Network Hardening Systemwidefunction.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 615


System and Other Functions<strong>Caché</strong> provides network hardening to allow user jobs to continue processing in the event ofnetwork transport errors. Network hardening allows global references to remote servers tocomplete successfully even if network transport errors occur. When a network transport erroroccurs, the network transport code reestablishes connections and retransmits network requests.Where the user or application must take some action to restore communications, the clientprocess receives a specific error.Note:This function provide network hardening support for DCP (Distributed Cache Protocol)distributed data management. It does not provide support for ECP (EnterpriseCache Protocol) distributed data management.DCP (Distributed Cache Protocol) with network hardening performs multiple retries of anetwork request. ECP (Enterprise Cache Protocol) does not support network hardening anddoes not perform multiple retries. ECP issues a error when encountering anetwork transport error; the suggested programming practice is to roll back the currenttransaction when encountering a error, then retry the transaction. At <strong>Caché</strong>version 5.0 and subsequent, the default for distributed data caching is ECP. For further details,see Introduction and DCP in the Distributed Data Management Guide.You can determine the network hardening process state for a specified process (and otherinformation) using a method of the SYS.Process class, as shown in the following example:ZNSPACE "%SYS"WRITE ##CLASS(SYS.Process).%OpenId($JOB).StateGet()ParametersnThe boolean value that specifies whether <strong>Caché</strong> enables or disables network hardening forthe current process:01Disables network hardening.Enables network hardening. The system default setting is 1.ExampleThe following example tests the status of network hardening for the system and the currentprocess, and enables it for the current process, if necessary:616 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(68,28)SET x=$ZUTIL(69,27)WRITE !,"System-wide network hardening:",xSET y=$ZUTIL(68,27)IF y=0 {SET z=$ZUTIL(68,27,1)WRITE !,"Network hardening enabled:",$ZUTIL(68,27)}ELSE {WRITE !,"Network hardening was already enabled"}See Also• $ZUTIL(69,27) Enable/Disable Network Hardening System-wide legacy function• $ZUTIL(67,4) Determine the Process State legacy function$ZUTIL(68,28)Restricts or permits kills of root-level global nodes for the current process.$ZUTIL(68,28,n)$ZU(68,28,n)ParametersnThe boolean value that specifies whether or not a process can kill root-level(unsubscripted) global nodes.DescriptionThe $ZUTIL(68,28) function specifies whether or not a process can kill root-level (unsubscripted)global nodes. By default, the switch for the process is set to zero (0). The defaultfor the system (set through $ZUTIL(69,28)) is also set to zero (0). This means that killing aroot-level node does not generate an error. For example, you can execute the followingwithout an error:KILL ^aInvoking $ZUTIL(68,28) without specifying n returns the current switch setting.You can set the switch for your process so that root-level global node kills are not allowedby issuing $ZUTIL(68,28,1). After you set the switch, any attempt to kill a root-level nodegenerates a error. For details on error format, refer to the$ZERROR special variable.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 617


System and Other FunctionsParametersnThe value that specifies whether <strong>Caché</strong> allows the current process to kill root-level globalnodes. 0 enables root-level global node kills (the default). 1 disables root-level global nodekills.Notes$ZUTIL(68,28,n) overrides any system-wide setting. Thus, you can prohibit root-nodedeletion even if that prohibition is deactivated system-wide. You can also deactivate prohibitionof root-node deletion even if that prohibition is activated system-wide.This system-wide default behavior can be configured using the $ZUTIL(69,28) function.Refer to $ZUTIL(69,28) — Control Root (Unsubscripted) Node Kills.See Also• KILL command• $ZUTIL(69,28) Control Root (Unsubscripted) Node Kills function$ZUTIL(68,30)Sets error handling behavior for the current process.$ZUTIL(68,30,n)$ZU(68,30,n)ParametersnThe boolean value that specifies whether or not a process uses <strong>Caché</strong>-style errorhandling. 0 specifies <strong>Caché</strong>-style behavior. 1 specifies DSM-style behavior. Thesystem default setting is 0.DescriptionThe $ZUTIL(68,30) function specifies whether a process uses <strong>Caché</strong>-style error handling(the default) or legacy (DSM) error handling.When an error handler is invoked in <strong>Caché</strong>, that error handler remains on the stack of establishederror handlers. Therefore, if an error occurs while the error handler is executing, that618 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


error handler attempts to invoke itself, receives the same error again and enters an infiniteloop, unless that error handler explicitly sets the $ZTRAP special variable to a new value.By default, processes use <strong>Caché</strong>-style error handling, so that the value of the $ZUTIL(68,30)switch is 0.When an error handler is invoked in DSM, the error handler is unwound from the stack.Therefore, if an error occurs while the error handler is executing, that error is handled by theprevious error handler on the stack. You can duplicate this behavior for your process byinvoking this function.Use $ZUTIL(68,30) to set process-specific behavior. This takes precedence over systembehavior, which is set with a call to $ZUTIL(69,30).This system-wide default behavior can be configured using the $ZUTIL(69,30) function.Invoking $ZUTIL(68,30) without specifying n returns the current switch setting.ExampleThe following example lets you view the current state of the switch:WRITE !,"error handling system-wide setting:",$ZUTIL(69,30)WRITE !,"error handling this process setting:",$ZUTIL(68,30)See Also• $ZUTIL(69,30) Set Error Handling Behavior function• ZQUIT command• $ZTRAP special variable• Error Handling in Using <strong>Caché</strong> <strong>ObjectScript</strong>$ZUTIL(68,32)$ZUTIL(68,32)Sets date range and invalid date behavior for the current process.$ZUTIL(68,32,n)$ZU(68,32,n)ParametersnThe boolean value that specifies whether or not a process uses <strong>Caché</strong>-style datebehavior.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 619


System and Other FunctionsDescriptionThe $ZUTIL(68,32) function performs two process-specific operations:• It specifies how the $ZDATE function behaves when it receives invalid input.• It specifies the default range of valid dates for $ZDATE. (This provides backwardcompatibilitywith ISM.)$ZUTIL(68,32) only affects the behavior of $ZDATE; the other date and time functions areunaffected.This system-wide default behavior can be configured using the $ZUTIL(69,32) function.For further details on altering the system default for this switch, see $ZUTIL(69,32). Theinitial system default setting of $ZUTIL(68,32) is 0 for all <strong>Caché</strong> products. The initial defaultsetting of $ZUTIL(68,32) is 1 for all ISM products.Invoking $ZUTIL(68,32) without specifying n returns the current switch setting.ParametersnThe boolean value that specifies $ZDATE behavior. 0 specifies <strong>Caché</strong>-style behavior; 1specifies ISM-style behavior. The system default setting is 0.NotesCalling $ZUTIL(68,32)When you create a new process, its $ZDATE behavior is initialized from the current settingof $ZUTIL(69,32). Calling $ZUTIL(68,32) overrides this behavior for the current process.Changing the setting of $ZUTIL(69,32) affects only processes subsequently created, notexisting processes.Setting the Behavior for Invalid DatesAn invalid date is either not a positive integer, or is not a value within the range of valid dates,as specified above.$ZUTIL(68,32,0) causes $ZDATE to issue the error message or if you submit an invalid date. The behavior can be overriddenby supplying an erropt parameter to the $ZDATE call.$ZUTIL(68,32,1) causes $ZDATE to return the null string if you submit an invalid date.This behavior is set for any $ZDATE function call, regardless of the number of parameters.620 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(68,34)Setting the Range of Valid Dates$ZUTIL(68,32,0) sets the default range of valid dates for <strong>Caché</strong> . This range is from 0 through2980013, inclusive, which corresponds to dates from 12/31/1840 through 12/31/9999. Thisrange can be restricted by setting the $ZDATE mindate and maxdate parameters.$ZUTIL(68,32,1) sets the default range of valid dates for ISM compatibility. This range isfrom 1 through 94232, inclusive, which corresponds to dates from 01/01/1841 through12/30/2098. This date range is set for any $ZDATE function call which has three or fewerparameters. If a $ZDATE function call has more than three parameters, the valid date rangeis taken either from the $ZDATE mindate and maxdate parameters (if specified) or from thedate range established for the current locale.See Also• $ZDATE function• $ZUTIL(69,32) Set Date Range and Invalid Date Behavior function• More information on locales in Customized National Language Translations$ZUTIL(68,34)Sets whether asynchronous errors can interrupt the current process.$ZUTIL(68,34,n)$ZU(68,34,n)ParametersnThe boolean value that specifies whether or not the current process should receiveasynchronous errors.DescriptionThe $ZUTIL(68,34) function specifies whether asynchronous errors can interrupt the currentprocess.This system-wide default behavior can be configured using the $ZUTIL(69,34) function.For further details, see $ZUTIL(69,34).Invoking $ZUTIL(68,34) without specifying n returns the current switch setting.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 621


System and Other FunctionsParametersnThe value that specifies the process-specific behavior in response to asynchronous errors. 1enables the reception of asynchronous errors; 0 disables the reception of asynchronous errors.The system default setting is 1.NotesEven if a process has disabled reception of asynchronous errors, an asynchronous error willbe triggered the next time the process issues a ZSYNC command.See Also• ZSYNC command• $ZUTIL(69,34) Processes Interruptible by Asynchronous Errors function$ZUTIL(68,39)Enables or disables caching for the current process.$ZUTIL(68,39,n)$ZU(68,39,n)ParametersnThe boolean value that specifies whether or not a process has caching enabled.Note that settings are: 0 = caching enabled. 1 = caching disabled.DescriptionThe $ZUTIL(68,39) function disables or enables caching for the current process. Whencaching is enabled, <strong>Caché</strong> will cache DCP data for quicker retrieval.This function overrides the system-wide enable caching default.Invoking $ZUTIL(68,39) without specifying n returns the current switch setting.622 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


ParametersnThe boolean switch that determines whether caching is disabled for the current process. 0 =caching enabled. 1 = caching disabled. $ZUTIL(69,39) uses the same values to override thedefault setting system-wide. Note that the boolean values used in $ZUTIL(68,39) and$ZUTIL(69,39) are the opposite of those found in System Configuration.Caching enabled is the system-wide default setting. Setting $ZUTIL(68,39) overrides thesystem-wide setting for the current process.This system-wide default behavior can be configured using the $ZUTIL(69,39) function.See Also• $ZUTIL(69,39) Disable or Enable Caching System-wide function$ZUTIL(68,40)$ZUTIL(68,40)Sets sequential file end-of-file handling for the current process.$ZUTIL(68,40,n)$ZU(68,40,n)ParametersnThe boolean value that sets end-of-file handling for the current process. 0=<strong>Caché</strong>format. 1=MSM format.DescriptionThe $ZUTIL(68,40) function specifies end-of-file flagging format. This function is providedto support the porting of MSM routines that use $ZCYC to check for end of file on sequentialfile reads.Calling $ZUTIL(68,40,1) eliminates the error for sequential files for thecurrent process. Instead, when the end of a file is reached, the READ command returns anull string, the $ZPOS special variable is set to "" (the null string), and the $ZEOF specialvariable is set to -1.Invoking $ZUTIL(68,40) without specifying n returns the current switch setting.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 623


System and Other FunctionsThis function overrides the system-wide end-of-file handling default for the current process.This system-wide default behavior can be configured using the $ZUTIL(69,40) function.See $ZUTIL(69,40).ParametersnThe value that specifies how ends of files are flagged. 0 specifies that ends of files are flaggedin standard <strong>Caché</strong> format (the default). 1 specifies that ends of files are flagged in MSM format.See Also• $ZUTIL(69,40) End-of-File Handling for Sequential Files function• READ command• $ZEOF special variable• $ZPOS special variable• Sequential File I/O in <strong>Caché</strong> I/O Device Guide$ZUTIL(68,42)Sets $JOB format for the current process.$ZUTIL(68,42,n)$ZU(68,42,n)ParametersnThe boolean value that specifies whether or not a process uses the standard $JOBreturn string.DescriptionThe $ZUTIL(68,42) function specifies the format that the $JOB special variable returns forthe current process.This function provides for a unique value for $JOB on networked systems. This is usefulwhen using $JOB to index globals accessed by more than one networked system. (In the624 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


form $ZUTIL(68,42,1), the $JOB special variable returns a string of the formatprocessid:nodename.)This system-wide default behavior can be configured using the $ZUTIL(69,42) function.Invoking $ZUTIL(68,42) without specifying n returns the current switch setting.ParametersnThe value that specifies the string format that $JOB returns. 0 specifies the standard $JOBformat (the default); 1 specifies the format as processid:nodename. The $ZUTIL(131)function sets the value of the nodename variable.ExampleThe following example shows the two possible values for $JOB:SET x=$ZUTIL(68,42)IF x=0 {WRITE !,"Initially standard format ",xWRITE !,"Standard $JOB format: ",$JOBSET y=$ZUTIL(68,42,1)WRITE !,"Extended $JOB format: ",$JOBSET y=$ZUTIL(68,42,0) ; restore settingQUIT}ELSE {WRITE !,"Initially extended format",xWRITE !,"Extended $JOB format: ",$JOBSET y=$ZUTIL(68,42,0)WRITE !,"Standard $JOB format: ",$JOBSET y=$ZUTIL(68,42,1) ; restore settingQUIT}See Also• $ZUTIL(69,42) $JOB Format System Default function• $ZUTIL(131) Set and Get the System Name and IP Address function• $JOB special variable$ZUTIL(68,42)<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 625


System and Other Functions$ZUTIL(68,43)Sets clearing of global vectors for the current process.$ZUTIL(68,43,n)$ZU(68,43,n)ParametersnThe boolean value that specifies whether or not $ZUTIL(5) clears global vectorsfor the current process.DescriptionThe $ZUTIL(68,43) function specifies whether or not issuing the $ZUTIL(5) function withthe current namespace clears global vectors for the current process.$ZUTIL(68,43,1) provides compatibility with $ZUTIL(5) behavior prior to <strong>Caché</strong> version3.1; this call enables the clearing of global vectors for the current process when $ZUTIL(5)is issued with the current namespace.This system-wide default behavior can be configured using the $ZUTIL(69,43) function.For further details, see $ZUTIL(69,43).Invoking $ZUTIL(68,43) without specifying n returns the current switch setting.ParametersnThe value that specifies whether or not there is global vector clearing. 0 (default <strong>Caché</strong>behavior) disables global vector clearing. 1 (legacy behavior) clears global vectors. The systemdefault is 0.See Also• $ZUTIL(5) Display or Switch Namespace function• $ZUTIL(69,43) Sets Clearing of Global Vectors System-wide function626 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(68,45)$ZUTIL(68,45)Sets truncation mode for string-to-number conversions for the current process.$ZUTIL(68,45,n)$ZU(68,45,n)ParametersnThe boolean value that specifies whether or not the current process truncatesnumbers.DescriptionNormally, when <strong>Caché</strong> encounters a number larger than 9223372036854775807 E127 (orsmaller than -9223372036854775808 E127) it issues a error. The$ZUTIL(68,45) function specifies whether or not the current process truncates very largenumbers during string-to-number conversions. The default behavior is not to truncate numbersand, instead, to generate the error.This function only prevents errors during string-to-number conversions.A error can still occur during arithmetic operations.When set (n=1), the exponent is truncated to the biggest valid number and the conversioncontinues.This function is provided for MSM compatibility. Specifying $ZUTIL(55,8) to set MSMlanguage mode automatically sets $ZUTIL(68,45) and $ZUTIL(69,45). ($ZUTIL(68,45,0)is the default setting for the switch in all language modes except MSM mode.)This system-wide default behavior can be configured using the $ZUTIL(69,45) function.Invoking $ZUTIL(68,45) without specifying n returns the current switch setting.ParametersnThe boolean value that specifies whether number truncation occurs. 0 preserves large numbersand issues a error (the default); 1 enables truncation of large numbersduring the string-to-number conversion and suppresses errors.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 627


System and Other FunctionsSee Also• $ZUTIL(55) Language Mode Switch function• $ZUTIL(69,45) Truncate Numbers During String-to-Number Conversion function$ZUTIL(68,51)Sets whether or not changing namespaces changes operating system directories for the currentprocess.$ZUTIL(68,51,n)$ZU(68,51,n)ParametersnThe boolean value that specifies whether or not changing the namespace alsochanges the default directory for the current process.DescriptionThe $ZUTIL(68,51) function specifies — for the current process — whether changing thenamespace also changes the default directory. By default, changing to a new namespacecauses <strong>Caché</strong> to change the directory at the operating system level to the default directoryfor that namespace.Invoking $ZUTIL(68,51) without specifying n returns the current switch setting.To set this behavior on a system-wide basis, use $ZUTIL(69,51). The system-wide defaultbehavior is configurable. Go to the System Management Portal, select System Configuration,select Advanced Settings, on the pull-down Category list select <strong>ObjectScript</strong>. View and editthe current setting of SwitchOSDirectory. The default is “false” .Call $ZUTIL(168) to explicitly set the default directory at the operating system level.For information on mapping database directories to namespaces, refer to Configuring <strong>Caché</strong>in <strong>Caché</strong> System Administration Guide.628 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


ParametersnThe value that specifies the default behavior when changing namespaces. 0 specifies thatchanging the namespace automatically changes the default directory to the directory for thatnamespace (the default); 1 specifies that changing the namespace does not change the defaultdirectory.See Also• $ZUTIL(69,51) Namespace Default Directory Assignment function• $ZUTIL(168) Set Current Working Directory function$ZUTIL(68,63)$ZUTIL(68,63)Enables or disables the use of “e” as an exponent symbol for the current process.$ZUTIL(68,63,n)$ZU(68,63,n)ParametersnThe boolean value that specifies whether or not a process should treat lowercase“e” as an exponent symbol. 1 = evaluate “e” as an exponent symbol. 0 = do notevaluate “e” as an exponent symbol. The default is 1.DescriptionThe $ZUTIL(68,63) function disables or enables the evaluation of the lowercase letter “e”as an exponent symbol for the current process. $ZUTIL(68,63) has no effect on the evaluationof uppercase “E” as an exponent symbol.Invoking $ZUTIL(68,63) without specifying n returns the current switch setting.This function overrides the system-wide default, which is initialized to evaluate both “E” and“e” as exponent symbols. To set the system-wide default, you can use $ZUTIL(69,63). Forfurther details on altering the system default for this switch, see $ZUTIL(69,63).See Also• $ZUTIL(69,63) Disable or Enable “e” as Exponent System-wide function<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 629


System and Other Functions$ZUTIL(69)Sets system-wide configuration defaults.$ZUTIL(69,subfunc,n)$ZU(69,subfunc,n)ParameterssubfuncnAn integer specifying which $ZUTIL(69) subfunction to invoke.Optional — The value used to set the invoked function, usually a boolean(0 or 1), occasionally a numeric code. If this parameter is omitted, the$ZUTIL(69) subfunction returns its current value.DescriptionUse the $ZUTIL(69) subfunctions to set or clear system-wide configuration settings.Although each of the $ZUTIL(69,subfunc,n) functions control a different aspect of systemoperation, all of them have the following operating characteristics in common:• You must have the %Admin_Manage:Use privilege to execute any of the $ZUTIL(69)functions. These functions can also be invoked by % routines located in the manager'sdirectory. For further details, refer to the Privileges and Permissions chapter of the <strong>Caché</strong>Security Administration Guide.• Whenever you issue a call to $ZUTIL(69,subfunc) without specifying the third, nparameter, $ZUTIL(69,subfunc) returns the current setting of the switch specified bysubfunc.• Whenever you make a call to $ZUTIL(69,subfunc,n), the function first sets the switchto the new value specified by n, and then returns the previous switch value.• Whenever you change a system setting through the use of $ZUTIL(69,subfunc,n), onlyprocesses that log in subsequent to the change are affected. Processes that logged inbefore the change still operate under the old switch value.In a most cases, the $ZUTIL(69) function provides a system-wide override for a system-widedefault value. Setting one of these $ZUTIL(69) functions overrides the system configurationdefault; it does not change the default setting. The value set by $ZUTIL(69) applies to allsubsequent processes running on the current instance of <strong>Caché</strong>; stopping and restarting <strong>Caché</strong>causes these configuration values to revert to their defaults.630 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


In a few cases, the $ZUTIL(69) function provides a means to change the system-wide defaultvalue. These defaults can also be configured using various System Management Portal SystemConfiguration Advanced Settings. In these cases, the $ZUTIL(69) function changes theconfiguration setting for the current instance of <strong>Caché</strong>, and this change persists when <strong>Caché</strong>is stopped and restarted.The permanence of changes made using a $ZUTIL(69) function is described for each individual$ZUTIL(69) function.Many of the $ZUTIL(69) flags can be set on a per-process basis by using the corresponding$ZUTIL(68) subfunction.The following table shows the $ZUTIL(69) subfunctions recognized by <strong>Caché</strong>. For eachsubfunction the meaning and default are also given.Subfunctions$ZUTIL(69)Subfunction Number and OperationDefaultSettingSettablefromManagementPortal?PersistentOver <strong>Caché</strong>Shutdown?$ZUTIL(69,0) Default $ZUTIL(18) Values0YesNo$ZUTIL(69,1) Null Subscript Mode SystemDefault0NoNo$ZUTIL(69,2) Default Mode for SequentialFiles0NoNo$ZUTIL(69,3) Automatic File Creation ModeSystem Default0NoNo$ZUTIL(69,4) Default Device for JobbedProcesses (UNIX and OpenVMS)UNIX :/dev/nullOpenVMS:NL:NoNo$ZUTIL(69,5) Argumentless BREAK SystemDefault1NoNo$ZUTIL(69,6) Reliable SET Networking ModeSystem Default0NoNo$ZUTIL(69,7) <strong>Reference</strong>-in-Kind Mode SystemDefault0YesNo$ZUTIL(69,8) ZA and ZD Modes0NoNo<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 631


System and Other FunctionsSubfunction Number and OperationDefaultSettingSettablefromManagementPortal?PersistentOver <strong>Caché</strong>Shutdown?$ZUTIL(69,10) Freeze System if Journal FullSystem Default0YesYes$ZUTIL(69,11) Read Line Recall ModeSystem Default1NoNo$ZUTIL(69,13) Asynchronous SET/KILL Errorsto mneterr.log File0NoNo$ZUTIL(69,14) Asynchronous SET/KILL Errorsto Operator Console0NoNo$ZUTIL(69,15) Modem Disconnect DetectionSystem Default0YesYes$ZUTIL(69,19) DDP Password Security0NoNo$ZUTIL(69,20) Transfer Nodes with NullSubscripts with DSM-DDP0NoNo$ZUTIL(69,21) Synchronous TransactionCommit Mode0YesYes$ZUTIL(69,22) $X Update Mode for EscapeSequences0NoNo$ZUTIL(69,24) $ZF Process Deletion bySTOP/ ID (OpenVMS)0NoNo$ZUTIL(69,26) System Namespace DisplayDefault1YesYes$ZUTIL(69,27) Network Hardening1NoNo$ZUTIL(69,28) Control Root (Unsubscripted)Node Kills0NoNo$ZUTIL(69,30) Error Handling Behavior0NoNo$ZUTIL(69,31) Network Locks HandlingFollowing a DCP Outage0NoNo$ZUTIL(69,32) Date Range and Invalid DateBehavior0NoNo632 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(69)Subfunction Number and OperationDefaultSettingSettablefromManagementPortal?PersistentOver <strong>Caché</strong>Shutdown?$ZUTIL(69,34) Processes Interruptible byAsynchronous Errors1NoNo$ZUTIL(69,35) Silent Retry for domainspaceConnection Attempts0NoNo$ZUTIL(69,37) Physical Cursor PositioningMode0YesYes$ZUTIL(69,39) Caching for Future Processes0NoNo$ZUTIL(69,40) End-of-File Handling forSequential Files0NoNo$ZUTIL(69,42) $JOB Format System Default0NoNo$ZUTIL(69,43) Clearing of Global Vectors0NoNo$ZUTIL(69,44) Nagle Algorithm for TelnetTransmissions0YesYes$ZUTIL(69,45) Truncate Numbers DuringString-to-Number Conversion0NoNo$ZUTIL(69,49) Logging of TransactionRollbacks0NoNo$ZUTIL(69,51) Namespace Default DirectoryAssignment0YesYes$ZUTIL(69,60) Asynchronous TelnetDisconnect Errors0NoNo$ZUTIL(69,63) — “e” as Exponent Symbol1NoNoSee Also• $ZUTIL(68) Set Configuration Options for the Current Process functions<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 633


System and Other Functions$ZUTIL(69,0)Sets undefined variable default handling system-wide.$ZUTIL(69,0,n)$ZU(69,0,n)ParametersnA numeric code specifying how to handle undefined variables system-wide.Description$ZUTIL(69,0) is used to specify a system-wide default behavior for handling undefinedvariables. Setting n changes this behavior for local variables, process-private globals, andglobal variables systemwide; it has no effect on special variables.$ZUTIL(69,0) only affects variables invoked by subsequent processes; it does not affect thecurrent process. To set handling of undefined variables for the current process, use the$ZUTIL(18) Undefined Variable Behavior function.The value you assign to the variable n becomes the system-wide default behavior for allsubsequently initiated processes. The native default setting is 0, which specifies that allundefined variables result in the error message.Invoking $ZUTIL(69,0) without specifying n returns the current switch setting.The system-wide default behavior is configurable. Go to the System Management Portal,select System Configuration, select Advanced Settings, on the pull-down Category list select<strong>ObjectScript</strong>. View and edit the current setting of UndefVarBehavior. The default is 0.Setting $ZUTIL(69,0) overrides the System Configuration default; it does not change thedefault setting.ParametersnA numeric code that specifies how <strong>Caché</strong> treats an undefined variable:634 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(69,0)012Issues the error for any undefined variable.Returns a null string for a reference to an undefined variable with subscripts, andissues the error for undefined variables without subscripts.Returns a null string (instead of issuing an error) for any undefinedvariable.Integers larger than 2 or smaller than –1 are ignored as no-ops. A value of –1 sets$ZUTIL(69,0) to 2.NotesThe $DATA function tests if a specified variable is defined. It returns 0 if the variable isundefined.The $GET function returns a default value if a specified variable is undefined. The basicform of $GET returns a null string if the specified variable is undefined.The $ZUTIL(69,0) function defines handling behavior for all undefined variables. Setting$ZUTIL(69,0) has no effect on $DATA or $GET.You can use the ZWRITE command to display defined variables that have a null string value;ZWRITE does not display undefined variables that return a null string.ExampleThe following example shows the system-wide and per-process settings for handling undefinedvariables.NEW fredWRITE !,"systemwide:",$ZUTIL(69,0)," process:",$ZUTIL(18)SET y=$ZUTIL(18,2)WRITE !,"systemwide:",$ZUTIL(69,0)," process:",$ZUTIL(18)SET x=$ZUTIL(69,0,1)WRITE !,"systemwide:",$ZUTIL(69,0)," process:",$ZUTIL(18)WRITE !,$GET(fred,"Variable is undefined")IF fred="" {WRITE !,"null string for undefined variable" }ELSE { WRITE !,"something is wrong here" }SET x=$ZUTIL(69,0,0) // reset to default for next timeQUITSee Also• $ZUTIL(18) Undefined Variable Behavior function• ZWRITE command• $DATA function<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 635


System and Other Functions• $GET function$ZUTIL(69,1)Sets null subscript mode default system-wide.$ZUTIL(69,1,n)$ZU(69,1,n)ParametersnThe boolean value that specifies whether or not to enable the setting and referencingof null subscripted globals.DescriptionUse $ZUTIL(69,1) to specify the system-wide default setting for the null subscript modeswitch.If null subscripted globals are not enabled (n=0), attempting to set a null subscripted variable,such as SET ^x("")=99, or to reference a null subscript, such as WRITE ^x(""), results ina error. For details on error format, refer to the $ZERRORspecial variable.If null subscripted globals are enabled (n=1), you can set a null subscripted variable, such asSET ^x("")=99, just like any other variable. Referencing an undefined null subscriptedvariable results in a error.Invoking $ZUTIL(69,1) without specifying n returns the current switch setting.ParametersnThe switch that determines the default setting for the null subscript mode system-wide. 0 =Setting/referencing null subscripted globals disabled. 1 = Setting/referencing null subscriptedglobals enabled. The native default for this switch is OFF (0).NotesThe system-wide default behavior is that a null subscript reference causes a error. This configuration default cannot be changed using the System Management Portal.636 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


Setting $ZUTIL(69,1) overrides the system configuration default; it does not change thedefault setting.You can also enable/disable this mode on a per-job basis. For information on how to do this,see $ZUTIL(68,1) Null Subscript Mode Process Switch.The setting of the Null Subscript Mode has no effect on the use of a null string as a subscriptindex in $ORDER and $QUERY.ExampleThe following example tests the null subscript mode. If null subscripts are enabled locally,it creates some.NullSubsTestSET a=$ZUTIL(69,1)SET b=$ZUTIL(68,1)IF b=1 {WRITE !,"null subscripts enabled locally"UseNullSubsWRITE !,"system:",a," local:",b,!SET ^x("")=99,^x(0)=0,^x(1)=1ZWRITE ^xQUIT }ELSEIF a=1 {WRITE !,"null subscripts enabled system-wide"WRITE !,"system:",a," local:",bQUIT }ELSE {WRITE !,"will enable null subscripts"WRITE !,"system:",a," local:",bSET ret=$ZUTIL(69,1,1) ; enable system-wideWRITE !,"system:",$ZUTIL(69,1)," local:",$ZUTIL(68,1)SET y=$ZUTIL(68,1,1) ; enable for current processWRITE !,"system:",$ZUTIL(69,1)," local:",$ZUTIL(68,1)GOTO UseNullSubs}QUITSee Also• $ZUTIL(68,1) Null Subscript Mode Process Switch function$ZUTIL(69,1)<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 637


System and Other Functions$ZUTIL(69,2)Sets sequential file open mode system-wide default.$ZUTIL(69,2,n)$ZU(69,2,n)ParametersnThe boolean value that specifies the system-wide default mode for sequential fileson OPEN. The options are: 0=Read-only, 1=Read/Write.DescriptionUse $ZUTIL(69,2) to specify the system-wide default open mode for sequential files whenan OPEN command is issued with no mode parameter specified. The two available modesare open for read-only (0) and open for reading and writing (1). On OpenVMS systems, thedefault value is 1. On all other platforms, the default value is 0.Invoking $ZUTIL(69,2) without specifying n returns the current switch setting.This configuration default cannot be changed using the System Management Portal.Setting $ZUTIL(69,2) overrides the default system-wide; it does not change the systemconfiguration setting.This open mode default option can be set for the current process by calling $ZUTIL(68,2).ParametersnThe switch that determines the system-wide default mode for sequential files on OPEN: 0means R is the default; 1 means RW is the default. The native default mode for this switchis 0 ("Read").ExampleThe following example sets the open mode default, then opens a sequential file:638 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(69,3)SET x=$ZUTIL(69,2),y=$ZUTIL(68,2)WRITE !,"system-wide open mode:",xWRITE !,"current process open mode:",yIF y=0 {SET z=$ZUTIL(68,2,1)WRITE !,"Set the process open mode to:",$ZUTIL(68,2)}ELSE {WRITE !,"Open mode was already set to:",$ZUTIL(68,2)}OPEN "c:\myfiles\seqtest1":("NRW"):5; ...QUITSee Also• $ZUTIL(68,2) — Open Mode for Sequential Files function• OPEN command• Sequential File I/O in <strong>Caché</strong> I/O Device Guide$ZUTIL(69,3)Sets automatic sequential file creation system-wide.$ZUTIL(69,3,n)$ZU(69,3,n)ParametersnA boolean value that specifies whether or not an OPEN command should create anew sequential file if the specified sequential file does not exist.DescriptionIf you attempt to open a sequential file in "W" or "RW" mode but that file does not yet exist,the default behavior (for all platforms except OpenVMS) is for <strong>Caché</strong> to hang until the fileis actually created or the process is resolved by timeout expiration or by calling the RESJOButility. On OpenVMS systems, the default is to create a new sequential file.Invoking $ZUTIL(69,3) without specifying n returns the current switch setting.This configuration default cannot be changed using the System Management Portal.You can use $ZUTIL(69,3) to set a system-wide automatic file creation mode that causes asequential file to be created automatically when a user issues the OPEN command in "W"<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 639


System and Other Functionsor "RW" mode for a file that does not already exist. Setting $ZUTIL(69,3) overrides thisdefault system-wide; it does not change the System Configuration setting.You can set this automatic file creation mode for the current process using $ZUTIL(68,3).The system-wide or current-process default behavior can be overridden for individual OPENcommands using the “E” (or /CREATE) mode parameter. The OPEN mode parameters arelisted in Sequential File I/O in the <strong>Caché</strong> I/O Device Guide.ParametersnThe boolean switch that determines the system-wide default mode for nonexistent sequentialfiles on OPEN: 0 = Automatic new file creation disabled. 1 = Automatic new file creationenabled.See Also• $ZUTIL(68,3) Automatic Sequential File Creation Mode Process Default function• OPEN command• Sequential File I/O in <strong>Caché</strong> I/O Device Guide$ZUTIL(69,4)Sets the default device for jobbed processes on UNIX and OpenVMS systems.$ZUTIL(69,4,n)$ZU(69,4,n)ParameternThe boolean value to set the default assignment of the principal device associatedwith jobbed processes system-wide.DescriptionUse $ZUTIL(69,4) to specify the system-wide default for the principal device associatedwith jobbed processes.Invoking $ZUTIL(69,4) without specifying n returns the current switch setting.640 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


Setting $ZUTIL(69,4) overrides the default system-wide; it does not change the systemconfiguration setting. The configuration default cannot be changed using the System ManagementPortal.ParametersnA boolean switch that determines the system-wide default mode for the principal deviceassociated with jobbed processes. 0 = Use the null process (NL: or /dev/null) as the principaldevice. 1 = Use principal device of the parent process.NotesKeep the following points in mind when you use $ZUTIL(69,4,n):Windows SystemsThis function is a no-op. A call to $ZUTIL(69,4) returns 0. A call to $ZUTIL(69,4,1) doesnot issue an error message, but performs no operation and returns 0.UNIX Systems• You can use this function to maintain compatibility with prior releases. In UNIX versionsprior to 4.4.91-12, a child process retained the principal devices of its parent. If you haveenabled this compatibility mode and subsequently wish to disable it, issue $ZUTIL(69,4,0)to restore /dev/null as the default device for JOBbed process.• Reading from the null device returns the null string.OpenVMS/Alpha Systems<strong>Caché</strong> opens the principal input and output devices with a timeout of 2 seconds.If you job a process that accesses its principal input device, and it cannot open that device,the process gets a error. Failing to open the principal output device does notgenerate a error; the error occurs only if the input device cannot be opened.Reading from the null device results in a error.OpenVMS/VAX Systems$ZUTIL(69,4)If you job a process that accesses its principal input device, and it cannot open that device,it hangs until it either opens the device or is killed by calling the RESJOB utility. Failing toopen the principal output device does not generate a error; the error occursonly if the input device cannot be opened.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 641


System and Other FunctionsReading from the null device results in a error.See Also• $IO special variable• $PRINCIPAL special variable$ZUTIL(69,5)Enables argumentless BREAK processing system-wide.$ZUTIL(69,5,n)$ZU(69,5,n)ParametersnThe switch that determines the system-wide default behavior of argumentless BREAK:0 = <strong>Caché</strong> treats an argumentless BREAK as a no-op. 1 = <strong>Caché</strong> executes BREAKon argumentless BREAK (the default).DescriptionUse $ZUTIL(69,5) to enable or disable the processing of argumentless BREAK commandssystem-wide. You can override this system-wide default on a per-process basis by using$ZUTIL(68,5).Invoking $ZUTIL(69,5) without specifying n returns the current switch setting.ParametersnThe default setting for this switch is 1. <strong>InterSystems</strong> provides this capability for backwardscompatibility.This configuration default cannot be changed using the System Management Portal.Setting $ZUTIL(69,5) overrides the System Configuration default; it does not change thedefault setting.See Also• BREAK command642 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(69,6)• $ZUTIL(68,5) Argumentless BREAK Process Switch function• Debugging chapter in Using <strong>Caché</strong> <strong>ObjectScript</strong>$ZUTIL(69,6)Sets reliable SET networking mode system-wide.$ZUTIL(69,6,n)$ZU(69,6,n)ParametersnThe boolean value that specifies whether or not Reliable SET Networking mode isenabled system-wide.DescriptionUse $ZUTIL(69,6) to specify the system-wide setting for the Reliable SET Networking modeswitch.When Reliable SET mode is enabled, each request of a SET, KILL, or LOCK commandfrom a DCP client that results in a network error message (such as , , or ) waits for a reply before proceeding. When Reliable SET modeis disabled, the local system ignores errors incurred by SET, KILL, and LOCK requests.By default, Reliable SET mode is disabled, causing the local system to ignore such errors.Setting $ZUTIL(69,6) overrides the default system-wide; it does not change the systemconfiguration setting. This configuration default cannot be changed using the System ManagementPortal.Invoking $ZUTIL(69,6) without specifying n returns the current switch setting.You can also enable or disable this mode on a per-job basis. For information on how to dothis, see $ZUTIL(68,6) Reliable SET Networking Mode Process Switch.ParametersnThe switch to turn the Reliable SET mode switch on or off. 0 = Disable Reliable SET mode.1 = Enable Reliable SET mode. The native default for this switch is “false” (0).<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 643


System and Other FunctionsSee Also• KILL command• LOCK command• SET command• $ZUTIL(68,6) Reliable SET Networking Mode Process Switch function$ZUTIL(69,7)Retains or strips extended global reference from globals system-wide.$ZUTIL(69,7,n)$ZU(69,7,n)ParameternThe boolean switch to set the default for handling extended global referencessystem-wide.DescriptionUse $ZUTIL(69,7) to specify the system-wide default setting for the Extended Global <strong>Reference</strong>mode switch. This switch controls whether namespace names are returned as part ofa global name by the $NAME and $QUERY functions. <strong>Caché</strong> provides for stripping ofextended global references for purposes of backwards compatibility. The native default forthis switch is 0.0 = Do not strip the extended global reference; this enables extended reference as a systemwidedefault.1 = Strip the extended global reference and return just the global; this disables extended referenceas a system-wide default.Invoking $ZUTIL(69,7) without specifying n returns the current switch setting.For further information on extended global references, see Extended Global <strong>Reference</strong>s inUsing <strong>Caché</strong> Multi-Dimensional Storage.644 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


NotesThe system-wide default behavior is configurable. Go to the System Management Portal,select System Configuration, select Advanced Settings, on the pull-down Category list select<strong>ObjectScript</strong>. View and edit the current setting of QueryStripsExtendedRef. The default is“false” .Setting $ZUTIL(69,7) overrides the System Configuration default; it does not change thedefault setting.You can also disable or enable this mode on a per-job basis. For information on how to dothis, see$ZUTIL(68,7) Strip Extended Global <strong>Reference</strong>s.See Also• $NAME function• $QUERY function• $ZUTIL(68,7) Strip Extended Global <strong>Reference</strong>s function$ZUTIL(69,8)$ZUTIL(69,8)Sets ZA and ZD locking modes system-wide.$ZUTIL(69,8,n)$ZU(69,8,n)ParameternThe boolean value to set the system-wide default locking behavior when ZA andZD are called.DescriptionInvoking $ZUTIL(69,8,n) causes all ZA (ZALLOCATE) and ZD (ZDEALLOCATE)resource locking commands in <strong>Caché</strong> mode routines to act in either Open M [DSM] modeor <strong>Caché</strong> mode. The ZA and ZD commands are obsolete; this function is provided for compatibilityonly.Invoking $ZUTIL(69,8) without specifying n returns the current switch setting.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 645


System and Other FunctionsParametersnThe boolean switch to set the system-wide default setting for ZA and ZD behavior.0 = ZA and ZD commands act in <strong>Caché</strong> mode. In <strong>Caché</strong> mode, ZA and ZD are synonymouswith LOCK+ and LOCK–.1 = ZA and ZD commands act in DSM for OpenVMS mode. In DSM-11 mode, ZA can onlybe undone by ZD and LOCK+ can only be undone by LOCK–. All ZA commands in thesame location can be undone with ZD.The default is zero (0). For information about these modes, see the discussion of DSM compatibilitymodes in Open M Language Compatibility in Using <strong>Caché</strong> <strong>ObjectScript</strong>.NotesThe default is 0 (<strong>Caché</strong> behavior). This configuration default cannot be changed using theSystem Management Portal. Setting $ZUTIL(69,8) overrides the System Configurationdefault; it does not change the default setting.ZA and ZD modes are provided for compatibility purposes only. Use the LOCK +variableand LOCK –variable commands, rather than the obsolete ZA and ZD commands.See Also• LOCK command• ^$LOCK structured system variable• ZALLOCATE and ZDEALLOCATE in Open M Language Compatibility in Using <strong>Caché</strong><strong>ObjectScript</strong>646 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(69,10)$ZUTIL(69,10)Sets system behavior when journal is full.$ZUTIL(69,10,n)$ZU(69,10,n)ParametersnThe boolean value that specifies which system behavior applies when a journal isfull.Description$ZUTIL(69,10) determines <strong>Caché</strong> behavior when an error occurs in writing to the journal.• If this option is set to “true” (1), as soon as the error occurs all global activities that arenormally journaled are blocked, which causes other jobs to block. The typical outcomeis that <strong>Caché</strong> goes into a hang state until the journaling problem is resolved, and thenresumes running. While <strong>Caché</strong> is hanging, the administrator can take corrective measures,such as freeing up space on a disk that is full, switching the journal to a new disk, etc.This option has the advantage that once the problem is fixed and <strong>Caché</strong> resumes running,no journal information has been lost. It has the disadvantage that the system is lessavailable while the problem is being solved.• If this option is set to “false” (0), when a journaling error occurs journaling is entirelydisabled, while <strong>Caché</strong> continues running as normal. <strong>Caché</strong> sends a console message toalert the administrator, who can fix the problem and then run ^JRNSWTCH at the consoleto restart journaling.The default is zero (0). The native default for this switch is “false” (0); that is, to suspendjournaling and allow <strong>Caché</strong> processing to continue.Invoking $ZUTIL(69,10) without specifying n returns the current switch setting.This system-wide default can be configured. Go to the System Management Portal, selectSystem Configuration, select Advanced Settings, on the pull-down Category list select Journal.View and edit the current setting of FreezeOnError.Setting $ZUTIL(69,10) changes the system configuration setting shown in the SystemManagement Portal; this change persists across a <strong>Caché</strong> shutdown and restart.You can use $ZUTIL(78,22) to return journaling information.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 647


System and Other FunctionsParametersnThe switch that determines behavior: 0 = Journaling suspends and processing continues. 1 =System freezes.See Also• $ZUTIL(78,22) Return Journaling Information function• Journaling in the <strong>Caché</strong> High Availability Guide$ZUTIL(69,11)Sets Read Line Recall mode system-wide.$ZUTIL(69,11,n)$ZU(69,11,n)ParameternThe boolean value to enable or disable Read Line Recall mode system-wide.Description$ZUTIL(69,11) controls Read Line Recall mode system-wide.Invoking $ZUTIL(69,11) without specifying n returns the current switch setting.ParametersnThe switch that controls Read Line Recall mode. 0 = Disables Read Line Recall mode as asystem default. 1 = Enables Read Line Recall mode as a system default.The native default for this switch is on (1); that is, enable Read Line Recall.NotesThis configuration default cannot be changed using the System Management Portal.648 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


Setting $ZUTIL(69,11) overrides the System Configuration default; it does not change thedefault setting.You can also disable or enable this mode on a per-job and per-device basis. For informationon setting this for a job, see $ZUTIL(68,11) Read Line Recall Mode Process Switch.For information on using the R or N protocol to disable or enable read line recall for a device,see Terminal I/O in <strong>Caché</strong> I/O Device Guide.See Also• $ZUTIL(68,11) Read Line Recall Mode Process Switch function• Terminal I/O in <strong>Caché</strong> I/O Device Guide$ZUTIL(69,13)$ZUTIL(69,13)Sets logging of asynchronous SET/KILL errors.$ZUTIL(69,13,n)$ZU(69,13,n)ParametersnThe boolean value that specifies whether to log asynchronous SET/KILL errors inMNETERR.LOG.Description$ZUTIL(69,13) controls whether <strong>Caché</strong> sends network transmission errors that occur duringa remote, asynchronous SET or KILL request to the file MNETERR.LOG in the systemmanager's namespace.The corresponding $ZUTIL(69,14) function controls whether <strong>Caché</strong> sends these errors tothe operator console.Invoking $ZUTIL(69,13) without specifying n returns the current switch setting.Setting $ZUTIL(69,13) overrides the default system-wide; it does not change the systemconfiguration setting. This configuration default cannot be changed using the System ManagementPortal.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 649


System and Other FunctionsParametersnThe switch that controls where <strong>Caché</strong> sends transmission errors. 0 = Disables writing transmissionerrors to MNETERR.LOG. 1 = Enables writing transmission errors to MNETERR.LOG.This setting applies only to DCP networks.The native default for this switch is 0 (OFF). You cannot control this switch on a processlevel; that is, there is no equivalent $ZUTIL(68) call.See Also• ZSYNC command• $ZUTIL(69,14) Send Asynchronous Errors to Operator Console function• $ZUTIL(68,34) Process Interruptible by Asynchronous Errors function• $ZUTIL(69,34) Processes Interruptible by Asynchronous Errors function$ZUTIL(69,14)Sets sending of asynchronous SET/KILL errors to operator console.$ZUTIL(69,14,n)$ZU(69,14,n)ParametersnThe boolean value that specifies whether to send asynchronous SET/KILL errorsto the operator console.Description$ZUTIL(69,14) controls whether <strong>Caché</strong> sends network transmission errors that occur duringa remote asynchronous SET or KILL request to the operator's console.The corresponding $ZUTIL(69,13) function controls whether <strong>Caché</strong> logs these errors inMNETERR.LOG.Invoking $ZUTIL(69,14) without specifying n returns the current switch setting.650 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


Setting $ZUTIL(69,14) overrides the default system-wide; it does not change the systemconfiguration setting. This configuration default cannot be changed using the System ManagementPortal.ParametersnThe switch that controls where <strong>Caché</strong> sends transmission errors: 0 = Disable writing transmissionerrors to the console. 1 = Enables writing transmission errors to the console. When 1,<strong>Caché</strong> sends asynchronous network error notification to any operator logged in. When 0, nonotification is sent. This setting applies only to DCP networks.The native default for this switch is off (0); that is, to disable writing of asynchronousSET/KILL errors to the operator console. You cannot control this switch on a process level1; that is, there is no equivalent $ZUTIL(68) call.See Also• ZSYNC command• $ZUTIL(69,13) Log Asynchronous Errors to MNETERR.LOG function• $ZUTIL(68,34) Process Interruptible by Asynchronous Errors function• $ZUTIL(69,34) Processes Interruptible by Asynchronous Errors function$ZUTIL(69,15)$ZUTIL(69,15)Sets I/O device disconnect detection system-wide.$ZUTIL(69,15,n)$ZU(69,15,n)ParametersnThe boolean value that specifies whether <strong>Caché</strong> detects I/O device disconnection.Description$ZUTIL(69,15) controls whether <strong>Caché</strong> detects device disconnection for certain types ofTCP and terminal devices. This setting specifies how <strong>Caché</strong> responds to a disconnect of the<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 651


System and Other Functionsprincipal I/O device. Error on disconnect behavior depends on the settings of both$ZUTIL(69,15) and $ZUTIL(69,60):• If $ZUTIL(69,15,0) and $ZUTIL(69,60,0) the process exits without reporting an errorto the application when a disconnect is detected. The default for both functions is 0.• If $ZUTIL(69,15,1) and $ZUTIL(69,60,0) the process receives a error whena disconnect is detected during a <strong>Caché</strong> <strong>ObjectScript</strong> READ or WRITE command tothe device.• If $ZUTIL(69,15,1) and $ZUTIL(69,60,1) the process receives a errorimmediately when the terminal is disconnected.You should be aware that when error on disconnect is enabled, a process continues to executeafter its principal device has been disconnected. It is the responsibility of the application todetect the disconnect condition and exit gracefully. Use care when enabling error on disconnect.The application must be prepared to recognize the error and handle it appropriatelyin error traps.Error on disconnect is only applicable to TCP devices and to terminal devices where a disconnectcan be recognized. Examples are modem controlled terminals and Windows Telnet,Windows LAT, and Windows local cterm (TRM:) connections. Error on disconnect is onlyapplicable to the principal device.This error on disconnect option can be set for the current process by calling $ZUTIL(68,15).ParametersnThe switch that controls whether <strong>Caché</strong> detects I/O device disconnection. 0 = Disables systemwidedisconnect detection. 1 = Enables system-wide disconnect detection.System-wide, disconnect detection is disabled by default. $ZUTIL(69,15) returns the currentsystem-wide setting without changing it. $ZUTIL(69,15,n) sets this option.This system-wide default can be configured. Go to the System Management Portal, selectConfiguration, then select Advanced Settings. On the pull-down Category list select Terminal.View and edit the current setting of ErrorOnDisconnect. When 1 (true), <strong>Caché</strong> issues a error when a disconnect is detected during a <strong>Caché</strong> <strong>ObjectScript</strong> READ or WRITEcommand to the device (equivalent to $ZUTIL(69,15,1) / $ZUTIL(69,60,0)). If 0 (false),no error is issued when a disconnect is detected. The default is 0.Setting $ZUTIL(69,15) changes the system configuration setting shown in the SystemManagement Portal; this change persists across a <strong>Caché</strong> shutdown and restart.652 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


See Also$ZUTIL(69,19)• $ZUTIL(68,15) I/O Device Disconnect Detection function• $ZUTIL(69,60) Asynchronous Telnet disconnect error handling system-wide function$ZUTIL(69,19)Sets DDP password security system-wide.$ZUTIL(69,19,n)$ZU(69,19,n)ParametersnA boolean value that specifies whether to enable or disable password protection forDDP connections.DescriptionYou can use $ZUTIL(69,19) to set password protection for DDP (Distributed Data Processing)network connections system-wide. Setting $ZUTIL(69,19) overrides this default systemwide;it does not change the System Configuration setting.Invoking $ZUTIL(69,19) without specifying n returns the current switch setting.This configuration default cannot be changed using the System Management Portal.ParametersnThe boolean switch that determines the system-wide default mode for DDP password security:0 = DDP connections do not need a password to connect to <strong>Caché</strong>. 1 = DDP connectionsmust use a password to connect to <strong>Caché</strong>.In order for a setting of 1 to work, you must obtain the routine ^DDPSEC from the <strong>InterSystems</strong>Worldwide Response Center.See Also•<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 653


System and Other Functions$ZUTIL(69,20)Transfers global nodes with null subscripts with DSM-DDP.$ZUTIL(69,20,n)$ZU(69,20,n)ParametersnThe boolean value that specifies whether the network allows null subscripts.DescriptionWith Open M [DSM]-DDP networking, you can transfer global nodes that include null subscripts.$ZUTIL(69,20) controls this ability system-wide.When enabled (n=1), <strong>Caché</strong> can read and write global data with null subscripts across a networkconnection. When disabled (n=0), all data with null subscripts is effectively invisible,and all references to such data generate errors. The default is disabled (0).This setting only applies to DCP networks. On ECP, null subscripts are always allowed overthe network.Invoking $ZUTIL(69,20) without specifying n returns the current switch setting.Setting $ZUTIL(69,20) overrides the default system-wide; it does not change the systemconfiguration setting. This configuration default cannot be changed using the System ManagementPortal.ParametersnThe switch that controls whether <strong>Caché</strong> can transfer null-subscripted global nodes throughOpen M [DSM]-DDP. 0 = Disables system-wide transfer of null-subscript nodes. 1 = Enablessystem-wide transfer of null-subscripted nodes.By default, the ability to transfer null-subscripted globals is disabled. You cannot control thisswitch on a process level.For further details on subscripted globals, see Global Structure in Using <strong>Caché</strong> Multi-Dimensional Storage.654 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


See Also$ZUTIL(69,21)• $ZUTIL(68,1) Enable or disable use of null subscripts for the current process. function• $ZUTIL(69,1) Enable or disable use of null subscripts system-wide function$ZUTIL(69,21)Sets synchronous commit mode system-wide.$ZUTIL(69,21,n)$ZU(69,21,n)ParametersnA boolean value that specifies whether or not synchronous transaction commit modeis enabled system-wide.DescriptionYou can use $ZUTIL(69,21) to set the synchronous transaction commit mode system-wide.This enables or disables synchronizing TCOMMIT with the corresponding journal writeoperation. Every TCOMMIT command requests a flush of the journal data involved in thattransaction to disk. When $ZUTIL(69,21) is enabled (set to 1) a TCOMMIT does notcomplete until the journal data write operation completes. When set to 0, TCOMMIT doesnot wait for the write operation to complete. Setting $ZUTIL(69,21) changes the systemconfiguration setting and is persistent across <strong>Caché</strong> shutdowns and startups.Invoking $ZUTIL(69,21) without specifying n returns the current switch setting.This system configuration setting can also be changed using the System Management Portal.Select Configuration, then select Advanced Settings. On the pull-down Category list selectTransactions. View and edit the current setting of SynchronousCommit. The default is “false”.You can also disable or enable this mode on a per-process basis. See $ZUTIL(68,21).ParametersnThe boolean switch that determines the system-wide default mode for synchronous transactioncommit: 0 = TCOMMIT completion does not wait for journal file write completion. 1 =<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 655


System and Other FunctionsTCOMMIT completion waits for the journal file write operation to complete. The defaultis 0.See Also• TCOMMIT command• $ZUTIL(68,21) Set synchronous commit mode for the current process function$ZUTIL(69,22)Sets $X update mode for escape sequences system-wide.$ZUTIL(69,22,n)$ZU(69,22,n)ParametersnA numeric code that specifies the $X update mode. Select the value that correspondsto your system platform.DescriptionYou can control the way <strong>Caché</strong> updates $X when writing a string containing an escapesequence. Default behaviors for various <strong>Caché</strong> implementations are as follows:• UNIX parses the ANSI standard escape sequence and counts the rest of the non-escapecharacters in the string against $X.• VAX and Alpha do not count any more characters in the string against $X as soon asthey encounter an escape character ($CHAR(27)).• Open M [DSM] mode counts all characters in a string, including the escape character,against $X.• Open M [DTM] and Open M [MSM] count all characters except for the escape characteragainst $X.$ZUTIL(69,22,n) controls this ability system wide.Invoking $ZUTIL(69,22) without specifying n returns the current switch setting.656 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


ParametersnA numeric code that controls a non-default, consistent, system-wide way of updating $X. 0= Use UNIX default behavior on system. 1 = Use Open M [DSM] default behavior on system.2 = Use Open M [DTM]/Open M [MSM] default behavior on system. 3 = Use OpenVMSAlpha default behavior on system. The default behavior on UNIX is for n to be zero (0). Thedefault behavior on VAX or Alpha for n is three (3).NotesTo be counted correctly, the entire escape sequence must be a single string. For example, thefollowing is one string and is therefore recognized as an escape sequence:WRITE $CHAR(27)_"[0m"However, the following is two strings and is therefore not recognized as an escape sequence:WRITE $CHAR(27),"[0m"See Also• $ZUTIL(68,22) $X Update Mode for Escape Sequences function• $X special variable$ZUTIL(69,24)$ZUTIL(69,24)Sets $ZF process deletion behavior for OpenVMS STOP/ID system-wide.$ZUTIL(69,24,n)$ZU(69,24,n)ParametersnThe switch that controls whether <strong>Caché</strong> can delete a process that is executing auser-written $ZF function. 0 = Enable deletion of <strong>Caché</strong> processes with STOP/ID.1 = Disable deletion of <strong>Caché</strong> processes with STOP/ID.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 657


System and Other FunctionsDescriptionUsing the OpenVMS STOP/ID command to delete a <strong>Caché</strong> process can cause your systemto fail. For this reason, <strong>Caché</strong> on OpenVMS systems prevent you from deleting <strong>Caché</strong> processeswith STOP/ID.For processes that are executing $ZF functions, you may need to be able to delete a <strong>Caché</strong>process from OpenVMS. Some users of VMS use a form of the VIEW command to makessuch processes deletable.$ZUTIL(69,24,n) gives you the same ability on all OpenVMS systems.$ZUTIL(69,24,1) is enabled automatically at startup. That is, by default, you cannot delete<strong>Caché</strong> processes using STOP/ID.Invoking $ZUTIL(69,24) without specifying n returns the current switch setting.Setting $ZUTIL(69,24) overrides the default system-wide; it does not change the systemconfiguration setting. This configuration default cannot be changed using the System ManagementPortal.Notes$ZUTIL(69,24,n) affects only user-written $ZF functions. You cannot use STOP/ID to deleteprocesses executing $ZF(-1) regardless of the state of $ZUTIL(69,24).When you use STOP/ID to delete a process executing $ZF, a "ghost process" appears in the%SS listing. This ghost process cannot cause the system to hang.$ZUTIL(69,26)Sets namespace display in programmer prompt system-wide.$ZUTIL(69,26,n)$ZU(69,26,n)ParametersnThe boolean value that specifies whether to display the namespace name at theterminal prompt.658 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


Description<strong>Caché</strong> allows you to display the current namespace name for your process in the <strong>Caché</strong> Terminalprompt. (This setting also controls the display of the current namespace name in Telnetwindows.) You control whether the current namespace is displayed, by default, as part of theprompt for all processes on the system when you establish a configuration with the SystemManagement Portal, or a %ZSTART (or ZSTU) user-defined system configuration routine.You can also use $ZUTIL(69,26,n) to change whether the system displays the currentnamespace as a default for all processes at some point after system startup.Invoking $ZUTIL(69,26) without specifying n returns the current switch setting.You can set various values, including the current namespace, as the terminal prompt for thecurrent process using $ZUTIL(186).<strong>Caché</strong> maintains the name of the current namespace in the $ZNSPACE special variable. Thecurrent namespace can be an explicit namespace or an implied namespace.ParametersnA boolean switch that determines whether <strong>Caché</strong> by default displays the current namespaceat the terminal prompt for all processes on the system. 0 = Do not display the currentnamespace name. 1 = Display the current namespace name (the default).Issuing $ZUTIL(69,26,1) sets the switch. Issuing $ZUTIL(69,26,0) clears the switch.Notes$ZUTIL(69,26)This system-wide default is configurable. Go to the System Management Portal, select SystemConfiguration, select Advanced Settings, on the pull-down Category list select <strong>ObjectScript</strong>.View and edit the current setting of PromptShowsNamespace.Setting $ZUTIL(69,26) changes the system configuration setting shown in the SystemManagement Portal; this change persists across a <strong>Caché</strong> shutdown and restart.Any change you make with $ZUTIL(69,26) affects only processes that log in after you issue$ZUTIL(69,26). That is, if you issue $ZUTIL(69,26,0), only processes that subsequentlylog in do not display their current namespace. Processes that logged in before you issued$ZUTIL(69,26) still display their current namespace in the programmer-mode prompt.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 659


System and Other FunctionsSee Also• $ZUTIL(68,26) Set Terminal Prompt Display of Current Namespace for the CurrentProcess function• $ZUTIL(186) Set Terminal Prompt Display Values for the Current Process function• ZNSPACE command• $ZNSPACE special variable$ZUTIL(69,27)Enables or disables network hardening system-wide.$ZUTIL(69,27,n)$ZU(69,27,n)ParametersnThe boolean value that specifies whether to enable network hardening system-wide.DescriptionYou can use $ZUTIL(69,27) to enable or disable system-wide network hardening.Invoking $ZUTIL(69,27) without specifying n returns the current switch setting.<strong>Caché</strong> provides network hardening to allow user jobs to continue processing in the event ofnetwork transport errors. Network hardening allows global references to remote servers tocomplete successfully even if network transport errors occur.When a network transport error occurs, the network transport code re-establishes connectionsand retransmits network requests. Where the user or application must take some action torestore communications, the client process receives a specific error.This configuration default cannot be changed using the System Management Portal.Note:This function provide network hardening support for DCP (Distributed Cache Protocol)distributed data management. It does not provide support for ECP (EnterpriseCache Protocol) distributed data management.DCP (Distributed Cache Protocol) with network hardening performs multiple retries of anetwork request. ECP (Enterprise Cache Protocol) does not support network hardening and660 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


does not perform multiple retries. ECP issues a error when encountering anetwork transport error; the suggested programming practice is to roll back the currenttransaction when encountering a error, then retry the transaction. At <strong>Caché</strong>version 5.0 and subsequent, the default for distributed data caching is ECP. For further details,see Introduction and DCP in the Distributed Data Management Guide.ParametersnA switch that determines whether <strong>Caché</strong> by default enables or disables network hardeningfor the system. 0 = Disable network hardening. 1 = Enable network hardening. The defaultis 1.See Also$ZUTIL(69,28)• $ZUTIL(68,27) Enable/Disable Network Hardening for the Current Process function$ZUTIL(69,28)Controls root-level (unsubscripted) global node kills system-wide.$ZUTIL(69,28,n)$ZU(69,28,n)ParametersnThe boolean value that specifies whether <strong>Caché</strong> allows the processes to kill root-levelglobal nodes system-wide.DescriptionSetting $ZUTIL(69,28) allows you to control whether processes on your system can killroot-level (unsubscripted) global nodes.Invoking $ZUTIL(69,28) without specifying n returns the current switch setting.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 661


System and Other FunctionsParametersnA boolean switch that determines whether <strong>Caché</strong> allows the processes to kill root-level globalnodes: 0 = Root-level global node kills are allowed. 1 = Root-level global node kills are notallowed.The default for the system is zero (0). This means that killing a root-level node does notgenerate an error. For example, you can execute the following without an error:KILL ^aYou can determine the current state of the switch by issuing $ZUTIL(69,28). You can setthe switch for the system so that root-level global node kills are not allowed by issuing$ZUTIL(69,28,1). After you set the switch, any attempt to kill a root-level node generatesa error. For details on error format, refer to the $ZERRORspecial variable.NotesThis configuration default cannot be changed using the System Management Portal.Setting $ZUTIL(69,28) overrides the System Configuration default; it does not change thedefault setting.Any change you make with $ZUTIL(69,28) affects only processes that log in after you issue$ZUTIL(69,28). That is, if you issue $ZUTIL(69,28,1), only processes that log in after thefunction call was issued generate errors when attempts are made to kill rootlevelnodes. Processes that logged in before you issued $ZUTIL(69,28) can still kill rootlevelnodes.You can also disable or enable this mode on a per-job and per-device basis. For informationon setting this for a job, see $ZUTIL(68,28) Control Root (Unsubscripted) Node Kills.For further details on subscripted global nodes, see Global Structure in Using <strong>Caché</strong> Multi-Dimensional Storage.See Also• $ZUTIL(68,28) Control Root (Unsubscripted) Node Kills function• KILL command662 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(69,30)$ZUTIL(69,30)Sets error handling behavior system-wide.$ZUTIL(69,30,n)$ZU(69,30,n)ParametersnThe boolean value that specifies the system-wide default mode for error handlingbehavior.DescriptionUse $ZUTIL(69,30) to select either <strong>Caché</strong> error handling behavior, or DSM error handlingbehavior system-wide.When an error handler is invoked in <strong>Caché</strong>, that error handler remains on the stack of establishederror handlers. Therefore, if an error occurs when the error handler is executing, thaterror handler attempts to invoke itself, receives the same error again and enters an infiniteloop, unless that error handler explicitly sets $ZTRAP to a new value.When an error handler is invoked in DSM, the error handler is unwound from the stack.Therefore, if an error occurs while the error handler is executing, that error is handled by theprevious error handler on the stack.Invoking $ZUTIL(69,30) without specifying n returns the current switch setting.This error-handling option can be set for the current process by calling $ZUTIL(68,30).ParametersnA boolean switch that determines your system's error-handling behavior: 1 = Use Open M[DSM] error-handling behavior. 0 = Use <strong>Caché</strong> error-handling behavior. The default is <strong>Caché</strong>behavior.This configuration default cannot be changed using the System Management Portal. Setting$ZUTIL(69,30) overrides the system configuration default; it does not change the defaultsetting.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 663


System and Other FunctionsSee Also• $ZUTIL(68,30) Sets Error-Handling Behavior for the Current Process function• ZQUIT command• $ZTRAP special variable• Error Handling in Using <strong>Caché</strong> <strong>ObjectScript</strong>$ZUTIL(69,31)Sets network locks handling system-wide following a DCP outage.$ZUTIL(69,31,n)$ZU(69,31,n)ParametersnA boolean value that specifies whether or not to reinstate network locks when thenetwork returns after a DCP outage.DescriptionYou can use $ZUTIL(69,31) to set the system-wide handling of network locks when thenetwork returns after a DCP (Distributed Cache Protocol) outage. Setting $ZUTIL(69,31)overrides the default system-wide; it does not change the system configuration setting.Invoking $ZUTIL(69,31) without specifying n returns the current switch setting.The configuration default cannot be changed using the System Management Portal.ParametersnThe boolean switch that determines the system-wide default mode for reinstating networklocks: 0 = <strong>Caché</strong> network hardening attempts to reinstate the locks after a DCP outage. 1 =<strong>Caché</strong> “drops” (does not reinstate) network locks when the network returns after a DCP outage.The default is 0.See Also• Distributed Cache Protocol (DCP) in the <strong>Caché</strong> Distributed Data Management Guide.664 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(69,32)$ZUTIL(69,32)Sets date range and invalid date behavior system-wide.$ZUTIL(69,32,n)$ZU(69,32,n)ParametersnThe boolean value that specifies whether or not to use <strong>Caché</strong>-style date behaviorsystem-wide.Description$ZUTIL(69,32) performs two functions:• It sets the range of valid dates for $ZDATE. This provides compatibility with either<strong>Caché</strong> or ISM.• It sets the behavior of $ZDATE when an invalid date is input.$ZUTIL(69,32) only affects the behavior of $ZDATE; the other date and time functions areunaffected.Invoking $ZUTIL(69,32) without specifying n returns the current switch setting.ParametersnA switch that sets which date range to use. 0= Enables the standard <strong>Caché</strong> range of validdates (default). 1 = Enables ISM-compatible range of valid dates.NotesSetting the Range of Valid Dates$ZUTIL(69,32,0) sets the range of valid dates for <strong>Caché</strong>. This range is from 0 through2980013, inclusive, which corresponds to dates from 12/31/1840 through 12/31/9999. Thisrange can be restricted by setting the $ZDATE mindate and maxdate parameters.$ZUTIL(69,32,1) sets the range of valid dates for ISM compatibility. This range is from 1through 94232, inclusive, which corresponds to dates from 01/01/1841 through 12/30/2098.This date range is set for any $ZDATE function call which has three or fewer parameters. If<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 665


System and Other Functionsa $ZDATE function call has more than three parameters, the valid date range is taken eitherfrom the $ZDATE mindate and maxdate parameters (if specified) or from the date rangeestablished for the current locale.The default setting of $ZUTIL(69,32) is 0 for all <strong>Caché</strong> products, and 1 for all ISM products.Setting the Behavior for Invalid DatesAn invalid date is either not a positive integer, or is not a value within the range of valid dates,as specified above.$ZUTIL(69,32,0) causes $ZDATE to issue the error message or if you submit an invalid date. The behavior can be overriddenby supplying an erropt to the $ZDATE call.$ZUTIL(69,32,1) causes $ZDATE to return the null string if you submit an invalid date.This behavior is set for any $ZDATE function call, regardless of the number of parameters.This configuration default cannot be changed using the System Management Portal.Setting $ZUTIL(69,32) overrides the System Configuration default; it does not change thedefault setting.Calling $ZUTIL(69,32)When you create a new process, its $ZDATE behavior is initialized from the current SystemConfiguration default and $ZUTIL(69,32). Calling $ZUTIL(68,32) overrides this behaviorfor the current process. Changing the setting of $ZUTIL(69,32) affects only processes subsequentlycreated, not existing processes.See Also• $ZDATE function• $ZUTIL(68,32) Set Date Range and Invalid Date Behavior function• More information on locales in Customized National Language Translations666 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(69,34)$ZUTIL(69,34)Sets interruptability of processes by asynchronous errors system-wide.$ZUTIL(69,34,n)$ZU(69,34,n)ParametersnThe boolean value that specifies whether or not processes should be interrupted byreceiving asynchronous errors system-wide.Description$ZUTIL(69,34) allows you to set a system-wide switch that specifies whether all processesthat log on after the switch has been set can be interrupted by asynchronous errors. Theseasynchronous errors are documented in Transaction Processing in Using <strong>Caché</strong> <strong>ObjectScript</strong>.Invoking $ZUTIL(69,34) without specifying n returns the current switch setting.Setting $ZUTIL(69,34) overrides the default system-wide; it does not change the systemconfiguration setting. This configuration default cannot be changed using the System ManagementPortal.ParametersnA switch that determines whether all new processes can be interrupted by asynchronouserrors. 1 = Enables the reception of asynchronous errors (default); disconnect errors are sentasynchronously to the process. 0 = Disables the reception of asynchronous errors; the processonly gets the error when it enters the READ command.For this setting to be effective, modem disconnect detection must also be set. See$ZUTIL(69,15) — Modem Disconnect Detection System Default.NotesIf multiple asynchronous errors are detected for a particular job, the system will trigger atleast one asynchronous error. However, there is no guarantee what error will be triggered.Even if a process has disabled reception of asynchronous errors, an asynchronous error willbe triggered the next time the process issues a ZSYNC command.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 667


System and Other FunctionsSee Also• ZSYNC command• $ZUTIL(68,34) Process Interruptible by Asynchronous Errors function$ZUTIL(69,35)Sets silent retry for domainspace connection attempts system-wide.$ZUTIL(69,35,n)$ZU(69,35,n)ParametersnA boolean value that specifies whether or not to perform a silent retry for domainspaceconnection attempts.DescriptionYou can use $ZUTIL(69,35) to set domainspace connection attempt behavior system-wide.When enabled, a failed domainspace connection attempt is automatically retried withoutissuing an error (a “silent” retry). When disabled, a failed domainspace connection attemptis automatically retried, but an error message is issued.The default is to issue the error message. Setting $ZUTIL(69,35) overrides this default systemwide;it does not change the system configuration setting.Invoking $ZUTIL(69,35) without specifying n returns the current switch setting.This configuration setting cannot be changed using the System Management Portal.ParametersnThe boolean switch that determines the system-wide default mode for domainspace connectionattempt retry behavior: 0 = <strong>Caché</strong> returns an error to the user process but continues the attemptto reconnect to the domainspace. 1 = <strong>Caché</strong> automatically continues to attempt connectionto a domainspace until it is successful, without returning an error to the user process duringthe reconnection attempt(s).668 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


See Also•$ZUTIL(69,37)$ZUTIL(69,37)Sets physical cursor mode system-wide.$ZUTIL(69,37,n)$ZU(69,37,n)ParametersnA boolean value that specifies whether or not physical cursor positioning mode isenabled system-wide.DescriptionYou can use $ZUTIL(69,37) to set the physical cursor positioning mode system-wide. Thissetting accommodates character sets that use two physical spaces for a character, by determininghow <strong>Caché</strong> backspaces over characters. When enabled, <strong>Caché</strong> examines a character tosee if it occupies two physical positions on the device, and if so, writes two backspaces andtwo space characters. By default, <strong>Caché</strong> writes one backspace and one space character.Setting $ZUTIL(69,37) changes the system configuration setting and is persistent across<strong>Caché</strong> shutdowns and startups.Invoking $ZUTIL(69,37) without specifying n returns the current switch setting.This system configuration setting can also be changed using the System Management Portal.Select Configuration, then select Advanced Settings. On the pull-down Category list select<strong>ObjectScript</strong>. View and edit the current setting of PhysicalCursor. The default is “false” .ParametersnThe boolean switch that determines the system-wide default mode for physical cursor positioning:0 = space and backspace characters take one physical position. 1 = <strong>Caché</strong> examineseach space or backspace character to see if it occupies two physical positions on the device;if so, <strong>Caché</strong> writes two backspaces and two space characters.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 669


System and Other FunctionsSee Also• $X special variable• $Y special variable$ZUTIL(69,39)Sets caching for future processes system-wide.$ZUTIL(69,39,n)$ZU(69,39,n)ParametersnThe boolean value that specifies whether or not a process has caching enabled.Note that settings are: 0 = caching enabled. 1 = caching disabled.DescriptionUse $ZUTIL(69,39) to disable or enable client server caching system-wide for any futureprocess. When caching is enabled, <strong>Caché</strong> will cache data for quicker retrieval.Invoking $ZUTIL(69,39) without specifying n returns the current switch setting.ParametersnThe boolean switch that determines whether caching is disabled. 0 = caching enabled. 1 =caching disabled. Note that these boolean values are the opposite of those found in SystemConfiguration.Caching enabled (0) is the default setting for the switch. This configuration default cannotbe changed using the System Management Portal.Setting $ZUTIL(69,39) overrides this default system-wide; it does not change the SystemConfiguration setting. Setting $ZUTIL(68,39) overrides the system-wide setting for thecurrent process.See Also• $ZUTIL(68,39) Disable or Enable Caching function670 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(69,40)$ZUTIL(69,40)Sets end-of-file handling for sequential files system-wide.$ZUTIL(69,40,n)$ZU(69,40,n)ParametersnThe boolean value that sets end-of-file handling system-wide. 0=<strong>Caché</strong> format.1=MSM format.DescriptionThe $ZUTIL(69,40) function specifies end-of-file flagging format system-wide. This functionis provided to support the porting of MSM routines that use $ZCYC to check for end of fileon sequential file reads.$ZUTIL(69,40,1) eliminates the error for sequential files system-wide.Instead, when the end of a file is reached, the READ command returns a null string, the$ZPOS special variable is set to "" (the null string), and the $ZEOF special variable is setto -1.Invoking $ZUTIL(69,40) without specifying n returns the current switch setting.ParametersnThe switch that determines whether end-of-files are flagged: 0 = End-of-files are flagged instandard <strong>Caché</strong> format. 1 = End-of-files are flagged in MSM format.$ZUTIL(69,40,0) is the default setting for the switch. This option controls the behavior when<strong>Caché</strong> encounters an unexpected end-of-file when reading a sequential file. When set to 1,<strong>Caché</strong> sets the $ZEOF special variable to indicate that you have reached the end of the file.When set to 0, <strong>Caché</strong> issues an error. The default is 0.This configuration default cannot be changed using the System Management Portal.Setting $ZUTIL(69,40) overrides this default system-wide; it does not change the SystemConfiguration setting. Setting $ZUTIL(68,40) overrides the system-wide setting for thecurrent process.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 671


System and Other FunctionsSee Also• $ZUTIL(68,40) End-of-File Handling for Sequential Files function• READ command• $ZEOF special variable• $ZPOS special variable• Sequential File I/O in <strong>Caché</strong> I/O Device Guide$ZUTIL(69,42)Sets $JOB format default system-wide.$ZUTIL(69,42,n)$ZU(69,42,n)ParametersnThe boolean value that specifies whether or not to use the standard $JOB returnstring system-wide.Description$ZUTIL(69,42,1) permits the $JOB special variable to return a string of the formatprocessid:nodename for all processes system-wide. This function provides for a unique valuefor $JOB on networked systems. This is useful when using $JOB to index globals accessedby more than one networked system.Invoking $ZUTIL(69,42) without specifying n returns the current switch setting.ParametersnThe switch that determines the $JOB returned string format. 0 = Standard $JOB format. 1= Format the returned string as processid:nodename. The nodename is set using $ZUTIL(131).$ZUTIL(69,42,0) is the default setting for the switch.This configuration default cannot be changed using the System Management Portal.672 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


Setting $ZUTIL(69,42) overrides the System Configuration default; it does not change thedefault setting.See Also• $ZUTIL(68,42) $JOB Format for Process function• $ZUTIL(131) Set and Get the System Name and IP Address function• $JOB special variable$ZUTIL(69,43)$ZUTIL(69,43)Sets clearing of global vectors system-wide.$ZUTIL(69,43,n)$ZU(69,43,n)ParametersnThe boolean value that specifies whether or not $ZUTIL(5) clears global vectors forthe current process.Description$ZUTIL(69,43,1) enables the clearing of global vectors system-wide when $ZUTIL(5) isissued with the current namespace. This function provides compatibility with $ZUTIL(5)behavior prior to <strong>Caché</strong> version 3.1.When enabled, $ZUTIL(5) changes to a different namespace and resets the information in$ZUTIL(39). When not enabled, $ZUTIL(5) changes to a new namespace, but does notreset $ZUTIL(39).Invoking $ZUTIL(69,43) without specifying n returns the current switch setting.ParametersnThe switch that determines whether global vectors are cleared. 0 = Do not clear global vectors.1 = Clear global vectors ($ZUTIL(5) behaves as it did prior to <strong>Caché</strong> version 3.1).$ZUTIL(69,43,0) is the default setting for the switch.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 673


System and Other FunctionsThis configuration default cannot be changed using the System Management Portal.Setting $ZUTIL(69,43) overrides the System Configuration default; it does not change thedefault setting.See Also• $ZUTIL(5) Display or Switch Namespace function• $ZUTIL(68,43) Sets Clearing of Global Vectors for the Current Process function$ZUTIL(69,44)Sets use of the Nagle algorithm for Telnet transmissions system-wide.$ZUTIL(69,44,n)$ZU(69,44,n)ParametersnA boolean value that specifies whether or not the Nagle algorithm is enabled.DescriptionYou can use $ZUTIL(69,44) to set the use of the Nagle algorithm system-wide. The Naglealgorithm makes Telnet more efficient. It reduces the number of IP packets sent over thenetwork by consolidating messages that are sent within a small time interval into a single IPpacket. When the Nagle algorithm is enabled, the operating system waits some interval beforeactually committing the data from a send command, in the hopes that the application will callsend again with more data that can be consolidated with the first.Setting $ZUTIL(69,44) changes the system configuration setting and is persistent across<strong>Caché</strong> shutdowns and startups. This configuration setting cannot be changed using the SystemManagement Portal.Invoking $ZUTIL(69,44) without specifying n returns the current switch setting.ParametersnThe boolean switch that determines the system-wide default mode for use of the NagleAlgorithm: 0 = Nagle algorithm disabled. 1 = Nagle algorithm enabled. The default is 0.674 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


See Also•$ZUTIL(69,45)$ZUTIL(69,45)Truncates numbers during string-to-number conversion system-wide.$ZUTIL(69,45,n)$ZU(69,45,n)ParametersnThe boolean value that specifies whether or not to truncate numbers system-wide.DescriptionNormally, when <strong>Caché</strong> encounters a number larger than 9223372036854775807 E127 (orsmaller than -9223372036854775808 E127) it issues a error.$ZUTIL(69,45,n) turns off the error during string-to-number conversions.Instead, truncate the exponent to the biggest valid number and continue conversion. Thisfunction only prevents errors during string-to-number conversions. A error can still occur during arithmetic operations.This function is provided for MSM compatibility. Specifying $ZUTIL(55,8) to set MSMlanguage mode automatically sets $ZUTIL(69,45).Invoking $ZUTIL(69,45) without specifyingn returns the current switch setting.ParametersnThe switch that determines whether number truncation occurs. 0 = Do not truncate largenumbers; issue a error. 1 = During string-to-number conversion, truncatelarge numbers and suppress errors.$ZUTIL(69,45,0) is the default setting for the switch in all language modes except MSMmode. This configuration default cannot be changed using the System Management Portal.Setting $ZUTIL(69,45) overrides the System Configuration default; it does not change theconfiguration setting.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 675


System and Other FunctionsSee Also• $ZUTIL(55) Language Mode Switch function• $ZUTIL(68,45) Truncate Numbers During String-to-Number Conversion for the CurrentProcess function$ZUTIL(69,49)Sets logging of transaction rollbacks system-wide.$ZUTIL(69,49,n)$ZU(69,49,n)ParametersnA boolean value that specifies whether or not to log transaction rollbacks.DescriptionYou can use $ZUTIL(69,49) to set logging of transaction rollbacks system-wide. Whenenabled, <strong>Caché</strong> logs transaction rollbacks to the console log file: cconsole.log in the <strong>Caché</strong>system management directory (Mgr), or to an alternate filename.log named by the secondpiece of the console parameter.This default console log file location is configurable. Go to the System Management Portal,select Configuration, then select Advanced Settings. On the pull-down Category list selectMiscellaneous. View and edit the current setting of ConsoleFile. By default this setting isblank, routing console messages to cconsole.log. If you change this setting, you must restart<strong>Caché</strong> for this change to take effect.The default is to not log transaction rollbacks. Setting $ZUTIL(69,49) overrides this defaultsystem-wide; it does not change the system configuration setting.Invoking $ZUTIL(69,49) without specifying n returns the current switch setting.The configuration default cannot be changed using the System Management Portal.676 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


ParametersnThe boolean switch that determines the system-wide default mode for transaction rollbacklogging: 0 = rollback logging disabled. 1 = rollback logging enabled. The default is 0.See Also• TROLLBACK command$ZUTIL(69,51)$ZUTIL(69,51)Sets namespace default directory assignment behavior system-wide.$ZUTIL(69,51,n)$ZU(69,51,n)ParametersnThe boolean value that specifies whether or not changing the namespace alsochanges the default directory.Description$ZUTIL(69,51) allows you to specify whether changing your namespace should also changethe default directory. Normally, when you change to a different namespace, <strong>Caché</strong> changesthe directory at the operating system level to the default directory for that namespace. Thisfunction allows you to change the namespace without changing the directory.Invoking $ZUTIL(69,51) without specifying n returns the current switch setting.ParametersnThe switch that determines the default behavior when changing namespaces. 0 = Changingthe namespace automatically changes the default directory to the directory for that namespace.1 = Changing the namespace does not change the default directory. The system default is 0.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 677


System and Other FunctionsNotes$ZUTIL(69,51) sets this behavior on a system-wide basis. You can set this behavior for thecurrent process by calling $ZUTIL(68,51).The system-wide default behavior is configurable. Go to the System Management Portal,select System Configuration, select Advanced Settings, on the pull-down Category list select<strong>ObjectScript</strong>. View and edit the current setting of SwitchOSDirectory. The default is “false”.Setting $ZUTIL(69,51) changes the system configuration setting shown in the SystemManagement Portal; this change persists across a <strong>Caché</strong> shutdown and restart.Call $ZUTIL(168) to explicitly set the default directory at the operating system level.See Also• $ZUTIL(68,51) Namespace Default Directory Assignment for the Current Processfunction• $ZUTIL(168) Set Current Working Directory function$ZUTIL(69,60)Sets handling of asynchronous Telnet disconnect errors system-wide.$ZUTIL(69,60,n)$ZU(69,60,n)ParametersnA boolean value that specifies whether or not processes receive Telnet disconnecterrors asynchronously.DescriptionYou can use $ZUTIL(69,60) to set asynchronous disconnect error handling system-wide.$ZUTIL(69,60) is only applicable to Telnet connections on Windows. It has no effect onany other device type or operating system.For $ZUTIL(69,60) to be operational, one of the following must be set to enabled (1):678 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


• The System Management Portal Configuration option ErrorOnDisconnect must be set to1 (True). Go to the System Management Portal, select Configuration, then select AdvancedSettings. On the pull-down Category list select Terminal. View and edit the current settingof ErrorOnDisconnect.• $ZUTIL(69,15) must set to 1.• $ZUTIL(68,15) must set to 1 for the current process.The $ZUTIL(69,60) default setting is 0 (disabled). Setting $ZUTIL(69,60,1) overrides thisdefault system-wide; it does not change the System Configuration setting.Invoking $ZUTIL(69,60) without specifying n returns the current switch setting.This configuration setting cannot be changed using the System Management Portal.ParametersnThe boolean switch that determines the system-wide default mode for asynchronous disconnecterrors: 0 = the process receives a error at the next READ or WRITE command.1 = The process receives an asynchronous error immediately when a disconnectoccurs on the device. This error occurs at the next command executed. HANG commandswill be interrupted.See Also• $ZUTIL(68,15) — Modem Disconnect Detection for the Current Process function• $ZUTIL(69,15) — Modem Disconnect Detection System-wide function$ZUTIL(69,60)<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 679


System and Other Functions$ZUTIL(69,63)Enables or disables the use of “e” as an exponent symbol.$ZUTIL(69,63,n)$ZU(69,63,n)ParametersnThe boolean value that specifies whether or not <strong>Caché</strong> should treat lowercase “e”as an exponent symbol. 1 = evaluate “e” as an exponent symbol. 0 = do not evaluate“e” as an exponent symbol. The default is 1.DescriptionThe $ZUTIL(69,63) function disables or enables the evaluation of the lowercase letter “e”as an exponent symbol system-wide. $ZUTIL(69,63) has no effect on the evaluation ofuppercase “E” as an exponent symbol.The system-wide default is to treat both “E” and “e” as exponent symbols. You can use$ZUTIL(69,63) to reset this system-wide default. For details on overriding this system defaultfor an individual process, see $ZUTIL(68,63).Invoking $ZUTIL(69,63) without specifying n returns the current switch setting.See Also• $ZUTIL(68,63) Disable or Enable “e” as Exponent function$ZUTIL(71)Sets date to a fixed value.$ZUTIL(71,date)$ZU(71,date)ParametersdateA positive integer that represents a date in $HOROLOG format.680 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


DescriptionSets the date internally stored by <strong>Caché</strong> in the $HOROLOG special variable to a specifiedfixed value for the current process. Calling $ZUTIL(71,0) restores $HOROLOG to thecurrent date.Using this function to set a fixed value for the date causes all subsequent calls to $HOROLOGfrom that process to return that fixed value as the date. A date set using $ZUTIL(71,date)is a fixed date; it does not increment at midnight. $ZUTIL(71,date) has no effect on the timeportion of $HOROLOG, which continues to represent the current time.Issue $ZUTIL(71) with no date parameter to display the date value set by a prior$ZUTIL(71,date) call. $ZUTIL(71) defaults to 0 (which denotes December 31, 1840.)Issuing $ZUTIL(71) with no date parameter has no effect on $HOROLOG.To restore $HOROLOG to the current date, issue $ZUTIL(71,0) or $ZUTIL(71,""). Thesecalls revert $HOROLOG to the current date, and revert $ZUTIL(71) to 0 (December 31,1840.)$ZUTIL(71,date) returns as its function value the previous setting of date. It returns zero if$HOROLOG was not set to a fixed value, either because you have not called this functionsince your <strong>Caché</strong> process was created, or you have already reset $HOROLOG by calling$ZUTIL(71,0).ParametersdateAn integer that falls between 0 (December 31, 1840) and 2980013 (December 31, 9999)inclusive.Example$ZUTIL(71)The following example shows the relationship between $ZUTIL(71) and $HOROLOG.This example uses the $ZDATETIME function to show that $ZUTIL(71) has no effect onthe time portion of $HOROLOG, and that $ZUTIL(71) does not return a time value. Dateformat 5 is used here because it always returns a 4–digit year:<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 681


System and Other FunctionsWRITE $ZDATETIME($ZUTIL(71),5),!/* returns the $ZUTIL(71) default:Dec 31, 1840 */WRITE $ZDATETIME($HOROLOG,5),!/* returns the current date and time,in this case: Jan 3, 2003 11:21:29 */WRITE $ZDATETIME($ZUTIL(71,55555),5),!/* sets $HOROLOG and returns the prior valueof $ZUTIL(71): Dec 31, 1840 */WRITE $ZDATETIME($ZUTIL(71),5),!/* returns the value set by the previous $ZUTIL(71):Feb 7, 1993 */WRITE $ZDATETIME($HOROLOG,5),!/* returns the value set by $ZUTIL(71)and the current time:Feb 7, 1993 11:21:41 */WRITE $ZDATETIME($HOROLOG,5),!/* returns the fixed date value set by $ZUTIL(71)and the incrementing current time:Feb 7, 1993 11:21:44 */WRITE $ZDATETIME($ZUTIL(71,0),5),!/* reverts $HOROLOG and $ZUTIL(71)to their default values, andreturns the fixed date value set bythe prior $ZUTIL(71): Feb 7, 1993 */WRITE $ZDATETIME($HOROLOG,5),!/* returns the current date and time,in this case: Jan 3, 2003 11:22:01 */WRITE $ZDATETIME($ZUTIL(71),5),!/* returns the $ZUTIL(71) default:Dec 31, 1840 */Notes$ZUTIL(71,date) sets the date only for the process that invokes $ZUTIL(71,date). All other<strong>Caché</strong> processes continue to get $HOROLOG values that reflect the actual current date.$ZUTIL(71,date) has no effect on $ZTIMESTAMP or $ZUTIL(188).See Also• $HOROLOG special variable$ZUTIL(78,21)Searches journal file for open transactions.$ZUTIL(78,21)$ZU(78,21)DescriptionUse $ZUTIL(78,21) to search back journal files for open transactions.682 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


You must have the %Admin_Manage:Use privilege to execute any of the $ZUTIL(78) functions.These functions can also be invoked by % routines located in the manager's directory.For further details, refer to the Privileges and Permissions chapter of the <strong>Caché</strong> SecurityAdministration Guide.Return Values$ZUTIL(78,21) returns five fields delimited by commas, as follows:offset,name,counter,tstart_counter,earliest_counter$ZUTIL(78,21)offsetnamecountertstart_counterearliest_counterJournal offset. An integer.Journal file name. A fully-qualified pathname.Journal file counter (pairing journal file name.) An integer.Journal file counter of the earliest TSTART. An integer. 0means no TSTART has been journaled.Journal offset of the earliest TSTART in the file. An integer.0 means no TSTART has been journaled.The string returned by $ZUTIL(78,21) might resemble the following example:132800,c:\cachesys\mgr\journal\20021204.001,4,4,132376The record indicated by the last two fields may not be a TSTART. However, there will beno open transaction preceding that record.See Also• TCOMMIT command• TSTART command• Using <strong>ObjectScript</strong> for Transaction Processing in Using <strong>Caché</strong> <strong>ObjectScript</strong>• Journaling in the <strong>Caché</strong> High Availability Guide<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 683


System and Other Functions$ZUTIL(78,22)Returns journaling information.$ZUTIL(78,22,filename,key)$ZU(78,22,filename,key)ParametersfilenamekeyOptional — The name of a journal file, specified as a quoted string.Optional — A numeric code for type of journaling information.DescriptionUse $ZUTIL(78,22) to return journaling information.You must have the %Admin_Manage:Use privilege to execute any of the $ZUTIL(78) functions.These functions can also be invoked by % routines located in the manager's directory.For further details, refer to the Privileges and Permissions chapter of the <strong>Caché</strong> SecurityAdministration Guide.ParametersfilenameThe full specification of the journal file on which you want information. Specify filename asa quoted string.keyA numeric code that specifies the type of information you want. The values you can use areas follows: 1 = Return prior journal file name. 2 = Return next journal file name (to be). 3 =Return maximum size of journal file. You must specify filename to specify key.Notes$ZUTIL(78,22): If you omit filename, $ZUTIL(78,22) returns boolean values for the following:jrnenabled^jrnpaused^jrnsuspended^jrnfailFor example, 1^0^0^0.The jrnfail flag indicates that an error retry is in progress.684 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(78,22)$ZUTIL(78,22,filename): If you include filename, $ZUTIL(78,22) opens the specified fileand reads the header. You must specify a complete file pathname, such as"C:\CacheSys\Mgr\Journal\20020206.001". If you include filename and omit key,$ZUTIL(78,22) returns one of the following values:0-11File doesn't exist.File is not a journal file.File exists and is a journal file.$ZUTIL(78,22,filename,key): You must specify filename to specify a key. If you includekey, $ZUTIL(78,22) returns the previously listed numeric values for non-journals: 0 for anon-existent file, or -1 for a non-journal file.If the file does exist and is a journal file, $ZUTIL(78,22) returns key, followed by a secondfield, delimited by a comma. If the value for the second field is a null string (for example,key=2 and there is no next journal file), $ZUTIL(78,22) just returns the key number.The following example shows the values returned by the different key numbers. Note thatthe key number itself is the first thing returned, followed by a value. In this case, there is nonext journal file, so key=2 returns just the key number itself.To determine the filename of the current journal file, use $ZUTIL(78,21).SET jrninfo=$ZUTIL(78,21)SET jrnname=$PIECE(jrninfo,",",2,2)WRITE !,"Current journal: ",jrnnameWRITE !,"prior: ",$ZUTIL(78,22,jrnname,1)WRITE !,"next: ",$ZUTIL(78,22,jrnname,2)WRITE !,"size: ",$ZUTIL(78,22,jrnname,3)1,c:\cachesys\mgr\journal\20021203.00123,1073741824See Also• $ZUTIL(78,21) Search Journal File for Open Transactions function• Using <strong>ObjectScript</strong> for Transaction Processing in Using <strong>Caché</strong> <strong>ObjectScript</strong>• Journaling in the <strong>Caché</strong> High Availability Guide<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 685


System and Other Functions$ZUTIL(78,23)Deletes a journal file.$ZUTIL(78,23,filename)$ZU(78,23,filename)ParametersfilenameThe name of the journal file to delete, specified as a quoted string.DescriptionYou can use $ZUTIL(78,23) to delete a journal file from within <strong>Caché</strong>. This function doesnot check that the file to be deleted is a journal file, so it may also delete non-journal files ordirectories.You must have the %Admin_Manage:Use privilege to execute any of the $ZUTIL(78) functions.These functions can also be invoked by % routines located in the manager's directory.For further details, refer to the Privileges and Permissions chapter of the <strong>Caché</strong> SecurityAdministration Guide.ParametersfilenameThe name of the file to delete, specified as a quoted string. $ZUTIL(78,23) expands filenames to full canonical form. On VMS systems it automatically specifies the latest versionof the file.Return Values$ZUTIL(78,23) returns one of the following values:1other valuesSuccessful file deletionFailure. A positive number other than 1 or a negative number indicatefailure. The exact return value is platform-dependent. Possible reasonsare file not found or file locked by another user.If the file is locked by another process, you cannot delete a file using $ZUTIL(78,23). If thespecified file is the active journal, a error is generated.686 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


NotesYou can also delete a journal file using the $$DELFILE^JRNUTIL(jrnfile) extrinsic function,as described in the <strong>Caché</strong> High Availability Guide. Unlike $ZUTIL(78,23), this extrinsicfunction confirms that the specified file is a journal file before attempting a delete operation.See Also• Journaling in the <strong>Caché</strong> High Availability Guide$ZUTIL(78,28)$ZUTIL(78,28)Returns journal directory block information.$ZUTIL(78,28)$ZU(78,28)Description$ZUTIL(78,28) returns information about the journal directory block.You must have the %Admin_Manage:Use privilege to execute any of the $ZUTIL(78) functions.These functions can also be invoked by % routines located in the manager's directory.For further details, refer to the Privileges and Permissions chapter of the <strong>Caché</strong> SecurityAdministration Guide.$ZUTIL(78,28) returns the information about the journal directory block in the followingform:dirblkver^dirblknum^dirblksizedirblkverdirblknumdirblksizeThe directory block versionThe directory block numberThe directory block size in bytes.The journal directory block in a journal file stores information about the database directoriesreferenced in journal records. The block is updated the first time a global journal SET orKILL occurs in a newly-mounted directory.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 687


System and Other FunctionsEvery time the block is updated, its version is incremented by 1. This version number is resetonly at startup and is not stored in a journal file. The zero-based block number tells where tolocate the directory block in a journal file. For example:OPEN jfile:("rf":8192)USE jfile:blocknumberREAD xSee Also• Using <strong>ObjectScript</strong> for Transaction Processing in Using <strong>Caché</strong> <strong>ObjectScript</strong>• Journaling in the <strong>Caché</strong> High Availability Guide$ZUTIL(78,29)Flushes journal buffer.$ZUTIL(78,29)$ZU(78,29)DescriptionAs part of rolling back a failed transaction, you need to flush to disk the journal buffer associatedwith that transaction. To do so, you use the $ZUTIL(78,29) function.You must have the %Admin_Manage:Use privilege to execute any of the $ZUTIL(78) functions.These functions can also be invoked by % routines located in the manager's directory.For further details, refer to the Privileges and Permissions chapter of the <strong>Caché</strong> SecurityAdministration Guide.$ZUTIL(78,29) returns a 1 if the buffer flush is successful, and a 0 if the buffer flush is notsuccessful.See Also• TROLLBACK command• Using <strong>ObjectScript</strong> for Transaction Processing in Using <strong>Caché</strong> <strong>ObjectScript</strong>• Journaling in the <strong>Caché</strong> High Availability Guide688 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(82,12)$ZUTIL(82,12)Redirects I/O operations.$ZUTIL(82,12,n)$ZU(82,12,n)ParameternThe boolean value that specifies whether or not to perform I/O redirection.DescriptionYou can use $ZUTIL(82,12) to put in effect redirection of I/O commands for the currentdevice. Specifying $ZUTIL(82,12) without the n parameter returns the current status of thisI/O redirection switch.For information on handling a timeout of a READ with I/O redirection, refer to $ZUTIL(96,4).When you turn on redirection for a particular device, READ and WRITE commands becomecalls to labels in the mnemonic space routine. Thus, as the following UNIX example shows,commands of the form:WRITE /?xxxorREAD /?xxxare treated as reference to tags %xxx in the mnemonic space routine for the current device.To determine the current device, use the $IO special variable.The redirection entrypoints and call formats for user-written routines for WRITE and READare as follows:WRITE STRING = DO wstr(STRING)WRITE *CHAR = DO wchr(CHAR)WRITE ! = DO wnlWRITE ?POS = DO wtab(POS)WRITE # = DO wffREAD VAR#LEN:TIMEOUT = SET VAR=$$rstr(LEN,TIMEOUT)READ *VAR:TIMEOUT = SET VAR=$$rchr(TIMEOUT)ParametersnThe boolean switch that determines redirection: 0 = Redirection not in effect for currentdevice (default). 1 = Redirection in effect for the current device.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 689


System and Other FunctionsSee Also• READ command• WRITE command• $ZUTIL(96,4) — Set $TEST to reflect I/O Redirection function• $IO special variable$ZUTIL(86)Returns configuration file pathname and config name.$ZUTIL(86)$ZU(86)Description$ZUTIL(86) returns the full pathname of the configuration file used to start the system, andthe current config name. The configuration file supplies both the system configurationparameters and the network configuration parameters during startup. In the following example,the configuration file is Cache.cpf.WRITE $ZUTIL(86)returns C:\CacheSys\Cache.cpf*CACHEIf <strong>Caché</strong> cannot determine the configuration name, $ZUTIL(86) returns UNKNOWN. Thisis not an error in $ZUTIL(86) processing, but reflects a problem with <strong>Caché</strong> installation.The most common reason for this behavior is the use of symbolic links (which <strong>Caché</strong> doesnot currently support) during <strong>Caché</strong> installation.690 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(90,4)$ZUTIL(90,4)Starts up in a specified namespace (UNIX/VMS).$ZUTIL(90,4,namespace)$ZU(90,4,namespace)ParametersnamespaceThe name of the namespace, specified as a quoted string.DescriptionYou can use $ZUTIL(90,4) on UNIX or VMS systems to set the <strong>Caché</strong> system-widenamespace for all subsequent processes. This function has no effect on Windows systems.You can use the $ZUTIL(90,10) function to determine if a namespace is defined. You canuse the $ZNSPACE special variable to determine your current namespace.See Also• ZNSPACE command• $ZUTIL(5) Display or Switch Namespace function• $ZUTIL(90,10) Test Whether a Namespace is Defined function• $ZNSPACE special variable$ZUTIL(90,10)Tests whether a namespace is defined.$ZUTIL(90,10,namespace)$ZU(90,10,namespace)ParametersnamespaceThe name of the namespace, specified as a quoted string.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 691


System and Other FunctionsDescriptionYou can test whether a namespace is defined by issuing this function. It returns 0 if thespecified namespace is not defined. It returns 1 if the specified namespace is defined.Namespace names are case-insensitive; by convention, they are specified and displayed inall uppercase characters.$ZUTIL(90,10) only recognizes explicit namespace names; it does not recognize impliednamespace names.ExampleIn the following example, the first $ZUTIL(90,10) returns 0 (namespace doesn't exist) andthe second $ZUTIL(90,10) returns 1 (namespace does exist):WRITE !,$ZUTIL(90,10,"FRED") ; a non-existent namespaceWRITE !,$ZUTIL(90,10,"SAMPLES")See Also• ZNSPACE command• $ZUTIL(90,4) Start Up in a Specified Namespace function• $ZNSPACE special variable692 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(94)$ZUTIL(94)Broadcasts a message to a specified process.$ZUTIL(94,pid,message,timeout,noxy)$ZU(94,pid,message,timeout,noxy)ParameterspidmessagetimeoutnoxyA process ID number.The message to send, specified as a quoted string.Optional — An integer specifying the number of seconds to wait beforetimeout. If omitted, no timeout occurs.Optional — A boolean value specifying whether the $X and $Y valuesare to be modified in the terminal process receiving the message. If 0,$X and $Y are updated. If 1, $X and $Y are not updated. The default is0. This parameter does not apply to OpenVMS systems, which do notupdate $X and $Y following a broadcast message.DescriptionUse $ZUTIL(94) to send a message to the principal device of the process you indicate.$ZUTIL(94) passes the message to the target process. The target process then writes themessage to its principal output device. The target process must be running <strong>Caché</strong>. If you senda message to your own process, you do not see the message on the screen of your principaldevice.$ZUTIL(94) does not add any carriage controls to the message it sends. To include any carriagecontrol (carriage returns or line feeds), you must include them in the message, using$CHAR(10) and $CHAR(13).$ZUTIL(94) complements $ZUTIL(9). $ZUTIL(9) sends a message to a specified devicewhile $ZUTIL(94) sends a message to the principal device of a specified process. Be surethat you use the right function for the right purpose. If you send a process id to $ZUTIL(9)or a terminal device name to $ZUTIL(94), you receive a error.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 693


System and Other FunctionsParameterspidThe process id of the target process. The System Management Portal provides a Processesoption, which list the pids of all running processes.messageThe message to send, specified as a quoted string.timeoutA timeout in seconds. If $ZUTIL(94) is not able to send the message during the timeoutperiod, it ceases attempts to send the message after timeout expires. You must specify timeoutto specify noxy. If you specify a timeout of < 0, no timeout occurs. If you specify a timeoutof 0, <strong>Caché</strong> sets a timeout of 1 second.noxyIf 0, $X and $Y are updated in the receiving process to indicate the location of the end of thebroadcast message. If 1, $X and $Y are not updated. The default is 0. This parameter doesnot apply to OpenVMS systems, which do not update $X and $Y following a broadcastmessage.See Also• $ZUTIL(9) Broadcast a Message to a Specified Device function• Terminal I/O in <strong>Caché</strong> I/O Device Guide$ZUTIL(96)Returns or sets <strong>Caché</strong> information.$ZUTIL(96)$ZU(96)DescriptionUse the various forms of $ZUTIL(96) to return or set various items of <strong>Caché</strong> information.The following sections describe $ZUTIL(96):• $ZUTIL(96,4) Sets $TEST to Reflect Redirection Operations694 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(96,4)• $ZUTIL(96,5) Sets $DEVICE• $ZUTIL(96,9) Returns the Calling Routine Name• $ZUTIL(96,10) Returns the Calling Routine Namespace• $ZUTIL(96,14) Returns the Current Device Type$ZUTIL(96,4)Sets $TEST to reflect I/O redirection.$ZUTIL(96,4,n)$ZU(96,4,n)ParameternThe boolean value used to set the $TEST special variable upon return from I/Oredirection code.0 = Clears $TEST (sets to 0) on return from the redirected READ.1 = Sets $TEST (sets to 1) on return from the redirected READ.DescriptionYou can specify how to handle the $TEST special variable on return from I/O redirectionby issuing this function. By default, the value of $TEST is preserved (stored and restored)across a call to extrinsic code, such as I/O redirection code. However, you may wish to returnthe setting of $TEST from I/O redirection code. For example, if application code invokes aREAD command with I/O redirection, and the READ times out, this timeout sets $TEST inyour application. To preserve this setting of $TEST upon returning from I/O redirection code,you must invoke $ZUTIL(96,4,n) within the I/O redirection code.For further information on I/O redirection, refer to $ZUTIL(82,12).Note:$ZUTIL(96,4,n) can only be invoked from extrinsic code. It cannot be called directlyfrom the <strong>Caché</strong> Terminal. Attempting to do so results in a error.See Also• READ command<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 695


System and Other Functions• $TEST special variable$ZUTIL(96,5)Sets the $DEVICE special variable.$ZUTIL(96,5,string)$ZU(96,5,string)ParameterstringThe string value used to set the $DEVICE special variable. Specified as aquoted string.DescriptionYou can use $ZUTIL(96,5) to set the value of the $DEVICE special variable to string. Byconvention, string should describe the outcome of an I/O operation as a 3-piece string, in theform:standard_error,user_error,explanatory_textSee Also• $DEVICE special variable$ZUTIL(96,9)Returns the calling routine name.$ZUTIL(96,9)$ZU(96,9)DescriptionYou can return the name of the calling routine name of the last DO or user-defined call madeto the current routine by issuing this function.If no calling routine exists, $ZUTIL(96,9) returns the null string.696 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(96,10)$ZUTIL(96,10)Returns the calling routine namespace.$ZUTIL(96,10)$ZU(96,10)DescriptionYou can return the name of the namespace of the calling routine of the last DO or user-definedcall made to the current routine by issuing a call to this function.If no calling routine exists, $ZUTIL(96,10) returns the null string.$ZUTIL(96,14)Returns the current device type.$ZUTIL(96,14)$ZU(96,14)DescriptionYou can return the current device type by issuing a call to this function. If the current inputand output devices are not the same, $ZUTIL(96,14) returns the current input device.The device ID of the current device is found in the $IO special variable. The USE commandestablishes a device as the current device.Return ValuesThe following table lists the values that $ZUTIL(96,14) can return and their meanings:Value012345Device TypeSequential file (see Sequential File I/O in <strong>Caché</strong> I/O Device Guide.)Terminal (see Terminal I/O in <strong>Caché</strong> I/O Device Guide.)Spool device (see The Spool Device in <strong>Caché</strong> I/O Device Guide.)Magnetic tape (see Magnetic Tape I/O in <strong>Caché</strong> I/O Device Guide.)System operator's consolePseudo device (device numbers 20 to 46)<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 697


System and Other FunctionsValue6789101112Device TypeNull deviceSpooled virtual consoleInterjob communication (devices 22 and 225)TCP bindingsSPX NTI device [<strong>Caché</strong> 3.1 doesn't support SPX]Net BIOs NTI deviceNamed pipe deviceSee Also• USE command• $IO special variable• I/O Devices and Commands in <strong>Caché</strong> I/O Device Guide$ZUTIL(110)Returns the name of the system that is running.$ZUTIL(110)$ZU(110)Description$ZUTIL(110) returns a string that contains the name of your current system. This functionis supported on different platforms, as follows:WindowsVMSUNIXSame value as returned by GetComputerName.Same value as returned by $GETSYISame value as returned by uname()This function is supported on both 8-bit and Unicode implementations of <strong>Caché</strong>.To return the current system name as the terminal prompt, use $ZUTIL(186,1).698 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


ExampleThe following example returns the name of the system from which it was issued.WRITE $ZUTIL(110)See Also$ZUTIL(114)• $ZUTIL(131) Set or return system name, IP address, or mgr directory pathname function$ZUTIL(114)Determines Ethernet address.$ZUTIL(114,flag,name)$ZU(114,flag,name)ParametersflagnameThe switch that specifies the information that $ZUTIL(114) is to return. Validvalues are 0, 1, and 2.Optional — Ethernet device name(s).DescriptionYou can return a string containing ethernet address information by issuing a call to the followingfunction.$ZUTIL(114,0) returns the address of the primary ethernet device. This primary ethernetdevice is the first ethernet device found on the device names list with a valid ethernet address.Any ethernet device can be designated the primary ethernet device.$ZUTIL(114,0,name) returns the address of any attached ethernet device specified by name.On VMS systems, this is the physical port address of the ethernet device, not the hardwareaddress.The ethernet address is returned as a string of 12 characters that represent the 48-bit ethernetaddress.The name is not case sensitive. The maximum length of a device names list is platformdependent,but the name of an individual device cannot be more than 15 characters in length.An invalid name value results in a error.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 699


System and Other Functions$ZUTIL(114,0) returns a null string, rather than an ethernet address if:• The primary ethernet device is not present in the device names list. $ZUTIL(114,0,name)returns a null string if the named device is not present in the device names list, or has nocorresponding ethernet address.• On Windows systems, the <strong>InterSystems</strong> Packet Driver is not installed.• On IBM AIX systems, the DLPI (Data Link Provider Interface) packages are not installed.• The ethernet adapters are protected against access by non-root users, and the processinvoking $ZUTIL(114,0) is not the root user.$ZUTIL(114,1) returns the current list of attached ethernet device names, delimited by$CHAR(1). The first name in this list is the primary ethernet device.$ZUTIL(114,2) returns the current list of ethernet device names, delimited by commas.$ZUTIL(114,2,name) replaces the current ethernet device names list with the list specifiedin name; it then returns the ethernet device names list prior to the replacement.ParametersflagThe switch that specifies the information that $ZUTIL(114) is to return. Valid values are:Code012DescriptionReturns the address of an attached ethernet device. When name is specified,it returns the address of the named device. When name is not specified, itreturns the primary ethernet device.Returns a list of the ethernet device names actually present on the system.This is a subset of the list returned by flag= 2. Listed names are separated bythe $CHAR(1) character.Returns the current list of ethernet device names, as set by <strong>Caché</strong> startup orby a subsequent invocation of $ZUTIL(114,2,name). Listed names areseparated by commas.nameEthernet device name(s). Valid values are:700 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(114)When flag = 0When flag= 2name is the name of a specific ethernet device.$ZUTIL(114,0,name) returns the address of the named device.name is an ethernet device names list, enclosed in quotes withindividual device names separated by commas. A name listspecified in $ZUTIL(114,2) cannot contain control characters.ExamplesThe following example returns the address of the first ethernet adaptor found:SET Add=$ZUTIL(114,0)WRITE Addreturns 0000C0A5C222.The following example returns the address of a named ethernet adaptor:SET Add=$ZUTIL(114,0,"\\device\\NBf_SMCISA1")WRITE ADDreturns 0000C0A6C392.The following example returns a $CHAR(1) delimited list of ethernet adaptor names:SET R=$ZUTIL(114,1)FOR I=1:1:$LENGTH(R,$CHAR(1)) {WRITE $PIECE(R,$CHAR(1),I),!}returns:\\Device\\NwlnkNb\\Device\\Nbf_SMCISA1\\Device\\Nbf_NdisWan4The following example first returns a comma-delimited list of ethernet device names andthen replaces that list of names with the list of names specified:ZZDUMP $ZUTIL(114,2)returns: en0,en1,et0,et1WRITE !,$ZUTIL(114,2,"es0,es1"),"add one"WRITE !,$ZUTIL(114,1),"check one"WRITE !,$ZUTIL(114,2,"es2"),"add two"WRITE !,$ZUTIL(114,1),"check two"returns: en0,en1,et0,et1ZZDUMP $ZUTIL(114,2)<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 701


System and Other Functionsreturns: es0,es1See Also• ZZDUMP command$ZUTIL(128,1)Returns location of last single step during debugging.$ZUTIL(128,1)$ZU(128,1)DescriptionThis function is invoked during debugging and returns information about the location of thelast single step entered.Return ValuesThis function returns the following information about the last single step entered:where:stacklevelxeclevellinerefsrcoffsetsrc$STACK level of the breakpoint.XECUTE level of the breakpoint.Line reference of the breakpoint.0-based offset to the location in the source line where the break hasoccurred.Source line of the breakpoint.This function is a useful primitive in the development of trace capabilities beyond what isoffered by the "T" action.You can invoke $ZUTIL(128,1) only in the condition expression or the execute code associatedwith a ZBREAK breakpoint, or in routines and functions invoked from these contexts.702 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


You must have the %Development:Use privilege to execute the $ZUTIL(128) function. Forfurther details, refer to the Privileges and Permissions chapter of the <strong>Caché</strong> Security AdministrationGuide.ExampleConsider the following sample routine ^TEST:TEST WRITE !,"THIS IS A TEST"QUITWe will establish a single step breakpoint definition that causes the information provided by$ZUTIL(128,1) to be written out for each executed line of TEST:ZBREAK $:"N"::"WRITE !,$ZUTIL(128,1)"BREAK "L+"DO TESTreturns:1 0 TEST^TEST 6 TEST WRITE !,"THIS IS A TEST"THIS IS A TEST1 0 TEST+1^TEST 1 QUITSee Also• BREAK command• ZBREAK command• “Tracing Execution” in the Debugging chapter of Using <strong>Caché</strong> <strong>ObjectScript</strong>$ZUTIL(130)$ZUTIL(130)Sets or returns the domain ID or index.$ZUTIL(130,flag,0,value)$ZU(130,flag,0,value)Parametersflag0valueSpecifies which value to set or return.Always the number zero (0).Optional — The value to set.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 703


System and Other FunctionsDescriptionYou can set the domain ID or dsindex, or return their current values by issuing a call to thisfunction.You must have the %Admin_Manage:Use privilege to execute $ZUTIL(130) functions. Thisfunction can also be invoked by % routines located in the manager's directory. For furtherdetails, refer to the Privileges and Permissions chapter of the <strong>Caché</strong> Security AdministrationGuide.ParametersflagA flag that specifies which $ZUTIL(130) value to set or return:12domain IDdomain index (dsindex)0This parameter is always the number zero (0).valueThe value to set. If no value is specified, $ZUTIL(130) returns the current value of the flag.A domain ID is a string, and thus must be set as a value in quotes. A domain index is aninteger, specified without quotes.ExamplesThe following example returns the current domain ID and the current domain index:SET x = $ZUTIL(130,1,0)SET y = $ZUTIL(130,2,0)WRITE !,"domain ID is ",xWRITE !,"domain index is ",yThe following example sets the domain ID to 1:DO $ZUTIL(130,1,0,"1")SET x = $ZUTIL(130,1,0)WRITE !,"domain ID is ",xThe following example sets the domain index to 1:704 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(131)DO $ZUTIL(130,2,0,1)SET y = $ZUTIL(130,2,0)WRITE !,"domain index is ",y$ZUTIL(131)Sets or returns system identifiers.$ZUTIL(131,flag,alias)$ZU(131,flag,alias)ParametersflagaliasA numeric code that specifies which value to get or set: 0 = system name oralias. 1 = system name and <strong>Caché</strong> instance name.Optional — The system name alias to set, specified as a quoted string.Description$ZUTIL(131,0) returns the system name, or the system name alias established with$ZUTIL(131,0,"name"). You can establish this alias system-wide for the current instanceof <strong>Caché</strong>. Stopping and restarting <strong>Caché</strong> causes the system name value to revert to the systemdefault.$ZUTIL(131,1) returns the system name, followed by the name of the current instance of<strong>Caché</strong>. These two names are separated by a colon (:). $ZUTIL(131,1) always returns theactual system name; it does not return the system name alias established by$ZUTIL(131,0,"name").The string returned by $ZUTIL(131,1) can also be returned by writing the contents of the$SYSTEM variable.Prior to <strong>Caché</strong> 5.1, $ZUTIL(131,1) returned the IP address and other system information.You can get the IP address and other information using methods of the SYS.Process class,as shown in the following example:ZNSPACE "%SYS"WRITE ##CLASS(SYS.Process).%OpenId($JOB).ClientIPAddressGet()An IP address consists of four numbers separated by periods. Each of these numbers can befrom 0 to 255, inclusive. Refer to the <strong>Caché</strong> Class <strong>Reference</strong> for further details.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 705


System and Other FunctionsParametersflagA flag code that specifies which $ZUTIL(131) value to set or return:0 = the system name or system name alias for this instance of <strong>Caché</strong>.1 = a system identifier string, consisting of the system name followed by a colon (:), and the<strong>Caché</strong> instance name.aliasThe alias value to set, specified as a quoted string. The $ZUTIL(131,0,"alias") function(like all <strong>ObjectScript</strong> functions) sets the specified value and returns the previous value. Analias value is set for the duration of the current <strong>Caché</strong> session.ExamplesWRITE $ZUTIL(131,0)returns MYSYSWRITE $ZUTIL(131,1)returns MYSYS:CACHE2WRITE !,$ZUTIL(131,0,"FRED")WRITE !,$ZUTIL(131,0)WRITE !,$ZUTIL(131,1)WRITE !,$ZUTIL(131,0)returns:MYSYSFREDMYSYS:CACHE2FREDSee Also• $ZUTIL(68,42) Set $JOB format for the current process function• $ZUTIL(110) Return Current System Name function• $ZUTIL(67,15) Return IP Address legacy function706 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(132)$ZUTIL(132)Makes the last device in use the principal I/O device.$ZUTIL(132)$ZU(132)DescriptionYou can make the current device (last device specified in a USE command) the principal I/Odevice (referenceable by USE 0 or USE $PRINCIPAL) by issuing a call to $ZUTIL(132).This function makes the current device the principal I/O device, while leaving the formerprincipal I/O device open, and thus capable of being used explicitly by name.$ZUTIL(132) takes no arguments. It returns 1 on success, 0 on failure, and generates a error if any arguments are specified.See Also• USE command• $PRINCIPAL special variable<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 707


System and Other Functions$ZUTIL(140)Returns file, directory, and disk information and performs file operations.$ZUTIL(140,1,name)$ZUTIL(140,2,name,timeflag)$ZUTIL(140,3,name,timeflag)$ZUTIL(140,4,name)$ZUTIL(140,5,name)$ZUTIL(140,6,name,newname)$ZUTIL(140,7,name)$ZUTIL(140,9,name)$ZUTIL(140,10,name)$ZUTIL(140,11,source,destination)$ZUTIL(140,12,name,mode)$ZUTIL(140,13,dir)The $ZU abbreviation can be used with above syntax.ParametersnametimeflagnewnamesourcedestinationmodedirThe name of the file or directory on which to perform the operation,specified as a quoted string.Optional — A boolean value specifying how to return a time value. Theavailable options are local (0), or UTC (1). The default is 0.For $ZUTIL(140,6), the file name used to rename the file. Specified as aquoted string.For $ZUTIL(140,11), the name of the file or directory used as the sourcefor a copy operation, specified as a quoted string.For $ZUTIL(140,11), the name of the file or directory used as thedestination (target) for a copy operation, specified as a quoted string.For $ZUTIL(140,12), an integer specifying the operating systempermissions to check. Available values are 0 through 7, which correspondto all possible bit mask combinations.For $ZUTIL(140,13), a disk name or directory pathname, specified as aquoted string.Description$ZUTIL(140) provides a (largely) platform-independent interface to retrieve operating systeminformation, such as attributes of a file or directory, and to create or delete files or directories.You can return a variety of file attributes for a specified file or directory using this function.708 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


You can test for the existence of a file and check its operating system level access permissions.You can rename, copy, or delete a file. You can create or delete a directory, or copy the filesfrom one directory to another. You can return the datestamp for the creation or most recentmodification of a file or directory. You can return the current size of a file. You can returnthe currently available disk space and block size — information that may be vital when creatingor copying a file.Parametersflag$ZUTIL(140)A number specifying which file or directory operation to perform. The following table showsthe $ZUTIL(140) flags recognized by <strong>Caché</strong>:Flag12345OperationReturns file size in bytes. If an error occurs, $ZUTIL(140) returns the operatingsystem's error code as a negative number. Thus, negative values are platformdependent.Thefollowing are common error codes returned by Windows systems:–2 = file not found.–3 = pathname not found.–5 = access denied (usually named item is a directory, not a file.)–12 = invalid access (usually user does not have read permission.)Returns modification date/time in $HOROLOG format. Returns -2 if the specifiedfile or directory does not exist. Using the optional timeflag, you can specifywhether to return the modification time value in local timezone time or Universaltime (UTC). Universal time is (for most purposes) equivalent to Greenwich MeanTime (GMT).Returns creation date/time in $HOROLOG format. Returns -2 if the specified fileor directory does not exist. Using the optional timeflag, you can specify whetherto return the creation time value in local timezone time or Universal time (UTC).Universal time is (for most purposes) equivalent to Greenwich Mean Time (GMT).Tests whether the named item exists. Returns 0 if the specified pathname exists,for either a file or a directory. Returns -2 if the specified item does not exist.Deletes the named file. Can delete a read-only file if user has privileges to modifythe directory in which the file resides. Returns 0 when successful. Returns -2 ifname does not exist. Returns -5 if name is a directory.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 709


System and Other FunctionsFlag678910111213OperationRenames the file specified in name with the name specified in newname. Maymove the file to a different location, if the host operating system supports it.Returns -2 if name does not exist. Returns -32 if name is a directory.Returns file attributes as a bit map. See $ZUTIL(140,7). Returns -2 if the specifiedfile does not exist.[unused]Creates the directory specified in name. Returns 0 when successful; returns -183if the specified directory already exists.Deletes the directory specified in name. Returns 0 when successful; returns -2if the specified directory does not exist.Copies a file or directory from source to destination:$ZUTIL(140,11,source,destination). The source must exist. If source isa file, destination may be a file or an existing directory. If source is a directory,destination must be a directory. In this case, all files in source are copied todestination, but subdirectories in source are not copied. Returns 0 whensuccessful; returns a negative integer upon failure.Check a file's access permissions: $ZUTIL(140,12,name,mode). The modebit mask has the following values: 0=file exists, 1=execute permission, 2=writepermission, 4=read permission; values 3, 5, 6, and 7 represent combinations ofthese values. Returns 0 when successful (bit mask matches file's permissions);returns -2 if the file does not exist, -13 if not all specified modes are permitted.$ZUTIL(140,12) does not change a file's modification date/time.Returns the amount of disk space available on the dir disk as four numeric valuesseparated by commas:Free disk space available to the caller. Windows: space available to the callerin bytes (limited if there is a quota for the user). UNIX: space available to nonprivilegedusers in blocks. VMS: space available to the caller in blocks.Total free disk space. Windows: in bytes. UNIX or VMS: in blocks.Total disk space. Windows: in bytes. UNIX or VMS: in blocks.Size of a block. Windows: defaults to 1. UNIX or VMS: in bytes.File and Directory NamesThe name, newname, source and destination parameters all specify a file or directory pathnameas a quoted string. Specify these parameter values in the standard syntax of file and directory710 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


names for the host operating system. On Windows and UNIX systems you can use the followingstandard pathname symbols: a single dot (.) to specify the current directory, or a doubledot (..) to specify its parent directory. For the directory functions on VMS, if name does notcontain the directory delimiters "[]" or "" it is assumed to be a subdirectory of the currentdirectory (i.e. "abc" is equivalent to "[.abc]"). For file deletion on VMS, an explicit file versionnumber must be supplied.Directory in $ZUTIL(140,13)$ZUTIL(140,13) uses the dir directory pathname to provide the name of the disk. It must,therefore contain the disk name, for example “c:”. dir can optionally supply a longer directorypathname, which is validated, but nothing beyond the disk name affects the values returned.If dir is a non-existent disk name or an invalid directory pathname, <strong>Caché</strong> returns -3. If diris a defined but unmounted disk, <strong>Caché</strong> returns -21. If dir is a file pathname, <strong>Caché</strong> returns-267. If dir contains a wildcard character (*), <strong>Caché</strong> returns -123.ExamplesThe following program example demonstrates the values returned by several of the$ZUTIL(140) flag options for a file:SET fname=$ZSEARCH("*cache.lck")WRITE !,"file path:",fnameWRITE !,"1:",$ZUTIL(140,1,fname)WRITE !,"2:",$ZUTIL(140,2,fname)WRITE !,"3:",$ZUTIL(140,3,fname)WRITE !,"4:",$ZUTIL(140,4,fname)WRITE !,"7:",$ZUTIL(140,7,fname)WRITE !,"12:",$ZUTIL(140,12,fname,0)The following program example demonstrates the values returned by $ZUTIL(140,13):SET dir="c:"SET by=" bytes",bl=" blocks"SET val=$ZUTIL(140,13,dir)WRITE !,"string is: ",valIF $PIECE(val,",",4)=1 {WRITE !,"This is a Windows system"WRITE !,$PIECE(val,",",1),by," free space available"WRITE !,$PIECE(val,",",2),by," total free space"WRITE !,$PIECE(val,",",3),by," total disk space"}ELSE { WRITE !,"This is a UNIX or VMS system"WRITE !,$PIECE(val,",",1),bl," free space available"WRITE !,$PIECE(val,",",2),bl," total free space"WRITE !,$PIECE(val,",",3),bl," total disk space"WRITE !,$PIECE(val,",",4),by," is the block size"}See Also• $ZSEARCH function$ZUTIL(140)<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 711


System and Other Functions• $ZUTIL(140,7) Return File Attributes function• $HOROLOG special variable$ZUTIL(140,7)Returns a bitmap of file attributes.$ZUTIL(140,7,filename)$ZU(140,7,filename)ParameterfilenameThe pathname of a file or directory, specified as a quoted string.DescriptionFor $ZUTIL(140) with other second parameter values, refer to $ZUTIL(140).Issuing $ZUTIL(140,7,filename) returns a bitmap that specifies several attributes of the file.The bitmap format is platform-dependent. A value of 1 for a bit specifies that the attributeapplies to the file.$ZUTIL(140,7) returns a negative error code value if an error occurred (the error code issupplied by the host operating system).Windows bit map:Bit Position124MeaningRead-onlyHiddenSystem8163264128256DirectoryArchiveDeviceNormalTemporary712 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(140,7)Bit Position512102420484096819216384MeaningSparse FileReparse PointCompressedOfflineNot Content IndexedEncryptedUNIX mode bit map:Bit Position1248163264128256Meaningexecute permission for otherswrite permission for othersread permission for othersexecute permission for groupwrite permission for groupread permission for groupexecute permission for ownerwrite permission for ownerread permission for owner51210242048set groupidset userid40960xF000 is a mask for file type:1: fifo2: character special4: directory6: block special<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 713


System and Other Functions8: regular10: symbolic link12: socketVMS bit maps:For VMS, this is the file protection. It consists of four 4-bit fields, accessed by the followinghexadecimal masks:000F: system privileges00F0: owner privileges0F00: group privilegesF000: world privilegesEach of these subfields can contain the following bit values:1: no read access2: no write access4: no execute access8: no delete accessExamplesThe following Windows example shows the values returned for a directory (“samples”) anda database file “CACHE.DAT”:ZNSPACE "%SYS"SET dir=$ZUTIL(168) ; determine <strong>Caché</strong> directorySET sampdir=dir_"samples"WRITE !,$ZUTIL(140,7,sampdir)WRITE !,$ZUTIL(140,7,sampdir_"\CACHE.DAT")The first $ZUTIL(140,7) returns 16 (Directory); the second $ZUTIL(140,7) returns 32(Archive).See Also• $ZUTIL(140) Return File Attributes function714 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(147)$ZUTIL(147)Handles spaces in pathnames for the host platform.$ZUTIL(147,pathname)$ZU(147,pathname)ParameterspathnameA file name or pathname, specified as a quoted string.DescriptionThe $ZUTIL(147) function handles spaces in pathnames as appropriate to the host platform.If pathname contains a space character, pathname handling is platform-dependent.• VMS permits space characters in pathnames; $ZUTIL(147) performs no special processingand returns the pathname unchanged.• UNIX only permits space characters in quoted pathnames; if a pathname containingspaces $ZUTIL(147) returns the pathname enclosed in double quotes (“pathname”). Ifa pathname does not contain spaces, $ZUTIL(147) returns it unchanged. $ZUTIL(147)performs no other pathname validation.• Windows does not support spaces in pathnames; $ZUTIL(147) strips spaces from thesupplied pathname. If a pathname does not contain spaces, $ZUTIL(147) returns itunchanged in all cases. On Windows systems, $ZUTIL(147) validates pathnames thatcontain spaces. If a pathname containing spaces does not exist, $ZUTIL(147) returnsthe pathname unchanged (with its blank spaces), with the entire pathnames enclosed indouble quotes (“pathname”). If a pathname containing spaces exists, $ZUTIL(147)returns the short form pathname with spaces removed, such as the following:USER>WRITE $ZUTIL(147,"C:\\My Test File.txt")C:\\MYTEST~1.TXTIn this case, the filename is truncated at the second blank space (if present), and an ordinalnumber is appending to distinguish similarly-named files.$ZUTIL(147) is commonly used with the $ZF(-1) and $ZF(-2) functions.ExamplesThe following Windows example shows how $ZUTIL(147) handles existing and non-existingpathnames with and without spaces:<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 715


System and Other FunctionsUSER>WRITE $ZUTIL(147,"C:\\MyTest.txt") /* Existing no blanks */C:\\MyTest.txtUSER>WRITE $ZUTIL(147,"C:\\FakeFile.txt") /* Non-Existing no blanks */C:\\FakeFile.txtUSER>WRITE $ZUTIL(147,"C:\\Fake File.txt") /* Non-Existing 1 blank */"C:\\Fake File.txt"USER>WRITE $ZUTIL(147,"C:\\My Test.txt") /* Existing 1 blank */C:\\MYTEST~1.TXTUSER>WRITE $ZUTIL(147,"C:\\My Test Doc.txt") /* Existing 2 blanks */C:\\MYTEST~2.TXTUSER>WRITE $ZUTIL(147,"C:\\My Test File.txt") /* Existing 2 blanks */C:\\MYTEST~3.TXTUSER>The following example uses $ZUTIL(147) to handle a pathname for $ZF(-1). A pathnamecontaining spaces is handled as appropriate for the host platform. A pathname that does notcontain spaces is passed through unchanged.SET x=$ZF(-1,$ZUTIL(147,"C:\\My Test.txt"))See Also• $ZF(-1) function• $ZF(-2) function• $ZUTIL(12) Translate file name to canonical form function$ZUTIL(158)Displays currently installed printers.$ZUTIL(158,0)$ZUTIL(158,1,n)$ZU(158,0)$ZU(158,1,n)ParametersnA sequential integer (counting from 1) assigned to a printer.DescriptionThe $ZUTIL(158,0) function returns the number of printers currently installed on your system,counting from 1.716 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


The $ZUTIL(158,1,n) function returns the pathname of the printer currently installed onyour system that corresponds to n. <strong>Caché</strong> counts printers from 1, and assigns a sequentialinteger to each. If n is a number that does not correspond to a printer, <strong>Caché</strong> issues a error.ExampleThe following example returns the total number of installed printers, then returns the pathnamefor each printer.SET x=$ZUTIL(158,0)WRITE !,"The number of printers is: ",xWHILE x>0 {WRITE !,"Printer #",x," is ",$ZUTIL(158,1,x)SET x=x-1 }See Also• JOB command$ZUTIL(168)• “Specifying Terminals and Printers by Device Name” in the I/O Devices and Commandschapter of <strong>Caché</strong> I/O Device Guide$ZUTIL(168)Returns location of current working directory, or sets current working directory.$ZUTIL(168,dir)$ZU(168,dir)ParametersdirOptional — Name of directory to set as working directory for sequential file output.Specified as a quoted string.Description$ZUTIL(168) (with no arguments) returns a string that contains the location of your currentworking directory for sequential file output. (Note that this directory should not be confusedwith the default directory for globals in the current namespace.)$ZUTIL(168,dir) sets your current working directory for sequential file output to the dirdirectory. It returns the pathname of the old working directory. If the directory cannot be set<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 717


System and Other Functionsas the current working directory, $ZUTIL(168) issues a error, and ^SYSLOGwill show the cause of the error.Note:On Windows systems, $ZUTIL(168,dir) sets as the current directory a directoryname entirely in lowercase letters, regardless of the case of dir. Because Windowsand <strong>Caché</strong> <strong>ObjectScript</strong> are case-insensitive, this is usually irrelevant. However, thismay affect some Windows applications (such as Java) which are case-sensitive.You can use the wildcard options of the $ZSEARCH function to locate an existing directory.You can use $ZUTIL(140) to create a new directory, or to return information about anexisting file or directory.ParametersdirThe name of the directory to set as the working directory. The directory pathname must bespecified as a quoted string. On Windows and UNIX systems you can also use the followingstandard pathname symbols: a single dot (.) to specify the current directory, or a double dot(..) to specify its parent directory. Remember, when setting a working directory,$ZUTIL(168,dir) return the previous directory setting.ExamplesWRITE $ZUTIL(168)returns something like: c:\cachesys\mgr\user\. (The actual directory will differ on differentinstallations of <strong>Caché</strong>.)The following example returns the current working directory, then changes the directory tothe samples directory.WRITE !,$ZUTIL(168)ZNSPACE "%SYS"SET dir=$ZUTIL(168)SET newdir=$ZUTIL(168,dir_"samples")WRITE !,$ZUTIL(168)returns something like:c:\cachesys\mgr\user\c:\cachesys\mgr\samples\718 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


See Also• $ZSEARCH function• $ZUTIL(68,51) Namespace Default Directory Assignment function• $ZUTIL(69,51) Namespace Default Directory Assignment function• $ZUTIL(140) Return File Attributes, Create or Delete a Directory function$ZUTIL(186)$ZUTIL(186)Sets display in programmer prompt for the current process.$ZUTIL(186,n)$ZU(186,n)ParametersnAn integer code or a comma-separated list of integer codes that specify whatelement(s) to include in the terminal prompt. Integer codes should be specified inthe order in which you wish the elements to be displayed.DescriptionThe $ZUTIL(186) function specifies what information should appear in the programmermodeprompt for <strong>Caché</strong> Terminal.Issuing $ZUTIL(186) (with no option) returns the current state of the prompt setting as acomma-separated list of integer codes. Like all $ZUTIL functions, when you issue$ZUTIL(186,n), it returns its integer code setting prior to the current operation.Issuing $ZUTIL(186,0) clears the setting, so that no prompt information is displayed.The initial value of this setting depends on the both the system platform and the system-widedefault setting. The system default setting for Windows systems is to display the currentnamespace at the terminal prompt. You can enable or disable the current namespace displayin the terminal prompt for the current process using either $ZUTIL(186) or $ZUTIL(68,26).To control whether the current namespace name appears by default as part of the prompt forall processes on the system, use any one of the following:<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 719


System and Other Functions• Go to the System Management Portal, select System Configuration, select AdvancedSettings, on the pull-down Category list select <strong>ObjectScript</strong>. View and edit the currentsetting of PromptShowsNamespace.• $ZUTIL(69,26) — Enable/Disable System Namespace Display Default function.• The %ZSTART user-defined system startup routine (ZSTU startup routines are alsosupported).ParametersnThe integer code that specifies what information to display as part of the process' programmermode prompt.01234567Reset the prompt.Host name, also known as the current system name. The name assigned to yourcomputer. For example, LABLAPTOP>. This is the same for all of your terminalprocesses. Refer to $ZUTIL(110) for further details.Namespace name. For example, %SYS>. To set your terminal prompt to just thecurrent namespace name, you can use $ZUTIL(68,26,1). The current namespacename is contained in the $ZNSPACE special variable, and can be changed usingthe ZNSPACE command. It can be an explicit namespace name or an impliednamespace name.Config name. The name of your <strong>Caché</strong> installation. For example, CACHE2>. This isthe same for all of your terminal processes.Current time, expressed as local time in 24-hour format with whole seconds. Forexample, 15:59:36>.This is the static time value for when the prompt was returned.This value changes for each prompt.pid. The process ID for your terminal. For example, 2336>. This is different for eachterminal process. This value can also be returned from the $JOB special variable.Username. For example, fred>. This is the same for all of your terminal processes.Elapse time executing the last command, in seconds.milliseconds. For example,.000495>. Leading and trailing zeros are suppressed.This changes for each prompt.You can specify any number of integer codes in any order. Duplicate integer codes are permitted.Integer codes are evaluated and displayed in the order specified. Multiple elementsin a prompt are separated by a colon (:).720 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


ExampleThe following example tests the terminal prompt status, and sets it to display the current timeif no prompt has been set.SET x=$ZUTIL(186)WRITE !,"x is: ",xIF x=0 {SET y=$ZUTIL(186,4)WRITE !,"Prompt changed to display current time"}ELSE {WRITE !,"Prompt is set as follows: ",$ZUTIL(186)}See Also• $ZUTIL(68,26) Enable/Disable Namespace Display Default function$ZUTIL(188)• $ZUTIL(69,26) Enable/Disable System-wide Namespace Display Default function$ZUTIL(188)Returns current date and time with fractional seconds.$ZUTIL(188)$ZU(188)DescriptionThis function returns the current local date and time in $HOROLOG format, with fractionalseconds. This value is in local time, adjusted for local time variants, such as Daylight SavingsTime. The value returned is in the following format:ddddd,ttttt.ffffffWhere ddddd is the current date, expressed as a count of the number of days since December31, 1840, where day 1 is January 1, 1841; ttttt is the current time, expressed as a count ofseconds from midnight; and ffffff is fractional seconds, specified to the maximum precisionsupported by your operating system platform.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 721


System and Other FunctionsNote:Because of a limitation in the Windows operating system, putting your Windowssystem into hibernate or standby mode may cause $ZUTIL(188) to return unpredictablevalues. Rebooting your Windows operating system will restore $ZUTIL(188)to the correct value. This problem does not affect $HOROLOG or $ZTIMESTAMPvalues.The various ways to return the current date and time are compared, as follows:• $ZUTIL(188) returns the local, variant-adjusted date and time, with fractional seconds,in <strong>Caché</strong> storage ($HOROLOG) format. Fractional seconds are expressed in the maximumavailable number of digits of precision.• $HOROLOG contains the local, variant-adjusted date and time in <strong>Caché</strong> storage format.It does not record fractional seconds. Instead, $HOROLOG rounds up any fractionalsecond to the next whole second.• $ZTIMESTAMP contains the UTC (Greenwich Mean) date and time, with fractionalseconds, in <strong>Caché</strong> storage ($HOROLOG) format. Fractional seconds are expressed inthree digits of precision.The $ZUTIL(188) value is unaffected by the $ZUTIL(71) function. ($ZUTIL(71) is usedto set the $HOROLOG value to a specified date.)You can use the $ZDATETIME function to convert dates and times from $HOROLOGformat to display format.ExampleSET x=$HOROLOGSET y=$ZUTIL(188)SET z=$ZTIMESTAMPWRITE !,x," which is ",$ZDATETIME(x,1,1,9)WRITE !,y," which is ",$ZDATETIME(y,1,1,9)WRITE !,z," which is ",$ZDATETIME(z,1,1,9)See Also• $ZDATETIME function• $ZUTIL(71) Set Date to a Fixed Value function• $HOROLOG special variable• $ZTIMESTAMP special variable• $ZTIMEZONE special variable•722 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(189)$ZUTIL(189)Checks if TCP device is disconnected.$ZUTIL(189)$ZU(189)Description$ZUTIL(189) checks if the current TCP device has been disconnected from the remote site.It returns 0 if the TCP device is disconnected. It returns 1 if the TCP device is still connected.You can also have <strong>Caché</strong> poll asynchronously for TCP disconnect by using the D mode optionfor the OPEN or USE command. Refer to Using the TCP Binding to Connect Client/ServerSystems in the <strong>Caché</strong> I/O Device Guide for further details.ExampleWRITE $ZUTIL(189)returns 0.See Also• $ZUTIL(96,14) Return the Current Device Type function• $ZA special variable• $IO special variable• I/O Devices and Commands in <strong>Caché</strong> I/O Device Guide<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 723


System and Other Functions$ZUTIL(193)Converts Coordinated Universal Time (UTC) to local date and time (and vice versa).$ZUTIL(193,timestamp,direction)$ZU(193,timestamp,direction)ParameterstimestampdirectionA date and time to be converted. Specify timestamp in $ZTIMESTAMP format.If direction is omitted or 0, specify a Coordinated Universal Time (UTC) dateand time value. If direction is 1, specify a local date and time value.Optional — A boolean values specifying the direction in which to converttimestamp. If 0, timestamp is interpreted as a UTC value and converted tolocal time. If 1, timestamp is interpreted as a local date/time value and isconverted to UTC.The default is 0.Description$ZUTIL(193) inter-converts Coordinated Universal Time and local time:• It takes a date and time value in a Coordinated Universal Time and converts it to localtime (direction = 0).• It takes a date and time value in local time and converts it to Coordinated Universal Time(direction = 1).$ZUTIL(193) performs conversions using the current value of the $ZTIMEZONE specialvariable. $ZUTIL(193) adjusts for local time variants, such as Daylight Savings Time.The current date and time, in Coordinated Universal Time, with fractional seconds is containedin $ZTIMESTAMP. Coordinated Universal Time (UTC) is independent of time zone. (UTCis another name for Greenwich Mean Time (GMT).) Consequently, $ZTIMESTAMP providesa timestamp which is uniform across time zones. This may differ from both the local timevalue (because of time zone and local time variants) and the local date value (because of theinternational date line).$ZUTIL(193) and $ZTIMESTAMP both represent date and time as a string with the format:ddddd,ttttt.fffWhere ddddd is an integer specifying the number of days since December 31, 1840; ttttt isan integer specifying the number of seconds since midnight of the current day, and fff is a724 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(193)varying number of digits specifying fractional seconds. This format is similar to $HOROLOG,except that $HOROLOG does not preserve fractional seconds.The $ZUTIL(193) time value is a decimal numeric value that counts the time in seconds andfractions thereof. The number of digits in the fractional seconds may vary from zero to nine,depending on the precision of your computer's time-of-day clock. On Windows systems thefractional precision is three decimal digits; on UNIX systems it is six decimal digits.$ZUTIL(193) suppresses trailing zeroes or a trailing decimal point in this fractional portion.The $ZUTIL(193) date value must be within the range of January 1, 1970 ($HOROLOG =47117,00000) through January 18, 2038 ($HOROLOG = 71971,86399). This is an operatingsystem limitation, independent of the date range available through $HOROLOG. Specifyinga date outside this range causes an error.Note:Exercise caution when comparing local time and UTC time:• You cannot interconvert local time and UTC time by simply adding or subtractingthe value of $ZTIMEZONE * 60. This is because $HOROLOG local time isadjusted for local time variants (such as Daylight Savings Time, which seasonallyadjusts local time by one hour). These local time variants are not reflected in$ZTIMEZONE.• Both the timezone offset from GMT and local time variants (such as the seasonalshift to Daylight Savings Time) can affect the date as well as the time. Convertingfrom local time to UTC time (or vice versa) requires converting the date as wellas the time.Current Date and TimeThe various ways to return the current date and time are compared, as follows:• $ZTIMESTAMP contains the UTC (Greenwich Mean) date and time, with fractionalseconds, in <strong>Caché</strong> storage ($HOROLOG) format. Fractional seconds are expressed inthree digits of precision (on Windows systems), or six digits of precision (on UNIX systems).• $HOROLOG contains the local, variant-adjusted date and time in <strong>Caché</strong> storage format.It does not record fractional seconds. How $HOROLOG resolves fractional secondsdepends on the operating system platform: On Windows, it rounds up any fractionalsecond to the next whole second. On UNIX, it truncates the fractional portion.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 725


System and Other Functions• $ZUTIL(188) returns the local, variant-adjusted date and time, with fractional seconds,in <strong>Caché</strong> storage ($HOROLOG) format. Fractional seconds are expressed in six digitsof precision.You can obtain the same time stamp information as $ZTIMESTAMP by invoking a systemmethod, using either of the following syntax forms:WRITE !,$SYSTEM.SYS.TimeStamp()WRITE !,##class(%SYSTEM.SYS).TimeStamp()Refer to the $SYSTEM special variable and the “Class %SYSTEM.SYS” section of the<strong>Caché</strong> Class <strong>Reference</strong> for further details.Other Date/Time Conversion FunctionsYou can represent local time information as Coordinated Universal Time (UTC) using the$ZDATETIME and $ZDATETIMEH functions with tformat values 7 or 8, as shown in thefollowing example:WRITE !,$ZDATETIME($ZTIMESTAMP,1,1,2)WRITE !,$ZDATETIME($HOROLOG,1,7,2)WRITE !,$ZDATETIME($HOROLOG,1,8,2)WRITE !,$ZDATETIME($ZUTIL(188),1,7,2)WRITE !,$ZDATETIME($ZUTIL(188),1,8,2)The above $ZDATETIME functions all return the current time as Coordinated UniversalTime (rather than local time). The conversions from local time adjust for local time variantsand adjust the date accordingly, if necessary. However, the $ZTIMESTAMP display valueand the tformat 7 or 8 converted display values are not identical. The tformat values 7 and 8insert the letter “T” before, and the letter “Z” after the time value. Also, because $HOROLOGtime does not contain fractional seconds, the precision of 2 in the above example pads thosedecimal digits with zeros.ExamplesThe following examples compare the $ZUTIL(193) return value when you specify$ZTIMESTAMP and $HOROLOG, and shows how the time portion of $ZTIMESTAMPis converted. The value derived from $ZTIMESTAMP contains fractional seconds;$HOROLOG does not.Conversion from Universal time to local time:SET clock=$HOROLOGSET stamp=$ZUTIL(193,$ZTIMESTAMP)WRITE !,"local/local date and time: ",$ZDATETIME(clock,1,1,2)WRITE !,"UTC/local date and time: ",$ZDATETIME(stamp,1,1,2)726 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZWASCIIConversion from local time to Universal time:SET clock=$ZUTIL(193,$HOROLOG,1)SET stamp=$ZTIMESTAMPWRITE !,"local/UTC date and time: ",$ZDATETIME(clock,1,1,2)WRITE !,"UTC/UTC date and time: ",$ZDATETIME(stamp,1,1,2)See Also• $ZDATETIME function• $ZUTIL(188) Local Date and Time with Fractional Seconds function• $HOROLOG special variable• $ZTIMESTAMP special variable• $ZTIMEZONE special variable$ZWASCIIReturns the numeric interpretations of a two-byte string.$ZWASCII(string,position)$ZWA(string,position)ParametersstringpositionA string. It can be a value, a variable, or an expression. It must be aminimum of two bytes in length.Optional — A starting position in the string, expressed as a positiveinteger.The default is 1. Position is counted in single bytes, not two-bytestrings. The position cannot be the last byte in the string, or beyond theend of the string. A numeric position value is parsed as an integer bytruncating decimal digits, removing leading zeros and plus signs, etc.DescriptionThe value that $ZWASCII returns depends on the parameters you use.• $ZWASCII(string) returns a numeric interpretation of a two-byte string starting at thefirst character position of string.• $ZWASCII(string,position) returns a numeric interpretation of a two-byte string beginningat the starting byte position specified by position.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 727


System and Other FunctionsExampleThe following example determines the numeric interpretation of the character string "ab":WRITE $ZWASCII("ab")It returns 25185.The following examples also return 25185:WRITE !,$ZWASCII("ab",1)WRITE !,$ZWASCII("abxx",1)WRITE !,$ZWASCII("xxabxx",3)In the following examples, string or position are invalid. The $ZWASCII function returns–1 in each case:WRITE !,$ZWASCII("a")WRITE !,$ZWASCII("aba",3)WRITE !,$ZWASCII("ababab",99)WRITE !,$ZWASCII("ababab",0)WRITE !,$ZWASCII("ababab",-1)Notes$ZWASCII and $ASCII$ZWASCII is similar to $ASCII except that it operates on 16-bit words instead of 8-bitbytes. To operate on 32-bit double words, use the $ZLASCII function.$ZWASCII(string,position) is the functional equivalent of:$ASCII(string,position+1)*256+$ASCII(string,position)$ZWASCII and $ZWCHARThe $ZWCHAR function is the logical inverse of $ZWASCII. For example:WRITE $ZWASCII("ab")returns: 25185.WRITE $ZWCHAR(25185)returns “ab”.See Also• $ASCII function• $ZWCHAR function728 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZWCHAR$ZWCHARReturns the requested two-byte string.$ZWCHAR(n)$ZWC(n)ParameternPositive integer that can be specified as a value, a variable, or an expression.Description$ZWCHAR returns a two-byte string for n. It is the functional equivalent of:WRITE $CHAR(n#256,n\256)ExampleThe following example returns the two-byte string for the integer 25185:WRITE $ZWCHAR(25185)returns: abNotes$ZWCHAR and $CHAR$ZWCHAR is similar to $CHAR except that it operates on 16-bit words instead of 8-bitbytes. To operate on 32-bit double words, use the $ZLCHAR function.$ZWCHAR and $ZWASCII$ZWASCII is the logical inverse of the $ZWCHAR function. For example:WRITE $ZWCHAR(25185)returns: abWRITE $ZWASCII("ab")returns: 25185See Also• $CHAR function<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 729


System and Other Functions• $ZLCHAR function• $ZWASCII function$ZWIDTHReturns the total width of the characters in an expression.$ZWIDTH(expression,pitch)ParametersexpressionpitchA string expressionOptional — The numeric pitch value to use for full-width characters.The default is 2. Other permissible values are 1, 1.25, and 1.5.Description$ZWIDTH is a DSM-J function available in <strong>Caché</strong> <strong>ObjectScript</strong>. $ZWIDTH returns thetotal width of the characters in expression. The pitch value determines the width to use forfull-width characters. All other characters are assigned a width of 1 and are considered to behalf-width.Note:$ZWIDTH can be abbreviated as $ZW in DSM-J mode. This abbreviation cannotbe used in <strong>Caché</strong> mode.ExampleAssume that the variable STR contains two half-width characters followed by a full-widthcharacter:WRITE $ZWIDTH(STR,1.5)returns 3.5.In this example, the two half-width characters total 2. Adding 1.5 (the specified pitch value)for the full-width characters produces a total of 3.5.NoteFull-width characters are determined by examining the pattern-match table loaded for your<strong>Caché</strong> process. Any character with the full-width attribute is considered to be a full-width730 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


character. You can use the special ZFWCHARZ patcode to check for this attribute(char?1ZFWCHARZ). See the description of the $X/$Y Tab in Customized National LanguageTranslations for more information about the full-width attribute.See Also• $ZPOSITION function• $ZZENKAKU function$ZWPACK and $ZWBPACK$ZWPACK and $ZWBPACKPuts strings without multibyte characters into 2-bytes per character format.$ZWPACK(string)$ZWP(string)$ZWBPACK(string)$ZWBP(string)ParametersstringThe string with multibyte characters to be packed.Description$ZWPACK is a function used to put strings without multibyte characters into a 2-bytes percharacter format in little-endian order.$ZWBPACK performs the same task, but the strings are stored in big-endian order.You can use $ZISWIDE on the string first to check that it does not contain multibyte characters.If you use $ZWPACK or $ZWUNPACK on strings containing multibyte characters,<strong>Caché</strong> generates a error.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 731


System and Other FunctionsConversion of a String to Multibyte Little or Big Endian FormatExamplesThe following examples show $ZWPACK and $ZWBPACK:WRITE $ZWPACK($CHAR(65,66,67,68))returns 4241 4443WRITE $ZWBPACK($CHAR(65,66,67,68))returns 4142 4344See Also• $ZISWIDE function• $ZWUNPACK and $ZWUNBPACK functions732 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZWUNPACK and $ZWUNBPACK$ZWUNPACK and $ZWUNBPACKUnpacks multibyte characters from storage in a 2-bytes per character format.$ZWUNPACK(string)$ZWUNP(string)$ZWBUNPACK(string)$ZWBUNP(string)ParametersstringThe string to be unpacked into multibyte characters.Description$ZWUNPACK is a function used to unpack multibyte characters from storage in a 2-bytesper character format in little endian order.$ZWBUNPACK performs the same task, but the strings are restored from big-endian order.Conversion of a Multibyte Little or Big Endian Format String to a Single-byte StringSee Also• $ZPOSITION function• $ZWPACK and $ZWBPACK functions<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 733


System and Other Functions$ZZENKAKUConverts Japanese alphabet characters.$ZZENKAKU(expression,flag1,flag2)Parametersexpressionflag1flag2A string expression.Optional — A flag to indicate whether conversion to full-widthhiragana (0) or conversion to full-width katakana (1) is required.Optional — A flag to indicate whether voiced sound processing isrequired (1) or not required (0).Description$ZZENKAKU is a DSM-J function available in Unicode versions of <strong>Caché</strong>. It is used forconverting Japanese alphabet characters.If flag1 is 0, $ZZENKAKU converts printable ASCII characters to their full-width counterpartsand converts half-width katakana characters to full-width hiragana characters. Thedefault value for flag1 is 0.If flag1 is 1, $ZZENKAKU converts printable ASCII characters to their full-width counterpartsand converts half-width katakana characters to full-width katakana characters.If flag2 is 1 and a half-width katakana character is followed by a voice sound mark or a semivoicesound mark, then (if appropriate) $ZZENKAKU combines the half-width katakanacharacter and the sound mark character into a target full-width hiragana or katakana character.The default value for flag2 is 1.Note:$ZZENKAKU can be abbreviated as $ZZ in DSM-J mode. This abbreviation cannotbe used in <strong>Caché</strong> mode.See Also• $ZPOSITION function• $ZWIDTH function734 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


The %ZLANG Language ExtensionLibrary%ZLANGAllows users to extend the <strong>Caché</strong> <strong>ObjectScript</strong> language.%ZLANGxnntagnamecodeArgumentsxnntagnamecodeA letter code specifying the type of routine. Available values are C =command; F = function; V = special variable. Letters must be uppercase.A two-digit numeric code specifying the language mode. The leadingzero must be specified. Available values are: 00 = <strong>Caché</strong>; 01 = DSM-11;02 = DTM; 05 = DSM/VSM (OpenVMS); 06 = DSM-J; 07 = DTM-J; 08= MSM; 9 = <strong>Caché</strong> BASIC; 11 = MV (multi-value) BASIC.The name of the command, function, or special variable. Refer to thenaming convention restrictions below.One or more lines of <strong>Caché</strong> <strong>ObjectScript</strong> code to perform some operation.This code must be indented, and follows all the standard whitespace,comment, and other conventions of <strong>Caché</strong> <strong>ObjectScript</strong>. It is stronglyrecommended that code end with a QUIT command, to preventaccidentally “falling through” to the next routine specified in %ZLANG.DescriptionYou can use the %ZLANG language extension library to add custom features to the <strong>Caché</strong><strong>ObjectScript</strong> language. You can declare user-defined commands, functions, and systemwidespecial variables for your installation of <strong>Caché</strong>. These custom extensions are invoked in thesame way as standard <strong>Caché</strong> <strong>ObjectScript</strong> features, and follow the same rules for syntax,operator precedence, etc.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 735


The %ZLANG Language Extension LibraryThe %ZLANG language extension library cannot be used to override, modify, or disable anystandard feature of <strong>Caché</strong> <strong>ObjectScript</strong>. If a feature in %ZLANG has the same name as astandard <strong>Caché</strong> feature, the standard feature is always the one that is invoked.The %ZLANG library name must be specified on the first line, beginning with column 1.Although this library tag should never be called as an entrypoint, it is good programmingpractice to follow it by a QUIT command (indented, in line 2) to prevent “fall through.” A%ZLANG library can contain one or more entrypoints, each specified by a tagname. However,all entrypoints in a %ZLANG library must be for the same type of routine (letter code) andlanguage mode (numeric code), as specified in the library name.The tag name for all %ZLANG features must follow the naming conventions of specifyingthe letter “Z” as the first letter of the feature name, and using only uppercase letters. (Featuresmay be invoked using any combination of uppercase or lowercase letters.) It is also stronglyrecommended that %ZLANG feature names avoid names of standard <strong>Caché</strong> features, and<strong>Caché</strong> and SQL reserved words. Further details on tag name conventions are specified below.You can also specify user-defined extrinsic functions using the $$ prefix syntax, as describedin User Defined Code chapter of Using <strong>Caché</strong> <strong>ObjectScript</strong>.Note:%ZLANG features generally do not execute as rapidly as standard <strong>Caché</strong> features.This performance limitation should be taken into consideration when coding performance-criticalroutines.Tag Name ConventionsA tag name is the label name used to invoke a %ZLANG feature from <strong>Caché</strong> <strong>ObjectScript</strong>code. The rules governing a tag name are different, and more restrictive, than the rules governinginvocation of that feature from code.• Because a tag name is a label, it must begin at column 1. The executable <strong>Caché</strong><strong>ObjectScript</strong> code for the feature must be indented.• A tag name for a function or a special variable does not begin with a dollar sign ($). Thisdollar sign is only used when invoking the function or special variable.• A tag name must begin with the letter “Z”. It can consist only of letters and numbers. Itcan include Unicode letter characters.• A tag name must consist of all uppercase characters. You can invoke the feature from<strong>Caché</strong> <strong>ObjectScript</strong> using any combination of uppercase or lowercase letters.• A tag name must be unique within %ZLANG, cannot duplicate the name of an existing<strong>Caché</strong> <strong>ObjectScript</strong> feature, and cannot be a reserved word.736 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


• A tag name can be a maximum of 31 characters in length. This does not include parenthesesand arguments that may follow the tag name.• A tag name for a function must include parentheses for arguments; if the function takesno arguments, specify empty parentheses. A tag name for a special variable may includeparentheses for for arguments; however, these parentheses are optional if the specialvariable takes no arguments.EntrypointsEach tag name specifies an entrypoint routine. You may specify multiple entrypoint routinesin the same source code library. However, all entrypoint routines in the same source codemust share the same feature type (x) and language mode (nn).ExamplesThe following example creates a command that execute the system status utility ^%SS:%ZLANGC00 ;QUIT ; this QUIT is always recommended to prevent "fall-through"ZSS ; tag name of a command to check system statusDO ^%SSQUITNote that %ZLANG specifies that this is a command (C) that is used in standard <strong>Caché</strong> languagemode (00).The following example creates a special variable that contains a portion of the <strong>Caché</strong> versionstring from the special variable $ZVERSION:%ZLANGV00 ;QUITZVERNUM ; tag name of a version string subset special variableQUIT $PIECE($ZVERSION,"(Build")Note that %ZLANG specifies that this is a special variable (V) that is used in standard <strong>Caché</strong>language mode (00).See Also• User Defined Code in Using <strong>Caché</strong> <strong>ObjectScript</strong>• Debugging in Using <strong>Caché</strong> <strong>ObjectScript</strong>%ZLANG<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 737


Legacy Commands and FunctionsLegacy commands and functions are obsolete. In most cases, they have been replaced bynewer implementations with different syntax. These commands and functions should not beused in new programming. They are documented here for compatibility with existing programcode. Note that legacy commands and functions are not compatible with their replacements;though they may appear in the same program, they should never be combined. For example,you should not use a block-oriented IF with the legacy line-oriented ELSE, or attempt tomanipulate a bitstring created with a $BIT function using a $ZBIT function, or vice versa.CommandsThe following legacy commands have been replaced by new command syntax:• FOR• IF• ELSE• DO (without an argument)• ZQUITThe legacy IF, ELSE, and FOR commands do not use curly brace block structure syntax.Instead, they execute commands that appear on the same program line. They are thus muchmore restricted as to line formatting than the newer block-oriented versions of these commands.In addition, the legacy IF command cannot use the ELSEIF clause, and uses the $TESTspecial variable.The legacy argumentless DO uses a period prefix syntax to indicate block structure. Thissyntax has been superseded and is not compatible with curly brace syntax. The argumentlessform of DO should not be used for future coding.The ZQUIT command has been replaced by ZTRAP $ZERROR. Refer to the ZTRAPcommand for further details.Functions• The following legacy functions have been replaced by the new $BIT functions:$ZBITAND, $ZBITCOUNT, $ZBITFIND, $ZBITGET, $ZBITLEN, $ZBITNOT,$ZBITOR, $ZBITSET, $ZBITSTR, $ZBITXOR.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 739


Legacy Commands and Functions• The following legacy functions have been replaced by SYS.Process class methods:$ZUTIL(67,0), $ZUTIL(67,1), $ZUTIL(67,4), $ZUTIL(67,5), $ZUTIL(67,6),$ZUTIL(67,7), $ZUTIL(67,8), $ZUTIL(67,9), $ZUTIL(67,10), $ZUTIL(67,11),$ZUTIL(67,12), $ZUTIL(67,13), $ZUTIL(67,14), $ZUTIL(67,15).• The following legacy function is no longer needed to distinguish Windows platforms:$ZUTIL(100).• The following legacy function is no longer needed for <strong>Caché</strong> upgrades: $ZUTIL(113).• The following legacy function supports the obsolete ViewPoint metric counters:$ZUTIL(133).DO (legacy version)Argumentless: executes the block of code that immediately follows it in the same program.DO:pc. blockcommand. blockcommandnextcommandArgumentspcblockcommandnextcommandOptional — A postconditional expression.One or more <strong>Caché</strong> <strong>ObjectScript</strong> commands executed as acode block. Note the presence of a period (.) prefix before eachcommand in this block. Comments and blank lines must alsohave a period prefix.The next <strong>Caché</strong> <strong>ObjectScript</strong> command following the DO codeblock. This is the first line of code after the argumentless DOthat is not prefixed by a period.740 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


DescriptionDO (legacy version)Note:This page describes the legacy argumentless DO command. The argumentless versionof the DO command is obsolete as of <strong>Caché</strong> 4.0, and should not be used in newprogramming. It is described here solely for compatibility with legacy applications.The legacy argumentless DO command uses a period prefix to group lines of codetogether into an code block. Curly braces are not used and line formatting is restrictive.This syntax has been superseded by the curly brace syntax. Argumentless DOis no longer needed within IF or FOR commands, and the DO:pc operation has beensuperseded by the block-structured IF command. This syntax is not compatible withcurly brace syntax; therefore, current <strong>Caché</strong> block structure commands such as IFand FOR that use curly brace syntax may not be used within an argumentless DOcode block.The argumentless DO command executes a block of code that immediately follows it in thesame program. Argumentless DO blocks can be nested, and a postconditional expression onthe DO command can be used to determine whether or not to execute a code block.<strong>Caché</strong> executes the block of code that immediately follows the DO command, then executesthe next command after that block of code.The lines of code executed by an argumentless DO must be written using a special blockstructure syntax. This syntax uses periods (.) at the beginning of code lines. This blockstructure syntax is used only with the argumentless DO command.You can specify the argumentless DO with a postconditional expression. If the postconditionalexpression tests FALSE (0), <strong>Caché</strong> skips the immediately following block of code (and anynested blocks of code within it) and continues execution at the same line level as the DOcommand.Argumentless DO Block StructureBecause block structures immediately follow argumentless DO commands, you can use themto make your programs easier to read and maintain. As a rule, you should consider usingblock structures to replace short routines that are called only once and that might otherwisebe spread throughout your code. The placement of block structures after their related DOcommands makes it easier to find them. The obvious levels of the structures themselves makeit easier to read the code.A block structure consists of one or more blocks of code, with each block consisting of oneor more lines on the same level of nesting. All of the lines on a given level are distinguishedby having the same number of periods (.) as prefix to the line of code.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 741


Legacy Commands and FunctionsCode Block SyntaxPeriods used to indicate the lines belonging to a code block take the following syntax:• The argumentless DO command should be the last command on its code line. It may befollowed, after one or more whitespace characters, by a comment indicator character (;or //) on the same line.• The code line immediately following the argumentless DO command, and every linewithin the block of code must have a period prefix, even if it is a comment line or a blankline.• The periods must prefix the code line. Therefore, no commands or comments may appearbefore the periods or between the periods on a code line.• The period must be indented. That is, it cannot be in the first column of the code line.Usually, the initial period is indented to the same level as the code line containing theargumentless DO command.• Nested code blocks mark each level of nesting by using additional prefix periods. Toindicate nesting, place the first period at the level of the code line containing the outermostDO, and indent with additional periods for each additional level of nesting.• A code block cannot contain labels. It can contain comment lines and blank lines, butthese lines must be prefixed by a period, following the same rules as code lines.• A period must be followed by at least one whitespace character (a blank space or tab).• This space character must be followed by either a command keyword, another prefixperiod (.), a comment indicator (; or //), or a line return. Therefore, line breaks within acommand should not be used with this syntax.• Period prefix code blocks should not be combined with code blocks delineated by curlybraces.NestingPeriod prefix code blocks can be nested within each other. Because the lines belonging to agiven code block all have the same number of prefix periods, you can easily visually distinguishthe contents of each block.When viewed in a listing, the lines in nested code blocks appear indented relative to eachother. For example, the lines in an inner block contain one more prefix period character thanthe lines in the outer block that contains it.742 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


When a block ends, as indicated by a line at with fewer prefix periods than the current line,<strong>Caché</strong> <strong>ObjectScript</strong> issues an implicit QUIT that exits the block of code, and resumes executionat the previous level. You can code an explicit QUIT command as the last line of the block,but it is not necessary.VariablesAll code blocks share the same local variables. Therefore, you can supply a value to an innerblock by setting a variable before invoking that code block level. Similarly, any results fromthe execution of an inner block can be preserved at the next higher level by changing thevalues of shared local variables.The $TEST special variable is handled differently by argumentless DO, than by a DO commandcalling a subroutine or procedure. The argumentless DO preserves the initial value of$TEST during execution of its code block. If the block includes a command (such as a legacyIF command, or a timed OPEN) that resets the value of $TEST, this change is not passedback to the next higher level.ArgumentspcAn optional postconditional expression. <strong>Caché</strong> executes the command if the postconditionalexpression is true (evaluates to a non-zero numeric value). <strong>Caché</strong> does not execute the commandif the postconditional expression is false (evaluates to zero). For further details, referto Command Postconditional Expressions in Using <strong>Caché</strong> <strong>ObjectScript</strong>.blockcommandOne or more <strong>Caché</strong> <strong>ObjectScript</strong> commands executed as a code block. Each blockcommandline (including comments and blank lines) must be prefixed by one or more periods, asspecified in the Code Block Syntax.ExamplesDO (legacy version)Note:Note that the following examples use the legacy versions of the IF and FOR commands.Commands that delineate a block of code using curly braces (such as thecurrent version of IF and FOR) do not need to use the argumentless DO, and arenot compatible with period prefix syntax.In the following example, the two argumentless DO commands each invoke a block of code.Which DO is executed and, consequently, which block is invoked depends on which operationthe user requests, as determined by the IF command. In each case, the result is passed back<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 743


Legacy Commands and Functionsto the WRITE command through the same shared local variable. The first block (which calculatesthe square of an integer) contains an implicit QUIT while the second block (whichcalculates the cube of an integer) contains an explicit QUIT.Start ; Square or cube an integer.READ !,"Square (S) or cube (C): ",op QUIT:op=""READ !,"Integer: ",num QUIT:num=""IF (op["S")!(op["s") DO. SET result=num*num ; Square block. WRITE !,"Result: ",resultELSE DO. SET result=num*num*num ; Cube block. WRITE !,"Result: ",result. QUITGOTO StartIn the following example, the argumentless DO repeatedly executes the code block until theFOR control variable (i) equals the value of y.FOR i=1:1:y DO. SET z=z*x. WRITE !,z. QUITThe following example shows nested code blocks in <strong>Caché</strong> <strong>ObjectScript</strong>, using implicit QUITcommands to end each block.MyRoutine ; Routine labelWRITE !,"At top level" ; Mainline code (Level count = 0)DO. ; Outermost block (Level count = 1).. DO. . ; Inner block 1 (Level count = 2). .. . DO. . . ; Inner block 2 (Level count = 3). . .. . ; (Level count = 2). ; (Level count = 1).. QUIT ; (Level count = 0)WRITE !,"Back at top level" ; Mainline code resumesAs shown in the preceding example, the first argumentless DO begins execution of the linesin the outermost block of code. <strong>Caché</strong> <strong>ObjectScript</strong> saves the line level at which the DOresides. If <strong>Caché</strong> <strong>ObjectScript</strong> encounters subsequent argumentless DO commands, it executesthe next inner block of code and increments the line level by one for each such command.When it finds an implicit or explicit QUIT in a block, <strong>Caché</strong> <strong>ObjectScript</strong> decrements theline level count by one and continues execution at the command that follows the DO for thatblock.744 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


See Also• DO command• $TEST special variableFOR (legacy version)FOR (legacy version)Executes a command loop repeatedly, testing at the beginning of each loop.FOR variable=forparameter,... commandF variable=forparameter,... commandwhere forparameter can be:exprstart:incrementstart:increment:endand command is one or more <strong>Caché</strong> <strong>ObjectScript</strong> commands on the same program line. Thiscommand (or commands) are executed repeatedly, based on the FOR test.ArgumentsvariableexprstartincrementendOptional — A counter variable for the FOR loop.Optional — The value of variable before executing the loopcommands.Optional — The value of variable on the first iteration of the FORloop.Optional — The value used to increment variable after each iterationof the FOR loop.Optional — The value used to terminate the FOR loop.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 745


Legacy Commands and FunctionsDescriptionNote:This page describes the legacy version of the FOR command. This version is obsoleteas of <strong>Caché</strong> 4.0, and should not be used in new programming. It is described heresolely for compatibility with legacy applications.The legacy FOR command is line-oriented; the loop it executes consists of commandsthat follow it on the same program line. Curly braces are not used and line formattingis restrictive. The new FOR command is block structured; the loop it executes consistsof commands found within the curly braces that follow the FOR command. Lineformatting (white space, line breaks) is unrestrictive.The FOR command has two basic forms:• Without an argument• With an argumentFOR Without an ArgumentFOR without an argument executes the command(s) that follow it on the same line indefinitely.<strong>Caché</strong> repeats these commands until it encounters a QUIT or GOTO command.The FOR keyword without an argument must be separated from the command that followsit by at least two blank spaces.FOR With an ArgumentThe action FOR performs depends on the argument form you use.FOR variable=expr executes the commands that follow it on the same line once, settingvariable to the value of expr.FOR variable=start:increment executes the commands that follow it on the same line indefinitely.On the first iteration, <strong>Caché</strong> sets variable to the value of start. Each execution of theFOR command increments the variable value by the specified increment value. <strong>Caché</strong> repeatsthe commands until it encounters a QUIT or GOTO command.FOR variable=start:increment:end sets variable to the value of start. <strong>Caché</strong> then executesthe commands that follow it on the same line based on the conditions described in this table:746 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


FOR (legacy version)increment is positiveIf start>end, do not execute FOR. Whenvariable > (end-increment), or if <strong>Caché</strong>encounters a QUIT or GOTO command,stop.increment is negativeIf start


Legacy Commands and FunctionsExamplesArgumentless FORIn the following example, demonstrating argumentless FOR, the user is prompted repeatedlyfor a number that is then passed to the Calc subroutine by the DO command. The FOR loopterminates when the user enters a null string (presses ENTER without inputting a number),which causes the QUIT command to execute. The argumentless FOR keyword must be followedby two (or more) spaces.FOR READ !,"Number: ",num QUIT:num="" DO Calc(num)Using FOR variable=exprWhen you specify variable=expr, <strong>Caché</strong> executes the FOR command(s) once. The value inexpr can be a literal or any valid expression. If you specify an expression, it must evaluateto a single numeric value.In the following example, the WRITE command on the line with the FOR command executesonce, with num having the value 4. It writes the number 12:SET val=4FOR num=val WRITE num*3 QUITUsing FOR variable=start:increment:endThe arguments start, increment, and end specify a start, increment, and end value, respectively.All three are evaluated as numbers. They can be integer or real, positive or negative. If yousupply string values, they are converted to their numeric equivalents at the start of the loop.When <strong>Caché</strong> first enters the loop, it assigns the start value to variable and compares thevariable value to the end value. If the variable value is less than the end value (or greaterthan it, in the case of a negative increment value), <strong>Caché</strong> executes the loop commands. Itthen updates the variable value using the increment value. (The variable value is decrementedif a negative increment is used.)Execution of the loop continues until the incrementing of the variable value would exceed(not just equal) the end value (or until <strong>Caché</strong> encounters a QUIT or GOTO). At that point,to prevent variable from exceeding end, <strong>Caché</strong> suppresses variable assignment and loopexecution ends. If the increment causes the variable value to equal the end value, <strong>Caché</strong>executes the FOR loop one last time and then terminates the loop.The following code executes the WRITE command repetitively to output, in sequence, allof the characters in string1, except for the last one. Even though the end value is specified as748 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


len-2, only the last character will be skipped. This is because the loop is terminated only whenthe variable value exceeds (not just matches) the end value.SET len=$LENGTH(string1)FOR index=1:1:len-2 WRITE $EXTRACT(string1,index)Using FOR variable=start:incrementIn this form of the FOR command there is no end value; the commands following the FORmust contain a QUIT or GOTO command to terminate the loop. In many cases, the FORinvokes a DO loop, which contains the QUIT or GOTO command.The start and increment values are evaluated as numbers. They can be integer or real, positiveor negative. If string values are supplied, they are converted to their numeric equivalents atthe start of the loop. <strong>Caché</strong> evaluates the start and increment values when it begins executionof the loop. Any changes made to these values within the loop are ignored.When <strong>Caché</strong> first enters the loop, it assigns the start value to variable and executes the loopcommands. It then updates the variable value using the increment value. (The variable valueis decremented if a negative increment is used.) Execution of the loop continues until <strong>Caché</strong>encounters a QUIT or GOTO within the loop.The following example illustrates use of the FOR variable=start:increment form to computean average for a series of user-supplied numbers. The postconditional QUIT is included toterminate execution of the loop when the user enters a null string (that is, presses ENTERwithout inputting a value). When the postconditional expression (num="") tests TRUE, <strong>Caché</strong>executes the QUIT and terminates the DO loop.The loop counter (the i variable) is used to keep track of how many numbers have beenentered. i is initialized to 0 because the counter increment occurs after the user inputs anumber. <strong>Caché</strong> terminates the loop when the user enters a null. After the loop is terminated,the SET command references i (as a local variable) to calculate the average.SET sum=0FOR i=0:1 DO AverageloopSET average=sum/iAverageloopREAD !,"Number: ",numQUIT:num=""SET sum=sum+numFurther Examples of FOR with Increment SyntaxFOR (legacy version)The following example of the FOR variable=start:increment form prompts the user for anumber and then passes the number and the current value of x to the Calc subroutine invokedby the DO command. The value of x is initialized to 1 and is incremented by 1 for each exe-<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 749


Legacy Commands and Functionscution of the loop. The FOR loop terminates when the user presses ENTER, which causesthe QUIT command to execute.FOR x=1:1 READ !,"Number: ",num QUIT:num="" DO Calc(num,x)Calc(a,b)The following example of the FOR variable=start:increment:end form prompts the user fora number and then passes the number to the Calc subroutine invoked by DO. The value of xis initialized to 1 and is incremented by 1 for each execution of the loop. The FOR loop terminateseither when the value of x would exceed the end value (3) or when the user pressesENTER, causing the QUIT command to execute.MainloopFOR x=1:1:3 READ !,"Number: ",num QUIT:num="" DO Calc(num)Calc(a)The following example of the FOR variable=start:increment:end form shows a FOR loopwhere the WRITE command is never executed, since the first value of i (10) is already greaterthan the end value (1) minus the increment value (1).FOR i=10:1:1 WRITE iThe following example shows a FOR loop that executes the WRITE command 10 timesthen completes with i=10.FOR i=1:1:10 WRITE iThe following example shows a FOR loop that executes the WRITE command 10 timesthen completes with i=11.SET i=1FOR i=1:0:10 WRITE i,! SET i=i+1Using FOR with Multiple forparametersA single FOR command can contain both types of parameter syntax. The following is anexample of FOR with multiple forparameters. The first forparameter is the expr syntax. Thesecond forparameter is the start:increment:end syntax. The two forparameters are separatedby a comma. The first time through the FOR, <strong>Caché</strong> uses the expr syntax, and invokes theTest subroutine with x equal to the value of y. In the second (and subsequent) iterations,<strong>Caché</strong> uses the start:increment:end syntax. It sets x to 1, then 2, etc. On the final iteration,x=10.MainloopFOR x=y,1:1:10 DO TestTest750 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


FOR (legacy version)Incrementing with Argumentless FORThe argumentless FOR operates the same as the FOR variable=start:increment form. Theonly difference is that it does not provide a way to keep track of the number of loop executions.Two (or more) spaces are required after the FOR keyword in an argumentless FOR command.The following example shows how the previous loop counter example might be rewrittenusing the argumentless FOR. The assignment i=i+1 replaces the loop counter. Note the twospaces following the argumentless FOR keyword.Average2loopSET sum=0SET i=0FOR READ !,"Number: ",num QUIT:num="" SET sum=sum+num,i=i+1SET average=sum/iWRITE !!,"Average is: ",averageQUITNotesFOR and WatchpointsYou have limited use of watchpoints with FOR. If you establish a watchpoint for the control(index) variable of a FOR command, <strong>Caché</strong> triggers the specific watchpoint action only onthe initial evaluation of each FOR command argument. This restriction is motivated by performanceconsiderations.The following example contains three kinds of FOR command arguments for the watchedvariable X: a range, with initial value, increment, and limit (final value); a single value; anda range with initial value, increment, and no limit. Breaks occur when X has the initial values1, 20, and 50.USER>ZBREAK *XUSER>FOR X=1:1:10,20,50:2 SET T=X QUIT:X>69USER 2f0>wX=1USER 2f0>gUSER>FOR X=1:1:10,20,50:2 SET T=X QUIT:X>69USER 2f0>wT=10X=20USER> 2f0>gUSER>FOR X=1:1:10,20,50:2 SET T=X QUIT:X>69USER 2f0>wT=20X=50USER 2f0>gUSER>wT=70X=70<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 751


Legacy Commands and FunctionsTerminating a FOR Loop with QUIT or GOTOA FOR loop is terminated by a QUIT only if the QUIT appears as one of the loop commands.If <strong>Caché</strong> encounters a QUIT in a subroutine called by the DO command, it terminates onlythe subroutine, not the FOR loop itself.A FOR loop is terminated by a GOTO that appears anywhere within the loop. If a GOTOexits from a subroutine called by the DO command, <strong>Caché</strong> terminates both the subroutineand the FOR loop.See Also• FOR command• DO (legacy version) command• GOTO command• QUIT command752 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


IF (legacy version)IF (legacy version)Evaluates an expression, then selects which line of code to execute based on the truth valueof the expression.IF expression1 command1command2DescriptionNote:This page describes the legacy version of the IF command. This version is obsoleteas of <strong>Caché</strong> 4.0, and should not be used in new programming. It is described heresolely for compatibility with legacy applications.The legacy IF command is line-oriented; commands to be executed must follow iton the same program line. Curly braces are not used and line formatting is restrictive.The new IF command is block structured; the block it executes consists of commandsfound within the curly braces that follow the IF command. Line formatting (whitespace, line breaks) is unrestrictive. The new version of IF does not use the $TESTspecial variable.The old and new forms of IF and ELSE are syntactically different and should notbe combined; therefore, an IF of one type should not be paired with an ELSE of theother type.The IF command has two forms:Without an argumentWith an argumentIF Without an ArgumentIF without an argument executes the commands that follow it on the same line if the currentvalue of the $TEST variable is TRUE (non-zero). If $TEST is FALSE (0), <strong>Caché</strong> ignoresthe remaining commands and continues execution with the next line.IF With an ArgumentIF with the argument expression1 executes the commands that follow it on the same line ifexpression1 evaluates to TRUE (non-zero). (<strong>Caché</strong> also sets $TEST to TRUE.) If expression1evaluates to FALSE, <strong>Caché</strong> sets $TEST to FALSE (0), ignores the remaining commands onthat line, and continues execution with the next line.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 753


Legacy Commands and FunctionsThe expression1 argument can take the form of a single expression or a comma-separatedlist of expressions. For an expression list, <strong>Caché</strong> evaluates the individual expressions in leftto right order. It stops evaluation if it encounters an expression that is FALSE. If all expressionsevaluate to TRUE, <strong>Caché</strong> executes the command(s) following the expression1 argument onthat line. If any expression evaluates to FALSE, <strong>Caché</strong> ignores any remaining expressions,and does not execute the commands on that line, but continues execution at the next line ofcode.See Also• IF command• DO (legacy version) command• GOTO command• QUIT command• $TEST special variableZQUIT (legacy command)Exits a program with error handling.ZQ:pc expressionwherepcexpressionOptional — A postconditional expression.Optional — An expression that evaluates to an integer greater than0.<strong>Caché</strong> platforms recognize only the ZQ abbreviation for ZQUIT.754 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


DescriptionZQUIT (legacy command)Note:This page describes the legacy ZQUIT command. The ZQUIT command is obsoleteas of <strong>Caché</strong> 5.1, and should not be used in new programming. It is described heresolely for compatibility with legacy applications. New Programming should use theZTRAP command with the $ZERROR argument to pass control between errorhandlers. A ZQUIT command in new procedure code will result in a error. Refer to the ZTRAP command for further details.The ZQUIT command exits a coded routine and provides explicit control for error handling.Each time a DO, FOR, or XECUTE command is executed, or a user-defined function isinvoked, <strong>Caché</strong> places return information on the program stack (sometimes called the "callstack"). ZQUIT provides a mechanism whereby a nested error-handling routine can passcontrol to a higher level error handler. ZQUIT re-signals the error condition and causes <strong>Caché</strong>to unwind the program (call) stack.ZQUIT is similar to the QUIT command, but it provides explicit control for error handling.Unlike the QUIT command, ZQUIT can be used only in a coded routine. <strong>Caché</strong> ignoresZQUIT when entered from the programmer prompt.ZQUIT has two forms:• Without an argument.• With an argument.ZQUIT Without an ArgumentArgumentless ZQUIT clears the entire stack.ZQUIT With an ArgumentZQ expression unwinds the stack to another call stack level with a $ZTRAP error handler.The value of expression specifies the number of handler-specified stack levels ZQUITunwinds. If you use 1 as expression, <strong>Caché</strong> unwinds the stack to the first encountered $ZTRAPhandler. If you use 2 as expression, <strong>Caché</strong> unwinds the stack to the second encountered$ZTRAP handler, and so on.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 755


Legacy Commands and FunctionsArgumentspcAn optional postconditional expression. <strong>Caché</strong> executes the command if the postconditionalexpression is true (evaluates to a non-zero numeric value). <strong>Caché</strong> does not execute the commandif the postconditional expression is false (evaluates to zero). For further details, referto Command Postconditional Expressions in Using <strong>Caché</strong> <strong>ObjectScript</strong>.expressionAny valid <strong>Caché</strong> <strong>ObjectScript</strong> expression that evaluates to an integer greater than 0. <strong>Caché</strong>platforms use the settings of $ZTRAP to clear the program stack back to the setting indicatedby the resulting integer.NotesBehavior of Argumentless ZQUITWhen specified with no arguments, ZQUIT unwinds the entire stack. Execution continuesat the main program level; that is, the level at which the job began, in either programmermode or application mode.ZQUIT does not change the flow of control. Execution continues with the <strong>Caché</strong> <strong>ObjectScript</strong>command that follows ZQUIT. To mimic the errortrap behavior of M/11, an error processingroutine should end with the commandsZQ QUITNote that there are two spaces after ZQ.Here the QUIT command returns to programmer mode if the job began in programmer modeor it exits if the job began in application mode. To log application errors, end your errortrapcode with:ZQ GOTO ^%ETAgain, note the two spaces after ZQ.Behavior of ZQUIT with an ArgumentWhen specified with an argument, ZQUIT does not clear the entire stack, but instead clearsit back one or more levels at which the $ZTRAP special variable was set. The number oflevels is specified by the expression argument, which must evaluate to an integer greater than0. $ZTRAP directs error trapping to the routine to which it is set.756 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


ZQUIT (legacy command)For example:ZQ 1clears the stack back to the previous level at which $ZTRAP was set. Passing an argumentof "2" to ZQUIT clears the stack back to the second to last level at which $ZTRAP was set,and so on.<strong>Caché</strong> then transfers control to the errortrap routine currently set in $ZTRAP. When thaterrortrap routine quits, control reverts to the same place that it would on a QUIT from thesubroutine that set $ZTRAP.If <strong>Caché</strong> should find an error handler specified by the $ETRAP special variable at a stacklevel before reaching the stack level of the specified $ZTRAP error handler, <strong>Caché</strong> passescontrol to that $ETRAP error handler. If the $ETRAP error handler cannot dismiss the error,the $ZTRAP error handler that issued the original ZQUIT gains control again. At that point,the $ZTRAP error handler can use a GOTO command to transfer control to the $ZTRAPhandler originally specified.Note:Do not use an indirect GOTO (for example, ZQ 1 GOTO @$ZT) within a procedureor an object method with the default ProcedureBlock attribute. This results in acompile error, because you cannot use a GOTO to exit a procedure. Existing routinesthat use this construct should not be converted to procedures. Object methods thatuse this construct must be excepted from the ProcedureBlock attribute.You can alter this error-return sequence by using ZQUIT in any of the following ways:• ZQ 1 QUIT — Returns to the caller of the subroutine that set the previous error trap.• ZQ 1 GOTO @$ZT — Invokes the previous errortrap routine. (See Note above.)• ZQ QUIT — Either halts the application or enters programmer mode with an emptyprogram stack. Note the two spaces between ZQUIT and QUIT.• ZQ GOTO ^routine — Clears the program stack and resumes execution at the specifiedtoplevel routine that is typically a function driver. Note the two spaces between ZQUITand GOTO.See Also• QUIT command• ZTRAP command• $ZUTIL(68,30) Sets Error-Handling Behavior for the Current Process function<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 757


Legacy Commands and Functions• $ZTRAP special variable• Error Handling in Using <strong>Caché</strong> <strong>ObjectScript</strong>$ZBITAND (legacy function)Bitstring function – AND.$ZBITAND(bitstring1,bitstring2)DescriptionThis page describes the legacy function $ZBITAND. It is described here for compatibilitywith legacy applications.$ZBITAND returns a bitstring formed by the (bitstring1 AND bitstring2) operation. Thelength of the resulting bitstring equals the length of the shorter of the two specified bitstrings.The value of the resulting bitstring is 1 in all positions where both bitstrings held a 1, and 0in all other positions.ExampleIf bitstring1 = [0,1,1,0] and bitstring2 = [0,1,0,0], then the result of $ZBITAND would be[0,1,0,0]. That is:Position 1: 0 and 0 = 0Position 2: 1 and 1 = 1Position 3: 1 and 0 = 0Position 4: 0 and 0 = 0$ZBITCOUNT (legacy function)Bitstring function – COUNT.$ZBITCOUNT(bitstring)DescriptionThis page describes the legacy function $ZBITCOUNT. It is described here for compatibilitywith legacy applications.758 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZBITFIND (legacy function)$ZBITCOUNT returns the number of ON bits (1' s) in bitstring.ExampleIf bitstring = [0,0,1,1,0], then the result of $ZBITCOUNT would be 2.See Also• $BITCOUNT function$ZBITFIND (legacy function)Bitstring function – FIND.$ZBITFIND(bitstring, truthval, position)ParametersbitstringtruthvalpositionA bit string.Binary value (0 or 1).Optional — Specifies a starting bit position in bitstring.DescriptionThis page describes the legacy function $ZBITFIND. It is described here for compatibilitywith legacy applications.$ZBITFIND returns the position immediately after the first bit in bitstring that equals truthval.position specifies an optional starting position for the search. If position is omitted, the searchstarts at position 1.If truthval is not found, $ZBITFIND returns zero.$ZBITFIND is similar to the $FIND function in that the returned position is the next oneafter the matching bit. This permits a loop of the form:FindabitFOR p=1:0 {SET p=$ZBITFIND(bstring,1,p)QUIT:´pDO Foundone}Foundone<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 759


Legacy Commands and FunctionsParameterstruthvalBinary value (0 or 1).positionSpecifies a starting bit position in bitstring. The default is 1. Bits are counted left-to-right,with the first bit counted as number 1.ExamplesNote that the result is the position immediately after the bit that matches truthval.Given the bitstring[0,0,1,1,0]:If truthval=0 then the result of $ZBITFIND would be position 2.If truthval=1 then the result of $ZBITFIND would be position 4.If truthval=0 and position=2, then the result of $ZBITFIND would be position 3.If truthval=0 and position=3, then the result of $ZBITFIND would be position 6.$ZBITGET (legacy function)Bitstring function – GET.$ZBITGET(bitstring, position)ParametersbitstringpositionThe bit string to be evaluated.Value or expression that evaluates to a positive integer.DescriptionThis page describes the legacy function $ZBITGET. It is described here for compatibilitywith legacy applications.$ZBITGET returns the bit value (0 or 1) at the specified bit position within bitstring. Thefirst bit position is 1.760 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


ParameterspositionValue or expression that evaluates to a positive integer. Bit positions are counted left-to-right,with the first bit counted as number 1. If position is set to zero, or to an integer larger thanthe length ofbitstring, a error occurs.ExamplesGiven the bitstring [0,0,1,1,0]:If position=1, then the result of $ZBITGET would be 0.If position=2, then the result of $ZBITGET would be 0.If position=3, then the result of $ZBITGET would be 1.If position=4, then the result of $ZBITGET would be 1.If position=5, then the result of $ZBITGET would be 0.If position=6, then $ZBITGET would generate a error.See Also• $BIT function• $ZBITSET (legacy function)$ZBITLEN (legacy function)$ZBITLEN (legacy function)Bitstring function – LENGTH.$ZBITLEN(bitstring)DescriptionThis page describes the legacy function $ZBITLEN. It is described here for compatibilitywith legacy applications.$ZBITLEN returns the number of bits in bitstring.ExampleIf bitstring=[0,0,1,1,0], then the result of $ZBITLEN would be the length 5.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 761


Legacy Commands and FunctionsSee Also• $BITCOUNT function$ZBITNOT (legacy function)Bitstring function – NOT$ZBITNOT(bitstring)DescriptionThis page describes the legacy function $ZBITNOT. It is described here for compatibilitywith legacy applications.$ZBITNOT returns a permutation of bitstring with each of its bit positions inverted -- thatis, 1s become 0s, and 0s become 1s.ExampleIf bitstring=[0,0,1,1,0], then the result of $ZBITNOT would be a bitstring with the value[1,1,0,0,1].See Also• $BITLOGIC function$ZBITOR (legacy function)Bitstring function – OR.$ZBITOR(bitstring1,bitstring2)DescriptionThis page describes the legacy function $ZBITOR. It is described here for compatibilitywith legacy applications.$ZBITOR returns a bitstring formed by the (bitstring1 OR bitstring2) operation. The lengthof the resulting bitstring equals the longer length of the two bitstrings. The value of the762 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


esulting bitstring is 1 in all positions where either or both of the bitstrings held a 1, and 0 inall other positions. Bitstrings are compared left-to- right.ExampleIf bitstring1=[0,0,1,1,0] and bitstring2=[0,1,1,0], then the result of $ZBITOR would be[0,1,1,1,0]. That is:Position 1: 0 OR 0 = 0Position 2: 0 OR 1 = 1Position 3: 1 OR 1 = 1Position 4: 1 OR 0 = 1Position 5: 0 OR null = 0See Also• $BITLOGIC function• $ZBITXOR (legacy function) function• $ZBITAND (legacy function) function$ZBITSET (legacy function)$ZBITSET (legacy function)Bitstring function – SET.$ZBITSET(bitstring,position,truthval)ParametersbitstringpositiontruthvalThe bitstring to be set.Positive integer that specifies a location in bitstring.Single-bit binary value (0 or 1).DescriptionThis page describes the legacy function $ZBITSET. It is described here for compatibilitywith legacy applications.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 763


Legacy Commands and Functions$ZBITSET returns a permutation of bitstring in which the bit at position is set to truthval(0or 1).ParameterspositionPositive integer that specifies a location in bitstring. It can be specified as a value, a variable,or an expression. Bits are counted left-to-right, with the first bit counted as number 1.truthvalSingle-bit binary value (0 or 1).ExampleThe following example creates a bitstring using $ZBITSTR, then sets a bit using $ZBITSET.SET bitstring=$ZBITSTR(5,0)SET newbitstring=$ZBITSET(bitstring,3,1)If bitstring=[0,0,0,0,0], position=3, and truthval=1, then the result of $ZBITSET would bea bitstring with the value [0,0,1,0,0].See Also• $BIT function• $ZBITGET (legacy function)$ZBITSTR (legacy function)Bitstring function – STRING.$ZBITSTR(size,truthval)ParameterssizetruthvalPositive integer.Optional — Specifies a binary value (0 or 1) for the returned bits.764 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


DescriptionThis page describes the legacy function $ZBITSTR. It is described here for compatibilitywith legacy applications.$ZBITSTR returns a bitstring whose length is size bits long, with all of its bits set to truthval.ParameterssizePositive integer. The integer must be in the range 1 to 262,128 bits (32766 x 8). It can bespecified as a value, a variable, or an expression.truthvalSpecifies a binary value (0 or 1) for the returned bits. If truthval is 0, or is omitted, all thebits are set to 0 (OFF). If truthval is 1, all the bits are set to 1 (ON).ExampleThe following example creates a bitstring named bs:SET bs=$ZBITSTR(4,1)If size=4 and truthval=1, then the result of $ZBITSTR would be a bitstring with the value[1,1,1,1].$ZBITXOR (legacy function)Bitstring function – XOR.$ZBITXOR(bitstring1,bitstring2)Description$ZBITXOR (legacy function)This page describes the legacy function $ZBITXOR. It is described here for compatibilitywith legacy applications.$ZBITXOR returns a bitstring formed by the (bitstring1 XOR bitstring2) operation. Thelength of the resulting bitstring equals the shorter length of the two bitstrings.The following table shows the four possible results obtained by performing the XOR operationon two bits (b1 and b2):<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 765


Legacy Commands and Functionsb10011b20101equals0110ExampleIf bitstring 1=[0,0,1,1,0] and bitstring 2=[0,1,1,0], then the result of $ZBITXOR would be[0,1,0,1]. That is:Position 1: 0 XOR 0 = 0Position 2: 0 XOR 1 = 1Position 3: 1 XOR 1 = 0Position 4: 1 XOR 0 = 1Position 5: 0 XOR null = nullSee Also• $BITLOGIC function• $ZBITOR (legacy function) function• $ZBITAND (legacy function) function$ZUTIL(67,0) (legacy function)Returns the activity state of a specified process.$ZUTIL(67,0,pid)$ZU(67,0,pid)ParameterspidThe process ID number.766 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


DescriptionThis page describes the legacy function $ZUTIL(67,0), which has been superseded by theSYS.Process class methods. (Refer to the <strong>Caché</strong> Class <strong>Reference</strong> for further details.)$ZUTIL(67,0) is described here for compatibility with legacy applications.$ZUTIL(67,0,pid) returns 2 if the process is active, 1 if the process is dead but the pid is stillin the pidtable, 0 if the pid is not in the pidtable.The $ZUTIL(67,1,pid) function is identical, except when a value of 1 is returned:$ZUTIL(67,0,pid) leaves a dead process in the pidtable; $ZUTIL(67,1,pid) removes a deadprocess from the pidtable.ParameterspidA process ID number. The process ID of the current process is returned by the $JOB specialvariable. The System Management Portal provides a Processes option, which list the pids ofall running processes. If you specify a non-existent process, $ZUTIL(67,0) returns a valueof zero.ExampleThe following example tests the current process. It should (of course) return 2 (process isactive):WRITE $ZUTIL(67,0,$JOB)See Also• $ZUTIL(67,1) Return the Activity State of a Specified Process and Reset legacy function• $JOB special variable$ZUTIL(67,0) (legacy function)<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 767


Legacy Commands and Functions$ZUTIL(67,1) (legacy function)Returns the activity state of a specified process, and resets.$ZUTIL(67,1,pid)$ZU(67,1,pid)ParameterspidThe process ID number.DescriptionThis page describes the legacy function $ZUTIL(67,1), which has been superseded by theSYS.Process class methods. (Refer to the <strong>Caché</strong> Class <strong>Reference</strong> for further details.)$ZUTIL(67,1) is described here for compatibility with legacy applications.$ZUTIL(67,1,pid) returns 2 if the process is active, 1 if the process is dead but the pid is stillin the pidtable, 0 if thepid is not in the pidtable. If 1 is returned, $ZUTIL(67,1,pid) removesthe pid from the pidtable.The $ZUTIL(67,0,pid) function is identical, except when a value of 1 is returned:$ZUTIL(67,0,pid) leaves a dead process in the pidtable; $ZUTIL(67,1,pid) removes a deadprocess from the pidtable.ParameterspidA process ID number. The process ID of the current process is returned by the $JOB specialvariable. The System Management Portal provides a Processes option, which list the pids ofall running processes. If you specify a non-existent process, $ZUTIL(67,1) returns a valueof zero.ExampleThe following example tests the current process. It should (of course) return 2 (process isactive):WRITE $ZUTIL(67,1,$JOB)See Also• $ZUTIL(67,0) Return the Activity State of a Specified Process legacy function768 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(67,4) (legacy function)• $JOB special variable$ZUTIL(67,4) (legacy function)Returns the process state.$ZUTIL(67,4,pid)$ZU(67,4,pid)ParameterspidThe process ID number.DescriptionThis page describes the legacy function $ZUTIL(67,4), which has been superseded by theSYS.Process class methods. (Refer to the <strong>Caché</strong> Class <strong>Reference</strong> for further details.)$ZUTIL(67,4) is described here for compatibility with legacy applications.$ZUTIL(67,4,pid) returns process state information in the form x^y^z, three numeric codesseparated by caret symbols. x = pstate, an integer indicating which part of the code is executing.y = pstatebits, a bitmap which provide additional process state information. z = gstatebits, abitmap which provide information on global requests and other shared resources requestedby the process. One use of the gstatebits bitmap is to give state information on cluster locking.Process state information can also be obtained from the Processes option of the SystemManagement Portal, which lists the State for all currently running processes. The pstate,pstatebits, and gstatebits information can be obtained from the command line by running theCSTAT utility with the appropriate operand. For example, to obtain gstatebits informationcall CSTAT -p64.pstate can return the following values:pstate12345AbbreviationLOCKOPENCLOSUSEREADDefinitionThis job is in the lock code.This job is opening a device.This job is closing a device.This job is in the USE command.This job is reading from a device.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 769


Legacy Commands and Functionspstate6789101112131415161718192021AbbreviationWRTGGETGSETGKILLGORDGQRYGDEFZFHANGJOBEXAMBRDSUSPINCRBSETBGETDefinitionThis job is writing to a device.This job is in gget.This job is in gset.This job is in gkill.This job is in gorder for $ORDER.This job is in gorder for $QUERY.This job is in gdefval.This job is in a $ZF function call.This job is in the HANG command.This job is jobbing a job.This job is doing ^JOBEXAM.This job is in $ZUTIL(9) or $ZUTIL(94),broadcasting a message.This job is suspended.This job is in a $INCREMENT function call.This job is setting a bit using the $BIT functions.This job is getting a bit using the $BIT functions.pstatebits can return the following values:pstatebits1248163265256DefinitionHibernating.Networking.Network Hardening.Halting.Duplicate pid encountered.Waiting for a network answer.Global Wait set/cleared in waitdup().Net lock waiting.770 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(67,5) (legacy function)pstatebits5121024DefinitionCluster slave job waiting for net answer.The dead job has an open transaction.ParameterspidA ten-digit process ID. The process ID of the current process is returned by the $JOB specialvariable. The System Management Portal provides a Processes option, which list the pids ofall running processes. If you specify a non-existent process, $ZUTIL(67,4) returns a valueof zero.SYS.Process MethodsYou can get the pstate process information using a method of the SYS.Process class, as shownin the following example:ZNSPACE "%SYS"WRITE ##CLASS(SYS.Process).%OpenId($JOB).StateGet()See Also• $JOB special variable• see “Display Process Information” in the Managing <strong>Caché</strong> chapter of the <strong>Caché</strong> SystemAdministration Guide$ZUTIL(67,5) (legacy function)Returns the routine name of a specified process.$ZUTIL(67,5,pid)$ZU(67,5,pid)ParameterspidThe process ID number.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 771


Legacy Commands and FunctionsDescriptionThis page describes the legacy function $ZUTIL(67,5), which has been superseded by theSYS.Process class methods. (Refer to the <strong>Caché</strong> Class <strong>Reference</strong> for further details.)$ZUTIL(67,5) is described here for compatibility with legacy applications.$ZUTIL(67,5,pid) returns a string containing the routine name of the specified process. Themaximum string length is 32 characters, for either 8-bit characters or Unicode characters. Ifthere is no routine name for the process, $ZUTIL(67,5) returns a null string.The routine names of all currently running processes are listed in the Processes option of theSystem Management Portal. The routine name of the current process is stored in the $ZNAMEspecial variable.To determine which client application is running, call $ZUTIL(67,13) to return the name ofthe executable file.Both $ZUTIL(67,5) and the $ZNAME special variable return a null string for a <strong>Caché</strong> Terminalprocess. On the Processes option of the System Management Portal a <strong>Caché</strong> Terminalprocess is listed with the routine name shell.ParameterspidA process ID number. The process ID of the current process is returned by the $JOB specialvariable. The System Management Portal provides a Processes option, which list the pids ofall running processes. If you specify a non-existent process, $ZUTIL(67,5) returns a valueof zero.SYS.Process MethodsYou can get the same process information using methods of the SYS.Process class, as shownin the following example:ZNSPACE "%SYS"WRITE ##CLASS(SYS.Process).%OpenId($JOB).RoutineGet()See Also• $JOB special variable• $ZNAME special variable772 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(67,6) (legacy function)$ZUTIL(67,6) (legacy function)Returns the namespace name for a specified process.$ZUTIL(67,6,pid)$ZU(67,6,pid)ParameterspidThe process ID number.DescriptionThis page describes the legacy function $ZUTIL(67,6), which has been superseded by theSYS.Process class methods. (Refer to the <strong>Caché</strong> Class <strong>Reference</strong> for further details.)$ZUTIL(67,6) is described here for compatibility with legacy applications.$ZUTIL(67,6,pid) returns the name of the namespace in which the process in running. If theprocess is not running in a namespace, it returns a null string.The namespace names (Nspace) of all currently running processes are listed in the Processesoption of the System Management Portal. The namespace name of the current process isstored in the $ZNSPACE special variable.The maximum namespace string length is 16 characters. Namespace names are not casesensitive.<strong>Caché</strong> displays namespace names in all capital letters.ParameterspidA process ID number. The process ID of the current process is returned by the $JOB specialvariable. The System Management Portal provides a Processes option, which list the pids ofall running processes. If you specify a non-existent process, $ZUTIL(67,6) returns a valueof zero.ExampleThe following example compares the namespace names returned by $ZUTIL(67,6) and$ZNSPACE; in this case, the results should be identical:<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 773


Legacy Commands and FunctionsSET pid=$JOBIF $ZUTIL(67,6,pid)=$ZNSPACE {WRITE !,pid," is the current process" }ELSE {WRITE !,pid," is NOT the current process" }QUITSYS.Process MethodsYou can get the same process information using methods of the SYS.Process class, as shownin the following example:ZNSPACE "%SYS"WRITE ##CLASS(SYS.Process).%OpenId($JOB).NameSpaceGet()See Also• $JOB special variable• ZNSPACE command• $ZUTIL(5) Display or Switch Namespace function• $ZUTIL(90,4) Start Up in a Specified Namespace function• $ZUTIL(90,10) Test Whether a Namespace is Defined function• $ZNSPACE special variable• Configuring Namespaces in <strong>Caché</strong> System Administration Guide$ZUTIL(67,7) (legacy function)Returns the device name for the specified process.$ZUTIL(67,7,pid)$ZU(67,7,pid)ParameterspidThe process ID number.DescriptionThis page describes the legacy function $ZUTIL(67,7), which has been superseded by theSYS.Process class methods. It is described here for compatibility with legacy applications.774 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(67,7,pid) returns a string containing the current device name for the specified process.This string consists of the final characters of the device name, up to 32 characters.The device name consists of three parts separated by vertical bars: the device type, the portnumber, and the process ID. For a <strong>Caché</strong> terminal with a process ID of 748, the device namewould be |TRM|:|748. For a <strong>Caché</strong> client application (routine name JOBEXAM or %CDSrv0)with a process ID of 749, the device name would be |TCP|1972|749. 1972 is the defaultport number. The %cmtP routine returns a device name of |TCP|1972; it does not return itsown process ID because this routine responds to client requests by creating client applicationjobs and uniquely identifying them by assigning a process ID number.ParameterspidA process ID number. The process ID of the current process is returned by the $JOB specialvariable. The System Management Portal provides a Processes option, which list the pids ofall running processes. If you specify a non-existent process, $ZUTIL(67,7) returns a valueof zero.SYS.Process MethodsYou can get the same process information using methods of the SYS.Process class, as shownin the following example:ZNSPACE "%SYS"WRITE ##CLASS(SYS.Process).%OpenId($JOB).CurrentDeviceGet()See Also• $JOB special variable$ZUTIL(67,8) (legacy function)$ZUTIL(67,8) (legacy function)Returns the number of lines executed by the specified process.$ZUTIL(67,8,pid)$ZU(67,8,pid)ParameterspidThe process ID number.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 775


Legacy Commands and FunctionsDescriptionThis page describes the legacy function $ZUTIL(67,8), which has been superseded by theSYS.Process class methods. It is described here for compatibility with legacy applications.$ZUTIL(67,8,pid) returns the number of lines executed as a 32-bit signed integer, which canrepresent 10 numeric digits.ParameterspidA process ID number. The process ID of the current process is returned by the $JOB specialvariable. The System Management Portal provides a Processes option, which list the pids ofall running processes. If you specify a non-existent process, $ZUTIL(67,8) returns a valueof zero.SYS.Process MethodsYou can get the same process information using methods of the SYS.Process class, as shownin the following example:ZNSPACE "%SYS"WRITE ##CLASS(SYS.Process).%OpenId($JOB).LinesExecutedGet()See Also• $JOB special variable$ZUTIL(67,9) (legacy function)Returns the number of global references made by the specified process.$ZUTIL(67,9,pid)$ZU(67,9,pid)ParameterspidThe process ID number.776 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


DescriptionThis page describes the legacy function $ZUTIL(67,9), which has been superseded by theSYS.Process class methods. It is described here for compatibility with legacy applications.$ZUTIL(67,9,pid) returns the number of global references for the specified process as aninteger. The System Management Portal provides a Processes option, which list the numberof global references for each running process.ParameterspidA process ID number. The process ID of the current process is returned by the $JOB specialvariable. The System Management Portal provides a Processes option, which list the pids ofall running processes. If you specify a non-existent process, $ZUTIL(67,9) returns a valueof zero.SYS.Process MethodsYou can get the same process information using methods of the SYS.Process class, as shownin the following example:ZNSPACE "%SYS"WRITE ##CLASS(SYS.Process).%OpenId($JOB).Global<strong>Reference</strong>sGet()See Also• $JOB special variable$ZUTIL(67,10) (legacy function)$ZUTIL(67,10) (legacy function)Returns the job type of the specified process.$ZUTIL(67,10,pid)$ZU(67,10,pid)ParameterspidThe process ID number.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 777


Legacy Commands and FunctionsDescriptionThis page describes the legacy function $ZUTIL(67,10), which has been superseded by theSYS.Process class methods. (Refer to the <strong>Caché</strong> Class <strong>Reference</strong> for further details.)$ZUTIL(67,10) is described here for compatibility with legacy applications.$ZUTIL(67,10,pid) returns the job type as an integer.The following are available job type codes:Code12348121620242832364044485256DescriptionJob has an interactive terminal associatedwith it.Job is dedicated to a single routine with nouser interaction or other owning deviceinteraction (a background job invoked by theJOB command).Job invoked by the operating system(application mode).Control process for non-OSVMS systemsWrite daemon processGarbage collector processJournal daemon for non-OSVMS systemsEnqueue daemon for USECLUSTERSsystemsRecovery daemon for USECLUSTERSsystemsSlave write daemonISNET server daemonNet daemon(s)License monitorViewpoint serverMVB serverDTM serverDTM namespace map serverRoutine NameshellCONTROLWRTDMNGARCOLJRNDMNENQDMNSLAVWDDCPDMNDMNNETLMFMON778 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


Code606468727680848896104108116140144DescriptionShadow master serverShadow serverShadow client serverReceive daemonODBC server master processIdle JOB ServerCMT Master ServerMSM-Activate Server<strong>Caché</strong> Direct Server: a client applicationCSP Server ProcessODBC/JDBC ServerDBX daemonTask ManagerClean-up Daemon$ZUTIL(67,10) (legacy function)Routine NameJOBSRV%cmtPJOBEXAM or %CDSrv0csp.ServerEXPDMNTASKMGRCLNDMNParameterspidA process ID number. The process ID of the current process is returned by the $JOB specialvariable. The System Management Portal provides a Processes option, which list the pids ofall running processes. If you specify a non-existent process, $ZUTIL(67,10) returns a valueof zero.See Also• JOB command• $JOB special variable<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 779


Legacy Commands and Functions$ZUTIL(67,11) (legacy function)Returns the user name of the specified process.$ZUTIL(67,11,pid)$ZU(67,11,pid)ParameterspidThe process ID number.DescriptionThis page describes the legacy function $ZUTIL(67,11), which has been superseded by theSYS.Process class methods. It is described here for compatibility with legacy applications.$ZUTIL(67,11,pid) returns a string containing the name of the user that initiated the specifiedprocess. This is, in most cases, either your own login name (for terminal processes and clientapplications), or SYSTEM.ParameterspidA process ID number. The process ID of the current process is returned by the $JOB specialvariable. The System Management Portal provides a Processes option, which list the pids ofall running processes. If you specify a non-existent process, $ZUTIL(67,11) returns a valueof zero.SYS.Process MethodsYou can get the same process information using methods of the SYS.Process class, as shownin the following example:ZNSPACE "%SYS"WRITE ##CLASS(SYS.Process).%OpenId($JOB).UserNameGet()See Also• $JOB special variable780 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(67,12) (legacy function)$ZUTIL(67,12) (legacy function)Returns the name of the system for a client application.$ZUTIL(67,12,pid)$ZU(67,12,pid)ParameterspidThe process ID of a client application.DescriptionThis page describes the legacy function $ZUTIL(67,12), which has been superseded by theSYS.Process class methods. It is described here for compatibility with legacy applications.$ZUTIL(67,12,pid) returns the name of the system on which the client application is runningas a string. If the specified pid is not a client application, $ZUTIL(67,12,pid) return the nullstring.On pre-5.1 versions of <strong>Caché</strong>, the client applications include <strong>Caché</strong> SQL Manager, <strong>Caché</strong>Control Panel, <strong>Caché</strong> Studio, <strong>Caché</strong> Explorer, and <strong>Caché</strong> Configuration Manager. All of these<strong>Caché</strong> client applications appear on the <strong>Caché</strong> Control Panel as routine name %CDSrv0. Thisis also the routine name returned by $ZUTIL(67,5,pid). To determine which client applicationis running as %CDSrv0, invoke $ZUTIL(67,13,pid) to return the name of the executablefile. You can, of course, create your own client applications.The <strong>Caché</strong> Terminal (routine name “shell”) and <strong>Caché</strong> <strong>Documentation</strong> are not client applications.ParameterspidA process ID number. The process ID of the current process is returned by the $JOB specialvariable. The System Management Portal provides a Processes option, which list the pids ofall running processes. If you specify a non-existent process, $ZUTIL(67,12) returns a valueof zero.SYS.Process MethodsYou can get the same process information using methods of the SYS.Process class, as shownin the following example:<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 781


Legacy Commands and FunctionsZNSPACE "%SYS"WRITE ##CLASS(SYS.Process).%OpenId($JOB).ClientNodeNameGet()See Also• $ZUTIL(67,5) Return the Routine Name of a Process function• $ZUTIL(67,13) Return the Executable of the Client Application function• $ZUTIL(67,14) Return the Operating System Running the Client Application function• $ZUTIL(67,15) Return the IP Address of the Client Application function• $JOB special variable$ZUTIL(67,13) (legacy function)Returns the name of the executable for a client application.$ZUTIL(67,13,pid)$ZU(67,13,pid)ParameterspidThe process ID number.DescriptionThis page describes the legacy function $ZUTIL(67,13), which has been superseded by theSYS.Process class methods. It is described here for compatibility with legacy applications.$ZUTIL(67,13,pid) returns a string containing the name of the executable file (.exe file) ofthe client application. If the pid is not a client application, $ZUTIL(67,13) returns the nullstring.On pre-5.1 versions of <strong>Caché</strong>, the client applications include the <strong>Caché</strong> SQL Manager(CSQLMGR.EXE), <strong>Caché</strong> Control Panel (CCTRLPNL.EXE), <strong>Caché</strong> Studio (CSTUDIO.EXE),<strong>Caché</strong> Explorer (CExplore.exe), and the <strong>Caché</strong> Configuration Manager (CCFGUTIL.EXE).All of these <strong>Caché</strong> applications appear on the <strong>Caché</strong> Control Panel as routine name %CDSrv0.You can, of course, create your own client applications.The <strong>Caché</strong> Terminal (routine name “shell”) and <strong>Caché</strong> <strong>Documentation</strong> are not client applications.782 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


ParameterspidA process ID number. The process ID of the current process is returned by the $JOB specialvariable. The System Management Portal provides a Processes option, which list the pids ofall running processes. If you specify a non-existent process, $ZUTIL(67,13) returns a valueof zero.SYS.Process MethodsYou can get the same process information using methods of the SYS.Process class, as shownin the following example:ZNSPACE "%SYS"WRITE ##CLASS(SYS.Process).%OpenId($JOB).ClientExecutableNameGet()See Also• $JOB special variable$ZUTIL(67,14) (legacy function)$ZUTIL(67,14) (legacy function)Returns the operating system running a client application.$ZUTIL(67,14,pid)$ZU(67,14,pid)ParameterspidThe process ID number of a <strong>Caché</strong> client application.DescriptionThis page describes the legacy function $ZUTIL(67,14), which has been superseded by theSYS.Process class methods. (Refer to the <strong>Caché</strong> Class <strong>Reference</strong> for further details.)$ZUTIL(67,14) is described here for compatibility with legacy applications.$ZUTIL(67,14,pid) returns the operating system information for a client application as ahexadecimal byte string. Use the ZZDUMP command to display this information.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 783


Legacy Commands and FunctionsNote:<strong>Caché</strong> 5.0 is supported on Windows 95, Windows 98, and Windows ME throughmaintenance version 5.0.3. <strong>InterSystems</strong> has made no commitment to support theseWindows platforms beyond <strong>Caché</strong> 5.0.3. Customers requiring further support forthese platforms should contact <strong>InterSystems</strong> directly.The format of this operating system information is as follows:Returned ElementMajor VersionMinor VersionBuild NumberOperating System TypeProcessor ArchitectureLength2 characters2 characters4 characters2 characters2 charactersDescriptionMajor Version identifies the majorversion number of the operatingsystem. For example, in NT3.51 themajor version is 3.Minor Version identifies the minorversion number of the operatingsystem. For example, in NT3.51 theminor version is 51.Build Number identifies the buildnumber of the operating system.This can be one of the following values:1 = Win32 on Windows 95, Windows98, or Windows ME. For 95 the MinorVersion is zero, for 98 the Minor Versionis greater than zero.2 = Win32 on Windows NT, Windows2000, Windows XP, or WindowsServer 2003.This can be one of the followingvalues: 0=Intel, 1=MIPS, 2=Alpha,3=PPC, 255=Unknown.To return the Windows operating system type for your system, use the $ZUTIL(100) function.Note that this function returns different numeric codes for operating system types.To return the <strong>Caché</strong> version number and the operating system and processor supported, usethe $ZVERSION special variable.784 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


ExamplesThe following is the hexadecimal string returned by $ZUTIL(67,14) for a Windows 2000system using an Intel processor:0005 0000 0893 0000 0002 0000The major version is 0005. The minor version is 0000. The build number is 0893. This correspondsto the Windows 2000 version number 5.00.2195. The next field is 0002 which, correspondsto the Windows 2000 operating system type. This is followed by 0000, indicating anIntel processor.The following is the hexadecimal string for a Windows 98 system using an Intel processor:0004 000A 08AE 040A 0001 0000The major version is 0004. The minor version is 000A. The build number is 08AE. Thiscorresponds to the Windows 98 version number 4.10.2222. Note that for Windows 95/98systems only, the second part of the build number field duplicates the major and minor versionnumber (here 040A). The next field is 0001 which, corresponds to the Windows 98 operatingsystem type. This is followed by 0000, indicating an Intel processor.ParameterspidA process ID number. The process ID of the current process is returned by the $JOB specialvariable. The System Management Portal provides a Processes option, which list the pids ofall running processes. If you specify a non-existent process, $ZUTIL(67,14) returns a valueof zero.See Also• $ZUTIL(67,15) Return the IP Address of the Client Application legacy function• $JOB special variable$ZUTIL(67,14) (legacy function)<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 785


Legacy Commands and Functions$ZUTIL(67,15) (legacy function)Returns the IP address of a client application.$ZUTIL(67,15,pid)$ZU(67,15,pid)ParameterspidThe process ID number of the <strong>Caché</strong> client application.DescriptionThis page describes the legacy function $ZUTIL(67,15), which has been superseded by theSYS.Process class methods. (Refer to the <strong>Caché</strong> Class <strong>Reference</strong> for further details.)$ZUTIL(67,15) is described here for compatibility with legacy applications.$ZUTIL(67,15,pid) returns the IP address in dotted decimal format. An IP address consistsof four decimal numbers, separated by dots. For example, the IP address of the local host is127.0.0.1. If the pid does not specify a client application, $ZUTIL(67,15,pid) returns the nullstring.On pre-5.1 versions of <strong>Caché</strong>, the client applications include <strong>Caché</strong> SQL Manager, <strong>Caché</strong>Control Panel, <strong>Caché</strong> Studio, <strong>Caché</strong> Explorer, and <strong>Caché</strong> Configuration Manager. All of these<strong>Caché</strong> client applications appear on the <strong>Caché</strong> Control Panel as routine name %CDSrv0. Thisis also the routine name returned by $ZUTIL(67,5,pid). To determine which client applicationis running as %CDSrv0, invoke $ZUTIL(67,13,pid) to return the name of the executablefile. You can, of course, create your own client applications.The <strong>Caché</strong> Terminal (routine name “shell”) and <strong>Caché</strong> <strong>Documentation</strong> are not client applications.ParameterspidA process ID number. The process ID of the current process is contained in the $JOB specialvariable. The System Management Portal provides a Processes option, which list the pids ofall running processes. If you specify a non-existent process, $ZUTIL(67,15) returns a valueof zero.786 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


SYS.Process MethodsYou can get the same process information using methods of the SYS.Process class, as shownin the following example:ZNSPACE "%SYS"WRITE ##CLASS(SYS.Process).%OpenId($JOB).ClientIPAddressGet()See Also• $JOB special variable• $ZUTIL(131) Set and Get the System Name and IP Address function$ZUTIL(100) (legacy function)• $ZUTIL(67,13) Return the Executable of the Client Application legacy function$ZUTIL(100) (legacy function)Determines which Windows operating system is running.$ZUTIL(100)$ZU(100)DescriptionThis page describes the legacy function $ZUTIL(100), which is obsolete as of <strong>Caché</strong> 5.1.<strong>Caché</strong> 5.1 and subsequent versions do not support Windows 95/98, so use of this function isnot meaningful. $ZUTIL(100) is described here for compatibility with legacy applications.You can use $ZUTIL(100) to return a code specifying which operating system you are currentlyrunning.The values that $ZUTIL(100) can return are as follows:01Windows NT 4, Windows 2000, Windows XP, or Windows Server 2003 (32–bit).Windows 95, Windows 98, or Windows ME.Note:<strong>Caché</strong> 5.0 is supported on Windows 95, Windows 98, and Windows ME throughmaintenance version 5.0.3. <strong>InterSystems</strong> has made no commitment to support theseWindows platforms beyond <strong>Caché</strong> 5.0.3. Customers requiring further support forthese platforms should contact <strong>InterSystems</strong> directly.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 787


Legacy Commands and FunctionsIf you issue $ZUTIL(100) on any other platform (UNIX or OpenVMS), you receive a error.You can also get operating system information from the $ZVERSION special variable, orthe $SYSTEM.Version class methods, as follows:WRITE $SYSTEM.Version.GetCompBuildOS()See Also• $SYSTEM special variable.• $ZVERSION special variable.• $ZUTIL(67,14)—Client Operating System legacy function$ZUTIL(113) (legacy function)Reclaims routine and directory blocks.$ZUTIL(113)$ZU(113)DescriptionThis page describes the legacy function $ZUTIL(113). It is described here for compatibilitywith legacy applications. The sole use of $ZUTIL(113) is to reclaim routine object directoryblocks when upgrading ISM database directories to <strong>Caché</strong>. It is neither needed nor supportedfor <strong>Caché</strong> version 5.0 and subsequent versions. No such block space reclamation is requiredwhen upgrading databases from an earlier version of <strong>Caché</strong> to <strong>Caché</strong> version 5.0 (or anysubsequent version).When upgrading a database from ISM to <strong>Caché</strong>, it is recommended that you upgrade in twostages: First upgrade from ISM to a pre-5.0 version of <strong>Caché</strong>, and execute $ZUTIL(113) toreclaim block space. Then upgrade from that version of <strong>Caché</strong> to <strong>Caché</strong> version 5.0 (or subsequent).$ZUTIL(113) reclaims unneeded routine object directory blocks resulting from a conversionfrom ISM to <strong>Caché</strong>. $ZUTIL(113) is not supported in <strong>Caché</strong> version 5.0 (or subsequent version).The $ZUTIL(49) function can be used to determine the current block size and maximumblock size.788 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


See Also$ZUTIL(133) (legacy function)• $ZUTIL(49) Obtain database label information for volume residing in namespace function$ZUTIL(133) (legacy function)Maintains a set of metric counters.$ZUTIL(133,n)$ZU(133,n)ParametersnNumeric code for different metric counter operations.DescriptionThis page describes the legacy function $ZUTIL(133). This function supports ViewPointsystem monitoring. $ZUTIL(133) is described here for compatibility with legacy applications.$ZUTIL(133) allows you to maintain a set of metric counters for an application and supplythese counters to ViewPoint. $ZUTIL(133) consists of eight subfunctions, as follows:n= 1n= 2n= 3n= 4n= 5n= 6n= 7n= 8Create a metric counters table.Add a counter to a metric counters table.Enable (show) or disable (hide) a table. When a table is hidden its countervalues are not displayed, but counters continue to increment.Retrieve table and counter definitions. You can retrieve the total number oftables defined, retrieve the definition of a table, or retrieve the definition of acounter within a table.Increment (or decrement) the value of a counter.Set a counter to a specified value, or return the current value of a counter.Display the current values for all counters.Show metrics status, enable, or disable metrics.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 789


Legacy Commands and Functions$ZUTIL(133,1)tnum=$ZUTIL(133,1,table,ccount,tabbrev,tdesc)$ZUTIL(133,1) creates a metric counter table and returns tnum, a numeric identifier for thattable. Calling $ZUTIL(133,1) with only the table parameter performs a lookup that determinesif a table with that name has been created. Calling $ZUTIL(133,1) with all four parameterscreates a working metric counter table. A maximum of 255 metric counter tables may becreated. You can call $ZUTIL(133,1) for an existing metric counter table to change the tdesc(table description).tnumtableccounttabbrevtdescReturns a positive numeric identifier for the counter table. Table numbersare assigned sequentially, beginning with 1. A value of 0 on a lookupmeans that the table has not been created. A negative value is an errorcode, indicating why the counter table cannot be created.The name of the metric counter table, specified as a quoted text string.The maximum length of the name is 20 characters.Optional — The number of counters to establish for the table. There isno explicit maximum value; however, there is a limit of 1024 total countersacross all counter tables.Optional — An abbreviation used to uniquely identify the metric countertable, specified as a quoted text string. This abbreviated name is usedwhen specifying a single counter in $ZUTIL(133,2). The maximum stringlength is 3 characters.Optional — The description of the table, specified as a quoted text string.A description can include variables.This example shows how to define a table.; Create counter tableSET BillingTable=$ZUTIL(133,1,"Billing",100,"BCT","My Billing Counters")If the last three parameters (ccount, tabbrev, tdesc) are not specified, only a lookup is performed.When a table is created, it is disabled. Therefore, you must use $ZUTIL(133,3) to explicitlyenable the table before its counters are available to ViewPoint.Each table has a version number that is an indicator of changes made to the table and counters.The value is incremented whenever a table is created, description changed, or enabled/disabled,790 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


or a counter's name or description is changed. Version numbers are returned by$ZUTIL(133,8).$ZUTIL(133,2)rval=$ZUTIL(133,2,tnum,cnum,cabbrev,cdesc)$ZUTIL(133) (legacy function)This function adds a metric counter to a table. If the counter exists, the function can be usedto change the name and/or description of the counter. Note that if the name or description ischanged, the version number of the table is incremented.rvaltnumcnumcabbrevcdescReturns a positive index number if the counter add/change wassuccessful. A negative value is an error message, indicating what kindof error occurred.The relative number of the metric counter table, specified as a positiveinteger, the count beginning with 1. The tnum of a table is returned bycalling $ZUTIL(133,1).The relative index number of the counter within the table, specified asan integer, the count beginning with 1.The name of the metric counter, specified as a quoted string. To specifya cabbrev name, concatenate the abbreviated name of the metric countertable (tabbrev in $ZUTIL(133,1)) with a unique counter name. If thecounter (specified by tnum and cnum) already exists, this new namereplaces the old name. Use the null string ("") to hide this counter.The description of the counter, specified as a quoted text string. Adescription can include variables.$ZUTIL(133,3)rval=$ZUTIL(133,3,tnum,n)This function is used to show (enable) or hide (disable) a metric counter table. All tables areinitially created as hidden. Hidden counter tables are disabled; the values in the counter tablewhile still incremented appropriately are unavailable to ViewPoint or a retrieve function call.You can determine the status (show or hide) of a table by calling $ZUTIL(133,3) withoutthe n parameter.<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 791


Legacy Commands and FunctionsrvaltnumnReturns the previous state of the table (1=show, 0=hide). If n is omitted, rvalreturns the current state of the table. If tnum does not exist, rval returns 0.The relative number of the metric counter table, specified as an integer, thecount beginning with 1. The tnum of a table is returned by calling$ZUTIL(133,1).Optional — A switch that specifies whether a table should be shown or hidden.1 = Show the table. 0 = Hide the table. Showing or hiding a table does notaffect the operation of its counters.$ZUTIL(133,4)rval=$ZUTIL(133,4,tnum,cnum)If you call $ZUTIL(133,4) specifying neither tnum nor cnum, $ZUTIL(133,4) returns thetotal number of metric counters tables defined. If you only specify tnum, $ZUTIL(133,4,tnum)retrieves the table definition of the specified table. If you specify both tnum and cnum,$ZUTIL(133,4,tnum,cnum) retrieves the definition of the specified counter; it does notretrieve the definition of that counter's table.rvaltnumcnumThe value returned, as described below. If neither tnum nor cnum is defined,rval is the total number of defined tables.Optional — The relative number of the metric counter table, as returned by$ZUTIL(133,1). Retrieve the definition of this table. A table definition containsthe values specified in $ZUTIL(133,1) and $ZUTIL(133,3). These values arereturned in the following sequence: number of counters (ccount), table name(table), abbreviated table name (tabbrev), table description (tdesc), and theshow/hide state boolean (n).Optional — The relative number of the counter within the table. Retrieve thedefinition of this counter. A counter definition consists of the counter name(cabbrev) and the counter description (cdesc). Thus, if both tnum and cnumare defined, the value of rval is: cabbrev_$CHAR(1)_cdesc.$ZUTIL(133,5)cval=$ZUTIL(133,5,tnum,cnum,value)$ZUTIL(133,5) increments or decrements the value of the specified counter. Calling$ZUTIL(133,5) without the value parameter increments the current value of the counter by792 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>


$ZUTIL(133) (legacy function)1. Calling $ZUTIL(133,5) with the value parameter increments or decrements the counterby the specified value.cvaltnumcnumvalueReturns the incremented (or decremented) value of the counter.The relative number of the metric counter table.The relative number of the counter within the table.Optional — Increment or decrement the specified counter by value. Thisincrement is specified as a signed or unsigned integer. To decrement acounter, specify a negative number. If you specify a decimal number, onlythe integer portion is applied, and the fractional portion is ignored. If valueis omitted, $ZUTIL(133,5) increments by 1.$ZUTIL(133,6)rval=$ZUTIL(133,6,tnum,cnum,value)Calling $ZUTIL(133,6) without the value parameter returns the current value of the specifiedcounter. Calling $ZUTIL(133,6) with the value parameter sets the counter to the specifiedvalue. $ZUTIL(133,6) is commonly used for setting the initial value of a counter; if unset,the initial value of a counter is always zero.rvaltnumcnumvalueReturns the value of the counter before being changed.The relative number of the metric counter table, as returned by$ZUTIL(133,1).The relative number of the counter within the table.Optional — Set the specified counter to value.$ZUTIL(133,8)status=$ZUTIL(133,8,n)The $ZUTIL(133,8) function enables or disables all $ZUTIL(133) functions except itself.When metrics are disabled, all $ZUTIL(133) function calls will return 0 or null (i.e., theyare treated as a no-op).<strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong> 793


Legacy Commands and FunctionsstatusnReturned status will always be 0 or a version number: If n is omitted, statusis 0 (if counters are disabled) or the version number (if counters are enabled).If n is 0, status is 0 (if counters were previously disabled) or the version number(if counters were previously enabled). If n is 1, status is the version number,which is incremented when the table or counter definition is changed.Optional — A switch that specifies whether metrics should be enabled ordisabled.This switch affects all tables. 1 = Enable metrics. 0 = Disable metrics.Error Return CodesWhen creating or manipulating tables, the $ZUTIL(133) function calls may return one ofthe following negative values if an error occurs.Error-1-2-3-4-5-6DescriptionExceeded maximum number of tables allowed.Exceeded maximum number of counters allowed.Invalid prefix, already exists for a different table.Invalid table/counter name, either too long or duplicate.Invalid number of counters, must be greater than 0No heap shared memory available.If a description is too long, no error is returned and the description is always truncated.See Also• For further details on ViewPoint metrics, see the <strong>Caché</strong> Basic System Management Guide.794 <strong>Caché</strong> <strong>ObjectScript</strong> <strong>Reference</strong>

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!