cache object script

228
Using Caché ObjectScript Version 2013.1 24 April 2013 InterSystems Corporation 1 Memorial Drive Cambridge MA 02142 www.intersystems.com

Upload: ajay-vikram-singh

Post on 20-Oct-2015

259 views

Category:

Documents


3 download

DESCRIPTION

This book describes the various elements of the Caché ObjectScript programming language.Its topics are:• Introducing Caché ObjectScript• Syntax Rules• Data Types and Values• Variables• Operators and Expressions• Regular Expressions• Commands• Functions• User-defined Code• ObjectScript Macros and the Macro Preprocessor• Multidimensional Arrays• String Operations• Transaction Processing• Error Processing• Command-line Routine Debugging• Open M Language Compatibility

TRANSCRIPT

  • Using Cach ObjectScriptVersion 2013.124 April 2013

    InterSystems Corporation 1 Memorial Drive Cambridge MA 02142 www.intersystems.com

  • Using Cach ObjectScriptCach Version 2013.1 24 April 2013 Copyright 2013 InterSystems CorporationAll rights reserved.

    This book was assembled and formatted in Adobe Page Description Format (PDF) using tools and information from the following sources:Oracle Corporation, RenderX, Inc., Adobe Systems, and the World Wide Web Consortium at www.w3c.org. The primary documentdevelopment tools were special-purpose XML-processing applications built by InterSystems using Cach and Java.

    , , , ,

    Cach WEBLINK, and Distributed Cache Protocol are registered trademarks of InterSystems Corporation.

    , ,

    InterSystems Jalapeo Technology, Enterprise Cache Protocol, ECP, and InterSystems Zen are trademarks of InterSystems Corporation.

    All other brand or product names used herein are trademarks or registered trademarks of their respective companies or organizations.

    This document contains trade secret and confidential information which is the property of InterSystems Corporation, One Memorial Drive,Cambridge, MA 02142, or its affiliates, and is furnished for the sole purpose of the operation and maintenance of the products of InterSystemsCorporation. No part of this publication is to be used for any other purpose, and this publication is not to be reproduced, copied, disclosed,transmitted, stored in a retrieval system or translated into any human or computer language, in any form, by any means, in whole or in part,without the express prior written consent of InterSystems Corporation.

    The copying, use and disposition of this document and the software programs described herein is prohibited except to the limited extentset forth in the standard software license agreement(s) of InterSystems Corporation covering such programs and related documentation.InterSystems Corporation makes no representations and warranties concerning such software programs other than those set forth in suchstandard software license agreement(s). In addition, the liability of InterSystems Corporation for any losses or damages relating to or arisingout of the use of such 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 BY INTERSYSTEMSCORPORATION ON THE USE OF, AND LIABILITY ARISING FROM, ITS COMPUTER SOFTWARE. FOR COMPLETE INFORMATIONREFERENCE SHOULD BE MADE TO THE STANDARD SOFTWARE LICENSE AGREEMENT(S) OF INTERSYSTEMS CORPORATION,COPIES OF WHICH WILL BE MADE AVAILABLE UPON REQUEST.

    InterSystems Corporation disclaims responsibility for errors which may appear in this document, and it reserves the right, in its sole discretionand without notice, to make substitutions and modifications in the products and practices described in this document.

    For Support questions about any InterSystems products, contact:

    InterSystems Worldwide Customer Support+1 617 621-0700Tel:+1 617 374-9391Fax:[email protected]:

  • Table of ContentsAbout This Book .................................................................................................................................... 1

    1 Introducing Cach ObjectScript ....................................................................................................... 31.1 Features ...................................................................................................................................... 31.2 Language Overview .................................................................................................................... 41.3 Invoking Commands and Functions ........................................................................................... 4

    1.3.1 Statements and Commands .............................................................................................. 51.3.2 Functions .......................................................................................................................... 51.3.3 Expressions ...................................................................................................................... 51.3.4 Variables ........................................................................................................................... 61.3.5 Operators .......................................................................................................................... 6

    1.4 Relationship with ISO Standard M ............................................................................................ 6

    2 Syntax Rules ........................................................................................................................................ 72.1 Case Sensitivity .......................................................................................................................... 7

    2.1.1 Identifiers ......................................................................................................................... 82.1.2 Keyword Names ............................................................................................................... 82.1.3 Class Names ..................................................................................................................... 82.1.4 Namespace Names ........................................................................................................... 8

    2.2 Unicode ...................................................................................................................................... 82.3 White Space ................................................................................................................................ 92.4 Comments ................................................................................................................................... 9

    2.4.1 Comments in INT Code for Routines and Methods ...................................................... 102.4.2 Comments in MAC Code for Routines and Methods .................................................... 102.4.3 Comments in Class Definitions Outside of Method Code ............................................. 10

    2.5 Literals ...................................................................................................................................... 112.5.1 String Literals ................................................................................................................. 112.5.2 Numeric Literals ........................................................................................................... 11

    2.6 Identifiers ................................................................................................................................. 122.6.1 Punctuation Characters within Identifiers ...................................................................... 12

    2.7 Labels ....................................................................................................................................... 132.8 Namespaces .............................................................................................................................. 14

    2.8.1 Extended References ...................................................................................................... 142.9 Reserved Words ........................................................................................................................ 15

    3 Data Types and Values ..................................................................................................................... 173.1 Strings ....................................................................................................................................... 17

    3.1.1 Escaping Quotation Marks ............................................................................................. 173.1.2 Concatenating Strings .................................................................................................... 183.1.3 String Comparisons ........................................................................................................ 183.1.4 Long Strings ................................................................................................................... 18

    3.2 Numbers ................................................................................................................................... 193.2.1 Fundamentals of Numbers ............................................................................................. 193.2.2 Canonical Form of Numbers .......................................................................................... 203.2.3 Strings as Numbers ........................................................................................................ 203.2.4 Concatenating Numbers ................................................................................................. 213.2.5 Fractional Numbers ........................................................................................................ 21

    3.3 Objects ...................................................................................................................................... 223.4 Persistent Multidimensional Arrays (Globals) ......................................................................... 22

    Using Cach ObjectScript iii

  • 3.5 Undefined Values ...................................................................................................................... 233.6 Boolean Values ......................................................................................................................... 233.7 Dates ......................................................................................................................................... 24

    4 Variables ............................................................................................................................................ 254.1 Categories of Variables ............................................................................................................. 25

    4.1.1 Local Variables ............................................................................................................... 254.1.2 Process-private Globals .................................................................................................. 274.1.3 Globals ........................................................................................................................... 284.1.4 Array Variables ............................................................................................................... 294.1.5 Special Variables ............................................................................................................ 294.1.6 Object Properties ............................................................................................................ 30

    4.2 Variable Typing and Conversion ............................................................................................... 304.2.1 Object Values .................................................................................................................. 31

    4.3 Variable Declaration and Scope ................................................................................................ 324.3.1 Using #Dim .................................................................................................................... 32

    5 Operators and Expressions .............................................................................................................. 335.1 Introduction to Operators and Expressions .............................................................................. 33

    5.1.1 Table of Operator Symbols ............................................................................................ 345.1.2 Operator Precedence ...................................................................................................... 355.1.3 Expressions .................................................................................................................... 365.1.4 Assignment ..................................................................................................................... 38

    5.2 String-to-Number Conversion .................................................................................................. 385.2.1 Numeric Strings ............................................................................................................. 385.2.2 Non-numeric Strings ...................................................................................................... 39

    5.3 Arithmetic Operators ................................................................................................................ 395.3.1 Unary Positive Operator (+) ........................................................................................... 405.3.2 Unary Negative Operator (-) .......................................................................................... 405.3.3 Addition Operator (+) ..................................................................................................... 405.3.4 Subtraction Operator (-) ................................................................................................. 415.3.5 Multiplication Operator (*) ............................................................................................ 415.3.6 Division Operator (/) ...................................................................................................... 425.3.7 Exponentiation Operator (**) ........................................................................................ 425.3.8 Integer Divide Operator ( \ ) ........................................................................................... 435.3.9 Modulo Operator (#) ...................................................................................................... 44

    5.4 Logical Comparison Operators ................................................................................................ 445.4.1 Unary Not ...................................................................................................................... 445.4.2 Precedence and Logical Operators ................................................................................. 455.4.3 Binary And .................................................................................................................... 455.4.4 Binary Or ....................................................................................................................... 46

    5.5 String Operators ....................................................................................................................... 475.5.1 Binary Concatenate ....................................................................................................... 48

    5.6 Numeric Relational Operators ................................................................................................. 485.6.1 Binary Less Than .......................................................................................................... 485.6.2 Binary Greater Than ...................................................................................................... 495.6.3 Greater Than or Equal To .............................................................................................. 495.6.4 Less Than or Equal To ................................................................................................... 49

    5.7 String Relational Operators ...................................................................................................... 505.7.1 Binary Equals ................................................................................................................ 505.7.2 Binary Contains ............................................................................................................. 515.7.3 Binary Follows .............................................................................................................. 51

    iv Using Cach ObjectScript

  • 5.7.4 Binary Sorts After ......................................................................................................... 525.8 Pattern Matching ...................................................................................................................... 53

    5.8.1 Specifying How Many Times a Pattern Can Occur ....................................................... 565.8.2 Specifying Multiple Patterns .......................................................................................... 575.8.3 Specifying a Combination Pattern ................................................................................. 575.8.4 Specifying an Indefinite Pattern ..................................................................................... 575.8.5 Specifying an Alternating Pattern (Logical OR) ............................................................ 585.8.6 Using Incomplete Patterns ............................................................................................. 585.8.7 Multiple Pattern Interpretations ..................................................................................... 595.8.8 Not Match Operator ....................................................................................................... 595.8.9 Pattern Complexity ......................................................................................................... 59

    5.9 Indirection ................................................................................................................................ 595.9.1 Name Indirection ........................................................................................................... 605.9.2 Pattern Indirection ......................................................................................................... 615.9.3 Argument Indirection .................................................................................................... 625.9.4 Subscript Indirection ..................................................................................................... 625.9.5 $TEXT Argument Indirection ........................................................................................ 63

    6 Regular Expressions ......................................................................................................................... 656.1 Wildcard and Quantifiers .......................................................................................................... 666.2 Literals and Character Ranges .................................................................................................. 666.3 Character Type Meta-Characters .............................................................................................. 67

    6.3.1 Single-letter Character Types ......................................................................................... 686.3.2 Unicode Property Character Types ................................................................................ 686.3.3 POSIX Character Types ................................................................................................. 70

    6.4 Grouping Construct .................................................................................................................. 716.5 Anchor Meta-Characters .......................................................................................................... 71

    6.5.1 String Beginning or End ................................................................................................. 716.5.2 Word Boundary .............................................................................................................. 72

    6.6 Logical Operators ..................................................................................................................... 736.7 Character Representation Meta-Characters .............................................................................. 73

    6.7.1 Hexadecimal, Octal, and Unicode Representation ......................................................... 746.7.2 Control Character Representation .................................................................................. 746.7.3 Symbol Name Representation ........................................................................................ 74

    6.8 Modes ....................................................................................................................................... 746.8.1 Mode for a Regular Expression Sequence ..................................................................... 756.8.2 Mode for a Literal .......................................................................................................... 76

    6.9 Comments ................................................................................................................................. 766.9.1 Embedded Comments .................................................................................................... 776.9.2 Line End Comment ........................................................................................................ 77

    6.10 Error Messages ....................................................................................................................... 77

    7 Commands ......................................................................................................................................... 797.1 Command Arguments ............................................................................................................... 79

    7.1.1 Multiple Arguments ....................................................................................................... 807.1.2 Argumentless Commands ............................................................................................... 807.1.3 Maximum Command Length ......................................................................................... 81

    7.2 Command Postconditional Expressions ................................................................................... 817.2.1 Postconditional Syntax ................................................................................................... 827.2.2 Evaluation of Postconditionals ....................................................................................... 82

    7.3 Invoking Code .......................................................................................................................... 837.3.1 Do ................................................................................................................................... 83

    Using Cach ObjectScript v

  • 7.3.2 Quit ................................................................................................................................. 837.3.3 Job .................................................................................................................................. 847.3.4 Xecute ............................................................................................................................ 84

    7.4 Assignment Commands ............................................................................................................ 847.4.1 Set ................................................................................................................................... 847.4.2 Kill ................................................................................................................................. 857.4.3 New ................................................................................................................................ 85

    7.5 Flow Control Commands ......................................................................................................... 857.5.1 If, ElseIf, and Else .......................................................................................................... 867.5.2 For .................................................................................................................................. 867.5.3 While and Do/While ...................................................................................................... 88

    7.6 I/O Commands ......................................................................................................................... 887.6.1 Write ............................................................................................................................... 887.6.2 Read ............................................................................................................................... 897.6.3 Open, Use, and Close ..................................................................................................... 90

    7.7 Other Commands ...................................................................................................................... 90

    8 Functions ........................................................................................................................................... 918.1 Function Syntax ........................................................................................................................ 91

    9 User-defined Code ............................................................................................................................ 939.1 Procedures, Routines, Subroutines, Functions, and Methods: What Are They? ...................... 94

    9.1.1 Routines ......................................................................................................................... 959.1.2 Subroutines ..................................................................................................................... 959.1.3 Functions ........................................................................................................................ 95

    9.2 Procedures in Detail ................................................................................................................. 969.2.1 Invoking Procedures ....................................................................................................... 969.2.2 Procedure Syntax ........................................................................................................... 979.2.3 Procedure Variables ........................................................................................................ 999.2.4 Public and Private Procedures ..................................................................................... 1009.2.5 Procedure Parameters ................................................................................................... 1009.2.6 Procedure Code ........................................................................................................... 1039.2.7 Indirection, XECUTE Commands, and JOB Commands within Procedures .............. 1049.2.8 Error Traps within Procedures .................................................................................... 105

    9.3 Legacy User-Defined Code .................................................................................................... 1059.3.1 Subroutines ................................................................................................................... 1059.3.2 Functions ..................................................................................................................... 106

    10 ObjectScript Macros and the Macro Preprocessor ................................................................... 11110.1 Using Macros ....................................................................................................................... 111

    10.1.1 Creating Custom Macros ........................................................................................... 11210.1.2 Saving Custom Macros .............................................................................................. 11310.1.3 Invoking Macros ......................................................................................................... 11410.1.4 Referring to External Macros (Include Files) ............................................................ 114

    10.2 Preprocessor Directives Reference ....................................................................................... 11410.2.1 #; ................................................................................................................................. 11510.2.2 #Def1Arg .................................................................................................................... 11510.2.3 #Define ....................................................................................................................... 11610.2.4 #Dim ........................................................................................................................... 11710.2.5 #Else ........................................................................................................................... 11810.2.6 #ElseIf ........................................................................................................................ 11810.2.7 #EndIf ......................................................................................................................... 118

    vi Using Cach ObjectScript

  • 10.2.8 #Execute ..................................................................................................................... 11810.2.9 #If ............................................................................................................................... 11910.2.10 #IfDef ....................................................................................................................... 11910.2.11 #IfNDef .................................................................................................................... 12010.2.12 #Import ..................................................................................................................... 12010.2.13 #Include .................................................................................................................... 12110.2.14 #NoShow .................................................................................................................. 12110.2.15 #Show ....................................................................................................................... 12110.2.16 #SQLCompile Mode ................................................................................................ 12210.2.17 #SQLCompile Path .................................................................................................. 12210.2.18 #SQLCompile Select ................................................................................................ 12410.2.19 #UnDef ..................................................................................................................... 12410.2.20 ##; ............................................................................................................................. 12510.2.21 ##Continue ............................................................................................................... 12510.2.22 ##Expression ............................................................................................................ 12610.2.23 ##Function ............................................................................................................... 12710.2.24 ##lit .......................................................................................................................... 12810.2.25 ##SQL ...................................................................................................................... 12810.2.26 ##Unique .................................................................................................................. 129

    10.3 Using System-supplied Macros ............................................................................................ 12910.3.1 Making System-supplied Macros Accessible ............................................................ 12910.3.2 System-supplied Macro Reference ............................................................................ 130

    11 Multidimensional Arrays ............................................................................................................. 13311.1 What Multidimensional Arrays Are ..................................................................................... 133

    11.1.1 Multidimensional Tree Structures .............................................................................. 13311.1.2 Sparse Multidimensional Storage .............................................................................. 13411.1.3 Settings for Multidimensional Arrays ........................................................................ 134

    11.2 Manipulating Multidimensional Arrays ............................................................................... 13411.3 For More Information ........................................................................................................... 134

    12 String Operations ......................................................................................................................... 13512.1 Basic String Operations and Functions ................................................................................ 135

    12.1.1 Advanced Features of $Extract .................................................................................. 13612.2 Delimited Strings .................................................................................................................. 137

    12.2.1 Advanced $Piece Features .......................................................................................... 13712.3 List-Structure String Operations .......................................................................................... 138

    12.3.1 Sparse Lists and Sublists ............................................................................................ 13912.4 Lists and Delimited Strings Compared ................................................................................ 140

    12.4.1 Advantages of Lists .................................................................................................... 14012.4.2 Advantages of Delimited Strings ............................................................................... 140

    13 Transaction Processing ................................................................................................................. 14113.1 Managing Transactions Within Applications ....................................................................... 141

    13.1.1 Transaction Commands .............................................................................................. 14213.1.2 Using the Lock Command in Transactions ................................................................ 14213.1.3 Transaction Rollback within an Application .............................................................. 14313.1.4 Examples of Transaction Processing Within Applications ......................................... 144

    13.2 Automatic Transaction RollBack ......................................................................................... 14513.2.1 Rollback During Cach Startup ................................................................................. 14513.2.2 Rollback at Halt from Cach ...................................................................................... 14513.2.3 Rollback During RESJOB ......................................................................................... 145

    Using Cach ObjectScript vii

  • 13.2.4 Restore Journal Option of JOURNAL Utility ............................................................ 14513.3 System-Wide Issues with Transaction Processing ............................................................... 146

    13.3.1 Backups and Journaling with Transaction Processing ............................................... 14613.3.2 Asynchronous Error Notifications ............................................................................. 146

    14 Error Processing ........................................................................................................................... 14914.1 The TRY-CATCH Mechanism ............................................................................................. 149

    14.1.1 Using THROW with TRY-CATCH ............................................................................ 15014.1.2 Using the %Exception.SystemException and %Exception.AbstractException Classes................................................................................................................................................ 15114.1.3 Other Considerations with TRY-CATCH ................................................................... 151

    14.2 Traditional Error Processing ................................................................................................. 15214.2.1 How Traditional Error Processing Works .................................................................. 15214.2.2 Handling Errors with $ZTRAP .................................................................................. 15514.2.3 Handling Errors with $ETRAP .................................................................................. 15814.2.4 Handling Errors in an Error Handler .......................................................................... 16114.2.5 Forcing an Error ......................................................................................................... 16214.2.6 Processing Errors in Programmer Mode ................................................................... 162

    15 Command-line Routine Debugging ............................................................................................. 16715.1 Debugging with the Cach Debugger ................................................................................... 167

    15.1.1 Using Breakpoints and Watchpoints .......................................................................... 16715.1.2 Establishing Breakpoints and Watchpoints ................................................................ 16815.1.3 Disabling Breakpoints and Watchpoints .................................................................... 17115.1.4 Delaying Execution of Breakpoints and Watchpoints ................................................ 17215.1.5 Deleting Breakpoints and Watchpoints ...................................................................... 17215.1.6 Single-step Breakpoint Actions .................................................................................. 17215.1.7 Tracing Execution ...................................................................................................... 17315.1.8 INTERRUPT Keypress and Break ............................................................................. 17515.1.9 Displaying Information About the Current Debug Environment ............................... 17515.1.10 Using the Debug Device .......................................................................................... 17715.1.11 Cach Debugger Example ........................................................................................ 17715.1.12 Understanding Cach Debugger Errors ................................................................... 178

    15.2 Debugging With BREAK ..................................................................................................... 17915.2.1 Using Argumentless BREAK to Suspend Routine Execution ................................... 17915.2.2 Using Argumentless BREAK with a Postconditional ................................................ 17915.2.3 Using Argumented BREAK to Enable or Disable Interrupts ..................................... 17915.2.4 Using Argumented BREAK to Suspend Routine Execution ..................................... 18015.2.5 Enabling Single Stepping at the Previous Execution Level ....................................... 18115.2.6 Understanding the Programmer Mode Prompt Information ...................................... 18115.2.7 Resuming Execution after a BREAK or an Error ...................................................... 18215.2.8 The NEW Command in Programmer Mode .............................................................. 18315.2.9 The QUIT Command in Programmer Mode .............................................................. 18415.2.10 Cach Error Messages .............................................................................................. 184

    15.3 Using %STACK to Display the Stack .................................................................................. 18415.3.1 Running %STACK ..................................................................................................... 18415.3.2 Displaying the Process Execution Stack .................................................................... 18515.3.3 Understanding the Stack Display ............................................................................... 185

    15.4 Other Debugging Tools ........................................................................................................ 18915.4.1 Displaying References to an Object with $SYSTEM.OBJ.ShowReferences ............ 18915.4.2 Error Trap Utilities ..................................................................................................... 189

    viii Using Cach ObjectScript

  • 16 Open M Language Compatibility ............................................................................................... 19316.1 Displaying and Switching Language Mode ......................................................................... 19316.2 DSM-11 Language Compatibility ........................................................................................ 194

    16.2.1 Using Routine Interlock Devices ............................................................................... 19416.2.2 Issuing I/O Commands for Routine Interlock Devices .............................................. 19516.2.3 Working with DSM-11 Mode Routines ..................................................................... 19516.2.4 Transferring Globals from DSM-11 Systems ............................................................ 19616.2.5 I/O Programming in DSM-11 Compatibility Mode ................................................... 19716.2.6 VIEW Command and $VIEW Function .................................................................... 20116.2.7 ZAllocate and ZDeallocate ........................................................................................ 20116.2.8 Extended Functions for DSM-11 Mode ..................................................................... 20116.2.9 Unsupported DSM-11 Functions ............................................................................... 20216.2.10 Extended Special Variables for DSM-11 Mode ....................................................... 20216.2.11 Extended Commands for DSM-11 Compatibility Mode ......................................... 20216.2.12 Error Handling for DSM-11 Compatibility Mode ................................................... 20316.2.13 $TEXT Comment Lines ........................................................................................... 203

    16.3 DSM Language Compatibility ............................................................................................. 20316.3.1 Porting Routines from DSM to Cach ....................................................................... 20316.3.2 Programming in DSM Language Mode ..................................................................... 20416.3.3 Device Control Mnemonic Spaces and Device Control Mnemonics ......................... 20616.3.4 Other DSM Language Features Implemented in Compatibility Mode ...................... 20716.3.5 VIEW Command and $VIEW Function .................................................................... 20916.3.6 Database Conversion .................................................................................................. 209

    16.4 DSM-J Language Compatibility .......................................................................................... 20916.5 DTM Language Compatibility ............................................................................................. 210

    16.5.1 Programming in DTM Compatibility Mode .............................................................. 21016.5.2 Commands, Functions, and Special Variables ........................................................... 21216.5.3 Database Conversion .................................................................................................. 215

    16.6 MSM Language Compatibility ............................................................................................. 21516.6.1 Commands, Functions, and Special Variables ........................................................... 21516.6.2 Database Conversion .................................................................................................. 216

    Using Cach ObjectScript ix

  • List of FiguresFigure 21: Studio Syntax Checking ....................................................................................................... 9Figure 141: Frames on a Call Stack .................................................................................................. 153Figure 142: $ZTRAP Error Handlers ................................................................................................ 158Figure 143: $ETRAP Error Handlers ................................................................................................ 160

    x Using Cach ObjectScript

  • List of TablesTable 31: Date Formats ........................................................................................................................ 24Table 41: Cach ObjectScript Type Conversion Rules ........................................................................ 31Table 51: ObjectScript Operators ........................................................................................................ 34Table 52: Pattern Codes ....................................................................................................................... 55Table 81: Invoking Cach ObjectScript Functions .............................................................................. 91Table 131: Cach Transaction Commands ........................................................................................ 142Table 151: Error Prompts in Programmer Mode ............................................................................... 182Table 152: %STACK Utility Information .......................................................................................... 186Table 153: Frame Types and Values Available .................................................................................. 186Table 154: %ERN Options ................................................................................................................ 190Table 161: Cach Language Modes ................................................................................................... 194Table 162: DSM-11 Compatibility Mode Open/Use Command Parameters .................................... 197Table 163: DSM-11 Compatibility Mode Set and Clear Status Bits ................................................. 199

    Using Cach ObjectScript xi

  • About This BookThis book describes the various elements of the Cach ObjectScript programming language.Its topics are:

    Introducing Cach ObjectScript Syntax Rules

    Data Types and Values

    Variables

    Operators and Expressions

    Regular Expressions

    Commands

    Functions

    User-defined Code

    ObjectScript Macros and the Macro Preprocessor Multidimensional Arrays

    String Operations

    Transaction Processing

    Error Processing

    Command-line Routine Debugging

    Open M Language Compatibility

    For a detailed outline, see the Table of Contents.

    Other, related documents in the Cach documentation set are:

    The Cach ObjectScript Language Reference Cach Programming Orientation Guide

    Using Cach Objects Using Cach SQL Using Cach Basic

    Using Cach Globals

    For general information, see Using InterSystems Documentation.

    Using Cach ObjectScript 1

  • 1Introducing Cach ObjectScriptCach ObjectScript is an object programming language designed for rapidly developing complex business applications. Itis well-suited for a variety of applications including:

    Business logic

    Application integration

    Data processing

    Cach ObjectScript source code is compiled into object code that executes within the Cach Virtual Machine. This objectcode is highly optimized for operations typically found within business applications, including string manipulations anddatabase access. ObjectScript programs are completely portable across all platforms supported by Cach.You can use Cach ObjectScript in any of the following contexts: Interactively from the command line of the Cach Terminal.

    As the implementation language for methods of Cach object classes. To create Cach ObjectScript routines: individual programs contained and executed within Cach. As the implementation language for Stored Procedures and Triggers within Cach SQL. As a server-side scripting language within a Cach Server Pages application.

    Cach ObjectScript is completely compatible and interoperable with the other Cach native scripting language: CachBasic.

    To learn more about Cach ObjectScript, you can also refer to: The Cach ObjectScript Tutorial for an interactive introduction to most language elements. The Cach ObjectScript Reference for details on individual commands and functions.

    1.1 FeaturesSome of the key features of Cach ObjectScript include: Powerful built-in functions for working with strings.

    Native support for objects including methods, properties, and polymorphism. A wide variety of commands for directing control flow within an application.

    Using Cach ObjectScript 3

  • A set of commands for dealing with I/O devices.

    Support for multidimensional, sparse arrays: both local and global (persistent). Support for efficient, Embedded SQL. Support for indirection as well as runtime evaluation and execution of commands.

    1.2 Language OverviewThe following is an introduction to the major elements of Cach ObjectScript.Cach ObjectScript does not define any reserved words: you are free to use any word as an identifier (such as a variablename). In order to accomplish this, Cach ObjectScript uses a set of built-in commands as well as special characters (suchas the $ prefix for function names) in order to distinguish identifiers from other language elements.For example, to assign a value to a variable, you can use the SET command:

    SET x = 100 WRITE x

    In Cach ObjectScript it is possible (though not recommended) to use any valid name as an identifier name, as shown inthe following program, which is functionally identical to the previous example:

    SET SET = 100 WRITE SET

    Some components of Cach ObjectScript, such as command names and function names, are not case-sensitive. Othercomponents of Cach ObjectScript, such as variable names and method names, are case-sensitive. For details refer to theSyntax chapter of this document.

    Note that whitespace can be inserted or omitted almost anywhere in Cach ObjectScript. However, one use of whitespaceis significant; a statement cannot start on the first character position on a line. Thus, all commands must be indented.Comments must also be indented. The only code element that can appear in the first character position on a line is a label:

    MyLabel SET x = 100 WRITE x

    Whitespace rules are further discussed in the Syntax chapter of this document.

    1.3 Invoking Commands and FunctionsObjectScript syntax, in its simplest form, involves invoking commands on expressions, such as: WRITE x

    which invokes the WRITE command on the variable x (this displays the value of x). In the example above, x is anexpression; an ObjectScript expression is one or more tokens that can be evaluated to yield a value. Each token can bea literal, a variable, the result of the action of one or more operators (such as the total from adding two numbers), the returnvalue that results from evaluating a function, some combination of these, and so on. The valid syntax for a statement involvesits commands, functions, and operators and expressions; see each chapter for information on these.

    4 Using Cach ObjectScript

    Introducing Cach ObjectScript

  • 1.3.1 Statements and CommandsA Cach ObjectScript program consists of a number of statements. Each statement defines a specific action for a programto undertake. Each statement consists of a command and its arguments.

    Consider the following ObjectScript statement: SET x="World" WRITE "Hello",!,x

    WRITE is a command. It does exactly what its name implies: it writes whatever you specify as its argument(s) to thecurrent principal output device. In this case, WRITE writes three arguments: the literal string Hello ; the ! character,which is a symbolic operator specific to the WRITE command that issues a line feed/carriage return; and the local variablex, which is replaced during execution by its current value. Arguments are separated by commas; you may also add whitespacebetween arguments (with some restrictions). Whitespace is discussed in the Syntax chapter of this document.Most Cach ObjectScript commands (and many functions and special variables) have a long form and a short (abbreviated)form (typically one or two characters). For example, the following program is identical to the previous one, but uses theabbreviated command names:

    S x="World" W "Hello",!,x

    The short form of a command name is simply a device for developers who do not like to type long command names. It isexactly equivalent to the long form. This document uses the long form of command names. For a complete list, seeAbbreviations Used in Cach ObjectScript in the Cach ObjectScript Reference.For more information on commands, refer to the Commands chapter or the individual reference page within the CachObjectScript Reference.

    1.3.2 FunctionsA function is a routine that performs a frequently required operation (for example, converting a string to its equivalentASCII code values). A function is invoked within a command line. This invocation passes parameters to the function, whichuses these parameter values to perform some operation. The function then returns a single value that is the result of theoperation. You can use a function any place you can use an expression. A function invoked upon an object is called amethod. (Expressions and methods are described later in this chapter.)In addition to its system-supplied functions, Cach ObjectScript allows you to write procedures, which are user-definedfunctions. The system-supplied functions are provided as part of Cach; they perform common string and data operationsand each is described in the Cach ObjectScript Reference. For information on defining and calling user-defined functions,refer to User-Defined Code.

    1.3.3 ExpressionsAn expression is any set of tokens that can be evaluated to yield a single value. For example, the literal string, hello , isan expression. So is l + 2. Variables such as x, functions such as $LENGTH(), and special variables such as $ZVERSIONalso evaluate to an expression.

    Within a program, you use expressions as arguments for commands and functions:

    SET x = "Hello" WRITE x,! WRITE 1 + 2,! WRITE $LENGTH(x),! WRITE $ZVERSION

    Using Cach ObjectScript 5

    Invoking Commands and Functions

  • 1.3.4 VariablesIn ObjectScript, a variable is the name of a location in which a runtime value can be stored. Variables must be defined, forexample, by using the SET command, but they do not have to be typed. Variables in Cach ObjectScript are untyped; thatis, they do not have an assigned data type and can take any data value. (For compatibility, the $DOUBLE function can beused to convert untyped floating point numbers to a specific numeric data type format.)Cach ObjectScript supports several kinds of variables: Local variables A variable that is accessible only by the Cach process that created it, and which is automatically

    deleted when the process terminates. A local variable is accessible from any namespace.

    Process-private globals A variable that is accessible only by the Cach process and is deleted when the processends. A process-private global is accessible from any namespace. Process-private globals are especially useful fortemporary storage of large data values.

    Globals A persistent variable that is stored within the Cach database. A global is accessible from any process, andpersists after the process that created it terminates. Globals are specific to individual namespaces.

    Array variables A variable with one or more subscripts. All user-defined variables can be used as arrays, includinglocal variables, process-private globals, globals, and object properties.

    Special variables (also known as system variables) One of a special set of built-in variables that contain a value fora particular aspect of the Cach operating environment. All special variables are defined; Cach sets all special variablesto an initial value (sometimes a null string value). Some special variables can be set by the user, others can only be setby Cach. Special variables are not array variables.

    Object properties A value associated with, and stored within, a specific instance of an object.

    Cach ObjectScript supports various operations on or among variables. Variables are described in much greater detail inthe Variables chapter of this document.

    1.3.5 OperatorsCach ObjectScript defines a number of built-in operators. These include arithmetic operators, such as addition (+ ) andmultiplication (* ), logical operators, and pattern match operators. For details, refer to the Operators chapter of thisdocument.

    1.4 Relationship with ISO Standard MCach ObjectScript is a superset of the ISO 11756-1999 standard M programming language. If you are an M programmeryou can run your existing M applications on Cach with no change.

    Cach ObjectScript offers a number of significant improvements over ISO-standard M including: Integrated support for objects and object-oriented programming. Procedure and control blocks using { } syntax. Relaxed whitespace requirements.

    Many new functions.

    You can take advantage of these new features in an evolutionary fashion, using them within your applications as you seefit.

    6 Using Cach ObjectScript

    Introducing Cach ObjectScript

  • 2Syntax RulesThis chapter describes the basic rules of ObjectScript syntax. Topics include: Case Sensitivity

    Unicode

    White Space

    Comments

    Literals

    Identifiers

    Labels

    Namespaces

    Reserved Words

    2.1 Case SensitivitySome parts of ObjectScript are case-sensitive while others are not. Generally speaking, the user-definable parts of ObjectScriptare case-sensitive while keywords are not:

    Case-sensitive: local variable names, process-private global names, global names, variable subscript names, classnames, method names, property names, the i% preface for an instance variable for a property, routine names, macronames, label names, lock names, passwords, Embedded SQL host variable names, Embedded SQL marker strings.

    Not case-sensitive: command names, function names, special variable names, namespace names (see below), usernames and role names, letter codes (for LOCK, OPEN, or USE), keyword codes (for $STACK), pattern match codes,the Embedded SQL &sql directive, %ZLANG tag names.

    Usually not case-sensitive: Case sensitivity of the following is platform-dependent: device names, file names, directorynames, disk drive names. The exponent symbol is usually not case-sensitive. Uppercase E is always a valid exponentsymbol; lowercase e can be configured as valid or invalid for the current process using the ScientificNotation()method of the %SYSTEM.Process, or system-wide using the ScientificNotation property of the Config.Miscellaneousclass.

    Using Cach ObjectScript 7

  • 2.1.1 IdentifiersUser-defined identifiers (variable, routine, and label names) are case-sensitive. String, string, and STRING all refer to dif-ferent variables. Global variable names are also case-sensitive, whether user-defined or system-supplied.

    Note: Cach SQL identifiers, in contrast, are not case-sensitive.

    2.1.2 Keyword NamesCommand, function, and system variable keywords (names) are not case-sensitive. You can use Write, write, or WRITE;all refer to the same command.

    2.1.3 Class NamesAll identifiers related to classes (class names, property names, method names, etc.) are case-sensitive. For purposes ofuniqueness, however, such names are considered to be not case-sensitive; that is, two class names cannot differ by casealone.

    2.1.4 Namespace NamesNamespace names are not case-sensitive, meaning that you can input a namespace name in any combination of uppercaseand lowercase letters. Note however, that Cach always stores namespace names in uppercase. Therefore, Cach may returna namespace name to you in uppercase rather than in the case which you specified. For further details on namespace namingconventions, see Namespaces.

    2.2 UnicodeYour instance of Cach supports the Unicode international character set if you selected the Unicode option during Cachinstallation. Unicode characters are 16-bit characters, also known as wide characters. The $ZVERSION special variableshows if your Cach installation supports Unicode.

    On a Unicode installation of Cach, some names can contain Unicode letter characters, while other names cannot containUnicode letters. Unicode letters are defined as alphabetic characters with ASCII values higher than 255. For example, theGreek lowercase lambda is $CHAR(955), a Unicode letter. Unicode Letters Permitted: local variable names; variable subscript names (for local, global, and process-private global

    variables); list element values; Embedded SQL host variable names; label names; namespace names; Cach and SQLuser names, role names, and passwords; Embedded SQL values; SQL table, view, field, and trigger names;^%ZLANG names for user-defined commands, functions, and special variables.

    No Unicode Letters: global variable names; process-private global names; administrator user names and passwords.

    Note: The Japanese locale does not support accented Latin letter characters in Cach names. Japanese names may contain(in addition to Japanese characters) the Latin letter characters A-Z and a-z (6590 and 97122), and the Greekcapital letter characters (913929 and 931937).

    8 Using Cach ObjectScript

    Syntax Rules

  • 2.3 White SpaceUnder certain circumstances, ObjectScript treats white space as syntactically meaningful. Unless otherwise specified, whitespace refers to blank spaces, tabs, and line feeds interchangeably. In brief, the rules are:

    White space must appear at the beginning of each line of code or single-line comment. (An empty line does not requireleading white space.) Leading white space is not required for: A line that begins with a label (and not with white space). If a line has a label, there must be white space between

    the label and any code or comment.

    The second or subsequent line of a multiline comment.

    There must be one and only one space (not tab) between a command and its first argument; if a command uses apostconditional, there are no spaces between the command and its postconditional.

    If a postconditional expression includes any spaces, then the entire expression must be parenthesized.

    There can be any amount of white space between any pair of command arguments.

    If a line contains code and then a single-line comment, there must be white space between them.

    Typically, each command appears on its own line, though you can enter multiple commands on the same line. In thiscase, there must be white space between them; if the first command is argumentless, then the second command mustbe preceded by two spaces or tabs (or one of each).

    The Cach Studio provides built-in syntax checking, so that it will mark any illegal use of white space, such as the followinginsertion of multiple spaces before a commands first argument:

    Figure 21: Studio Syntax Checking

    2.4 CommentsIt is good practice to use comments to provide in-line documentation in code, as they are a valuable resource when modifyingor maintaining code. Cach ObjectScript supports several types of comments which can appear in several kinds of locations: Comments in INT Code for Routines and Methods

    Comments in MAC Code for Routines and Methods

    Comments in Class Definitions Outside of Method Code

    Using Cach ObjectScript 9

    White Space

  • 2.4.1 Comments in INT Code for Routines and MethodsWithin INT code, several types of comments are available, all of which must start in column 2 or greater:

    The /* */ comment can appear within a line or across lines. /* can be the first element on a line or can follow otherelements; */ can be the final element on the line or can precede other elements.

    The // comment specifies that the remainder of the line is a comment; it can be the first element on the line or followother elements.

    The ; comment specifies that the remainder of the line is a comment; it can be the first element on the line or can followother elements.

    The ;; comment a special case of the ; comment type makes the comment available to the $TEXT functionwhen the routine is distributed as object code only; the comment is only available to $TEXT if no commands precedeit on the line.

    Note: Because Cach retains ;; comments in the object code (the code that is actually interpreted and executed),there is a performance penalty for including them and they should not appear in loops.

    A multiline comment (/* comment */) can be placed between command or function arguments, either before or aftera comma separator. A multiline comment cannot be placed within an argument, or be placed between a command keywordand its first argument or a function keyword and its opening parenthesis. It can be placed between two commands on thesame line, in which case it functions as the single space needed to separate the commands. You can immediately followthe end of a multiline comment (*/) with a command on the same line, or follow it with a single line comment on the sameline. The following example shows these insertions of /* comment */ within a line:

    WRITE $PIECE("Fred&Ginger"/* WRITE "world" */,"&",2),! WRITE "hello",/* WRITE "world" */" sailor",! SET x="Fred"/* WRITE "world" */WRITE x,! WRITE "hello"/* WRITE "world" */// WRITE " sailor"

    2.4.2 Comments in MAC Code for Routines and MethodsAll comment types that are valid for INT code are also valid for MAC code and behave in MAC code just as they do inINT code. Two other comment types are also available:

    The #; comment can start in any column but must be the first element on the line; #: comments do not appear in INTcode.

    The ##; comment can start in any column. It can be the first element on the line or can follow other elements. ##;comments do not appear in INT code. ##: can be used in ObjectScript code or in Embedded SQL code.

    The /// comment can start in any column but must be the first element on the line. If /// starts in column 1, it doesnot appear in INT code; if /// starts in column 2 or greater, it appears in INT code and is treated as if it were a //comment.

    2.4.3 Comments in Class Definitions Outside of Method CodeWithin class definitions, but outside of method definitions, several comment types are available, all of which can start inany column:

    The // and /* */ comments are for comments within the class definition.

    The /// comment serves as class reference content for the class or class member that immediately follows it. Forclasses themselves, the /// comment preceding the beginning of the class definition provides the description of theclass for the class reference content which is also the value of description keyword for the class). Within classes, all

    10 Using Cach ObjectScript

    Syntax Rules

  • /// comments immediately preceding a member (either from the beginning of the class definition or after the previousmember) provide the class reference content for that member, where multiple lines of content are treated as a singleblock of HTML. For more information on the rules for /// comments and the class reference, see either Extendingthe Class Reference in Using InterSystems Documentation or the %CSP.Documatic entry in the InterSystems ClassReference.

    2.5 LiteralsA literal is a series of characters that represents a particular string or numeric value, such as Hello and 5 below:

    WRITE "Hello" SET x = 5

    ObjectScript recognizes two types of literals: String literals

    Numeric literals

    2.5.1 String LiteralsString literals are sets of zero or more of the 95 ASCII graphic characters (ASCII decimal values 32 to 126) enclosed inquotation marks (unlike string literals, numeric literals do not need quotation marks). String literals consist of numbers,uppercase and lowercase letters, or symbolic characters (such as $, #, %, or &) enclosed in quotation marks. The value ofa string literal is constant and determined by the characters, including symbolic characters and spaces enclosed in quotationmarks.

    On Unicode systems, additional string literal characters are supported. These can be specified by using the $CHAR function,as shown in the following example:

    SET greekstr=$CHAR(952,945,955,945,963,963,945) WRITE greekstr

    To include the quotation mark character (") within a string, double the character, as shown in the following example: WRITE "This character "" is a quotation mark"

    A string that contains no value is known as a null string. It is represented by two quotation mark characters (""). A nullstring is considered to be an actual value. It has a length of 0.

    To concatenate strings, use the concatenate operator (_): SET mystr="Two halves"_" make a whole" WRITE mystr

    2.5.2 Numeric LiteralsNumeric literals are strings that ObjectScript evaluates as numbers. ObjectScript treats as a number any string that containsonly the following:

    The digits 0 through 9

    The Unary Minus operator (-) The Unary Plus operator (+)

    Using Cach ObjectScript 11

    Literals

  • The decimal_separator character (by default this is the period or decimal point character; in European locales this isthe comma character).

    The Letter E (used in scientific notation)

    ObjectScript can work with the following types of numbers: Integers (whole numbers such as 100, 0, or -7) Fractional numbers: decimal numbers (real numbers such as 3.767) and decimal fractions (real numbers such as .0442).

    ObjectScript supports two representations of fractional numbers: standard Cach floating point numbers ($DECIMALnumbers) and IEEE double-precision floating point numbers ($DOUBLE numbers). For further details, refer to the$DOUBLE function.

    Scientific notation: numbers placed in exponential notation (such as 2.8E2). To specify exponential notation inObjectScript, use the following format:[-]mantissaE[-]exponent

    where

    The optional Unary Minus operator used with negative numbers.-

    An integer or fractional number.mantissa

    An operator delimiting the exponent (can be uppercase or lowercase).EThe optional Unary Minus operator used with a negative exponent.-

    The integer exponent (the power of 10).exponent

    For example, to represent the number 10, use 1E1; and to represent number 280, use 2.8E2.

    2.6 IdentifiersAn identifier is the name of a variable, a routine, or a label. In general, legal identifiers consist of letter and number characters;with few exceptions, punctuation characters are not permitted in identifiers. Identifiers are case-sensitive.

    The naming conventions for user-defined commands, functions, and special variables are more restrictive (only letterspermitted) than identifier naming conventions. Refer to Extending Languages with ^ %ZLANG Routines in Cach SpecializedSystem Tools and Utilities.

    Naming conventions for local variables, process-private globals, and globals are provided in the Variables chapter of thisdocument.

    2.6.1 Punctuation Characters within IdentifiersCertain identifiers can contain one or more punctuation characters. These include:

    The first character of an identifier can be a percent (%) character. Cach names beginning with a % character (exceptthose beginning with %Z or %z) are reserved as system elements. For further details, see Rules and Guidelines forIdentifiers in the Cach Programming Orientation Guide.

    A global or process-private global name (but not a local variable name) may include one or more period (.) characters.A routine name may include one or more period (.) characters. A period cannot be the first or last character of anidentifier.

    12 Using Cach ObjectScript

    Syntax Rules

  • Note that globals and process-private globals are identified by a caret (^) prefix of one or more characters, such as the fol-lowing:

    Globals: Process-Private Globals:^globname ^||ppgname^|""|globname ^|"^"|ppgname^|"mynspace"|globname ^|"^",""|ppgname^["mynspace"]globname ^["^"]ppgname

    These prefix characters identify the type of storage and (in the case of globals) the namespace used for this storage. Theactual name begins after the final vertical bar or closing square bracket.

    2.7 LabelsAny line of ObjectScript code can optionally include a label (also known as a tag). A label serves as a handle for referringto that line location in the code. A label is an identifier that is not indented; it is specified in column 1. All Cach ObjectScriptcommands must be indented.

    Labels have the following naming conventions:

    The first character must be an alphanumeric character or the percent character (%). The second and all subsequentcharacters must be alphanumeric characters. A label may contain Unicode letters.

    They can be up to 31 characters long. A label may be longer than 31 characters, but must be unique within the first 31characters. A label reference matches only the first 31 characters of the label. However, all characters of a label orlabel reference (not just the first 31 characters) must abide by label character naming conventions.

    They are case-sensitive.

    A line can consist of only a label, a label followed by one or more commands, or a label followed by a comment. If acommand or a comment follows the label on the same line, they must be separated from the label by a space or tab character.

    The following are all unique labels:

    maximumMaxMAX86agent8686agent%control

    Labels are useful identifying sections of code and for managing flow control, since you can use the label to invoke the codethat follows it using the DO or GOTO command.

    Labels are also used by the PRINT and ZPRINT commands and the $TEXT function to identify source code lines.However, a label does not define an encapsulated unit of code; this means that once the labelled code executes, executioncontinues with the next labelled unit of code, if there is one. For instance, in the following code:

    SET x = 22 IF x=22 {DO label22 WRITE "All finished",! QUIT } ELSE {WRITE "This never happens"}label22 WRITE "x = ",x,!label23 SET x = 23 WRITE "x = ",x,!

    Using Cach ObjectScript 13

    Labels

  • execution continues from the code under label22 to that under label23, which results in the value of x being changedfrom 22 to 23. To avoid this situation, use the QUIT command to exit from the code where appropriate, as shown in thefollowing example:

    SET x = 22 IF x=22 {DO label22 WRITE "All finished",! QUIT } ELSE {WRITE "This never happens"}label22 WRITE "x = ",x,! QUITlabel23 SET x = 23 WRITE "x = ",x,! QUIT

    2.8 NamespacesA namespace name may be an explicit namespace name or an implied namespace name. An explicit namespace name isnot case sensitive; regardless of the case of the letters with which it is input, it is always stored and returned in uppercaseletters.

    In an explicit namespace name, the first character must be a letter or a percent sign (%). The remaining characters must beletters, numbers, hyphens (), or underscores (_). The name cannot be longer than 255 characters.When Cach translates an explicit namespace name to a routine or class name (for example, when creating a cached queryclass/routine name), it replaces punctuation characters with lowercase letters, as follows: % = p, _ = u, = d. An impliednamespace name may contain other punctuation characters; when translating an implied namespace name, these punctuationcharacters are replaced by a lowercase "s". Thus the following seven punctuation characters are replaced as follows: @ =s, : = s, / = s, \ = s, [ = s, ] = s, ^ = s.When using Cach MultiValue, each MultiValue account is mapped to a Cach namespace. The naming conventions forMultiValue accounts and Cach namespaces differ. For details about how MultiValue account names are translated tonamespace names, refer to the CREATE.ACCOUNT command in the Cach MultiValue Commands Reference.For information on using namespaces, see Namespaces and Databases in the Cach Programming Orientation Guide. Forinformation on creating namespaces, see Configuring Namespaces in the Cach System Administration Guide.

    2.8.1 Extended ReferencesAn extended reference is a reference to an entity that is located in another namespace. The namespace name can be specifiedas a string literal enclosed in quotes, as a variable that resolves to a namespace name, as an implied namespace name, oras a null string ("") a placeholder that specifies the current namespace. There are three types of extended references: Extended Global Reference: references a global variable in another namespace. The following syntactic forms are

    supported: ^ ["namespace"]global and ^ |"namespace"|global. For further details, refer to Global Variablessection of the Variables chapter of this manual.

    Extended Routine Reference: references a routine in another namespace.

    The DO command, the $TEXT function, and user-defined functions support the following syntactic form:|"namespace"|routine.

    The JOB command supports the following syntactic forms: routine|"namespace"|,routine["namespace"], or routine:"namespace".

    In all these cases, the extended routine reference is prefaced by a ^ (caret) character to indicate that the specified entityis a routine (rather than a label or an offset). This caret is not part of the routine name. For example, DO

    14 Using Cach ObjectScript

    Syntax Rules

  • ^|"SAMPLES"|fibonacci invokes the routine named fibonacci, which is located in the SAMPLES namespace.The command WRITE $$fun^|"SAMPLES"|house invokes the user-defined function fun() in the routine house,located in the SAMPLES namespace.

    Extended SSVN Reference: references a structured system variable (SSVN) in another namespace. The followingsyntactic forms are supported: ^$["namespace"]ssvn and ^$|"namespace"|ssvn. For further details, refer tothe ^$GLOBAL, ^$LOCK, and ^$ROUTINE structured system variables.

    All extended references can, of course, specify the current namespace, either explicitly by name, or by specifying a nullstring placeholder.

    2.9 Reserved WordsThere are no reserved words in Cach ObjectScript; you can use any valid identifier as a variable name, function name, orlabel. At the same time, it is best to avoid using identifiers that are command names, function names, or other such strings.Also, since ObjectScript code includes support for embedded SQL, it is prudent to avoid naming any function, object,variable, or other entity with an SQL reserved word, as this may cause difficulties elsewhere.

    Using Cach ObjectScript 15

    Reserved Words

  • 3Data Types and Values

    Cach ObjectScript is a typeless language you do not have to declare the types of variables. Any variable can have astring, numeric, or object value. That being said, there is important information to know when using different kinds of datain ObjectScript, such as: Strings

    Numbers

    Objects Persistent Multidimensional Arrays (Globals) Undefined Values

    Boolean Values

    Dates

    3.1 StringsA string is a set of characters: letters, digits, punctuation, and so on. You can define a string literal by placing text withina matched set of quotation marks ("): Set string = "This is a string." Write string

    Topics about strings include:

    Escaping Quotation Marks Concatenating Strings

    String Comparisons

    Long Strings

    3.1.1 Escaping Quotation MarksYou can include a " (double quote) character within a string literal by preceding it with another double quote character:

    Using Cach ObjectScript 17

  • Escaping Quotation Marks Set string = "This string has ""quotes"" in it." Write string

    There are no other escape sequences within ObjectScript string literals.

    3.1.2 Concatenating StringsYou can concatenate two strings into a single string using the _ concatenation operator:

    Concatenation Set string = "Hello" _ " Goodbye" Write string

    3.1.3 String ComparisonsYou can use the equals (=) and does not equal ('=) operators to compare two strings. String equality comparisons are casesensitive. Exercise caution when using these operators to compare a string to a number, because this comparison is a stringcomparison, not a numeric comparison. Therefore only a string containing a number in canonical form is equal to its corre-sponding number. ("-0" is not a canonical number.) This is shown in the following example: WRITE "Fred" = "Fred",! // TRUE WRITE "Fred" = "FRED",! // FALSE WRITE "-7" = -007.0,! // TRUE WRITE "-007.0" = -7,! // FALSE WRITE "0" = -0,! // TRUE WRITE "-0" = 0,! // FALSE WRITE "-0" = -0,! // FALSE

    The , = operators cannot be used to perform a string comparison. These operators treat strings as numbers andalways perform a numeric comparison. Any non-numeric string is assigned a numeric value of 0 when compared usingthese operators.

    3.1.4 Long StringsCach supports two maximum string length options:

    The traditional maximum string length of 32,767 characters.

    Long Strings maximum string length of 3,641,144 characters.

    As of Cach 2012.2, long strings are enabled by default for new installs. However, if you upgrade to 2012.2 from anexisting install, the long string enabled/disabled option will be the same as before the upgrade. If long strings are enabled,the maximum length of a string is 3,641,144 characters. If long string are disabled, the maximum length of a string is 32,767characters, which was the default for earlier versions of Cach.

    You can use either of the following methods to enable or disable long strings system-wide:

    In the Management Portal, select [System] > [Configuration] > [Memory and Startup]. On the System Memory and StartupSettings page, select the Enable Long Strings check box. If a process was already running when you enabled longstrings, long strings will not be enabled for that process.

    In the Cach parameter file, specify the value of the EnableLongStrings parameter, as described in the EnableLongStringssection of the Cach Parameter File Reference.

    Cach also supports the use of long strings on an optional, per-instance basis. To enable long strings for the current instance,use the EnableLongStrings property of the Config.Miscellaneous class.

    18 Using Cach ObjectScript

    Data Types and Values

  • Note: Performance may be affected when long strings are enabled. Enabling long strings increases the amount ofmemory allocated to the string stack by approximately 50 times. Cach uses the string stack for temporary stringhandling during command execution. This larger string stack memory is allocated to each process, whether theprocess uses long strings or not. You may need to retune your system to maintain performance.

    When a process actually uses a long string, the memory for the string comes from the operating systems malloc() buffer,not from the partition memory space for the process. Thus the memory allocated for actual long string values is not subjectto the limit set by the maximum memory per process (Maximum per Process Memory (KB)) parameter and does not affectthe $STORAGE value for the process.

    3.2 NumbersTopics related to numbers include:

    Fundamentals of Numbers

    Canonical Form of Numbers

    Strings as Numbers

    Concatenating Numbers

    Fractional Numbers

    3.2.1 Fundamentals of NumbersNumeric literals do not require any enclosing punctuation. You can specify a number using any valid numeric characters.Cach evaluates a number as syntactically valid, then converts it to canonical form.

    The syntactic requirements for a numeric literal are as follows:

    It can contain the decimal numbers 0 through 9, and must contain at least one of these number characters. It can containleading or trailing zeros.

    It can contain any number of leading plus and minus signs in any sequence. However, a plus sign or minus sign cannotappear after any other character, except the E scientific notation character. In a numeric expression a sign after anon-sign character is evaluated as an addition or subtraction operation. In a numeric string a sign after a non-signcharacter is evaluated as a non-numeric character, terminating the number portion of the string.

    Cach uses the PlusSign and MinusSign property values for the current locale to determine these sign characters (+and - by default); these sign characters are locale-dependent. To determine the PlusSign and MinusSign charactersfor your locale, invoke the GetFormatItem() method: WRITE ##class(%SYS.NLS.Format).GetFormatItem("PlusSign"),! WRITE ##class(%SYS.NLS.Format).GetFormatItem("MinusSign")

    It can contain at most one decimal separator character. In a numeric expression a second decimal separator results ina error. In a numeric string a second decimal separator is evaluated as the first non-numeric character,terminating the number portion of the string. The decimal separator character may be the first character or the lastcharacter of the numeric expression. The choice of decimal separator character is locale-dependent: American formatuses a period (.) as the decimal separator, which is the default. European format uses a comma (,) as the decimal sepa-rator. To determine the DecimalSeparator character for your locale, invoke the GetFormatItem() method: WRITE ##class(%SYS.NLS.Format).GetFormatItem("DecimalSeparator")

    Using Cach ObjectScript 19

    Numbers

  • It can contain at most one letter E (or e ) to specify a base-10 exponent for scientific notation. This scientificnotation character (E or e ) must be preceded by a number character or decimal point, and followed by either awhole number, or a single plus or minus sign followed by a whole number. It cannot be followed by a blank space, adecimal point, multiple plus and minus signs, or a fractional number. The base-10 exponent can contain leading zeros.See the ScientificNotation() method of the %SYSTEM.Process class, which controls use of this letter symbol.

    Numeric literal values do not support the following:

    They cannot contain numeric group separators. These are locale-dependent: American format uses commas, Europeanformat uses periods. You can use the $INUMBER function to remove numeric group separators, and the $FNUMBERfunction to add numeric group separators.

    They cannot contain currency symbols, hexadecimal letters, or other nonnumeric characters. They cannot contain blankspaces, except before or after a