SET (ObjectScript)
Synopsis
SET:pc setargument,...
S:pc setargument,...
where setargument can be:
variable=value
(variable-list)=value
Arguments
Argument | Description |
---|---|
pc | Optional — A postconditional expression. |
variable | The variable to set to the corresponding value. variable can be a local variable, a process-private global, a global, an object property, or a special variable. (Not all special variables can be set by an application; see documentation of individual special variables.) |
variable-list | A comma-separated list, enclosed in parentheses, that consists of one or more variable arguments. All of the variable arguments in variable-list are assigned the same value. |
value | A literal value, or any valid ObjectScript expression that evaluates to a value. Can be a JSON object or JSON array. |
Description
The SET command assigns a value to a variable. It can set a single variable, or set multiple variables using any combination of two syntactic forms. It can assign values to variables by specifying a comma-separated list of variable=value pairs. For example:
SET a=1,b=2,c=3
WRITE a,b,c
There is no restriction in the number of assignments you can perform with a single invocation of SET a=value,b=value,c=value,....
If a specified variable does not exist, SET creates it and assigns the value. If a specified variable exists, SET replaces the previous value with the specified value. Because SET executes in left-to-right order, you can assign a value to a variable, then assign that variable to another variable:
SET a=1,b=a
WRITE a,b
A value can be a string, a numeric, a JSON object, JSON array, or an expression that evaluates to one of these values. To define an “empty” variable, you can set the variable to the empty string ("") value.
Setting Multiple Variables to the Same Value
You can use SET to assign the same value to multiple variables by specifying a comma-separated list of variables enclosed in parentheses. For example:
SET (a,b,c)=1
WRITE a,b,c
You can combine the two SET syntactic forms in any combination. For example:
SET (a,b)=1,c=2,(d,e,f)=3
WRITE a,b,c,d,e,f
The maximum number of assignments you can perform with a single invocation of SET (a,b,c,...)=value is 128. Exceeding this number results in a <SYNTAX> error.
Restrictions on Setting Multiple Variables
-
$LIST: You cannot use SET (a,b,c,...)=value syntax to assign a value to a $LIST function on the left side of the equal sign. Attempting to do so results in a <SYNTAX> error. You must use SET a=value,$LIST(mylist,n)=value,c=value,... syntax when using $LIST to set one of the items.
-
$EXTRACT and $PIECE: You cannot use SET (a,b,c,...)=value syntax to assign a value to an $EXTRACT or $PIECE function on the left side of the equal sign if that function uses relative offset syntax. In relative offset syntax an asterisk represents the end of a string, and *-n and *+n represent a relative offset from the end of the string. For example, SET (x,$PIECE(mylist,"^",3))=123 is valid, but SET (x,$PIECE(mylist,"^",*))=123 results in an <UNIMPLEMENTED> error. You must use SET a=value,b=value,c=value,... syntax when setting one of these functions using relative offset.
-
Object Property: You cannot use SET (a,b,c,...)=value syntax to assign a value to an object property on the left side of the equal sign. Attempting to do so results in an <OBJECT DISPATCH> error with a message such as the following: Set property MyProp of class MyPackage.MyClass is not a direct reference and may not be multiple SET arg. You must use SET a=value,oref.MyProp=value,c=value,... syntax when setting an object property.
SET and Subscripts
You can set individual subscripted values (array nodes) for a local variable, process-private global, or a global. You can set subscripts in any order. If the variable subscript level does not already exist, SET creates it and then assigns the value. Each subscript level is treated as an independent variable; only those subscript levels set are defined. For example:
KILL myarray
SET 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 <UNDEFINED> error when invoked.
By default, you cannot set a null subscript. For example, SET ^x("")=123 results in a <SUBSCRIPT> error. However you can set %SYSTEM.Process.NullSubscripts()Opens in a new tab method to allow null subscripts for global and process-private global variables. You cannot set a null subscript for a local variable.
The maximum length of a subscript is 511 characters. Exceeding this length results in a <SUBSCRIPT> error.
The maximum number of subscript levels for a local variable is 255. The maximum number of subscript levels for a global variable depends on the subscript level names, and may exceed 255 levels. Attempting to set a local variable to more than 255 subscript levels (either directly or by indirection) results in a <SYNTAX> error. For further information on subscripted variables, refer to Formal Rules about Globals.
Arguments
pc
An optional postconditional expression. InterSystems IRIS executes the command if the postconditional expression is true (evaluates to a nonzero numeric value). InterSystems IRIS does not execute the command if the postconditional expression is false (evaluates to zero). For further details, refer to Command Postconditional Expressions.
variable
If the target variable does not already exist, SET creates it and then assigns the value. If it does exist, SET replaces the existing value with the assigned value.
The variable to receive the value resulting from the evaluation of value. It can be a local variable, a process-private global, a global variable. A local variable, process-private global, or global variable can be either subscripted or unsubscripted (see SET and Subscripts for further details). A global variable can be specified with extended global reference (see Formal Rules about Globals).
You can specify certain special variables, including $ECODE, $ETRAP, $DEVICE, $KEY, $TEST, $X, and $Y.
Local variables, process-private globals, and special variables are specific to the current process; they are mapped to be accessible from all namespaces. A global variable persists after the process that created it terminates.
A global is specific to the namespace in which it was created. By default, a SET assigns a global in the current namespace. You can use SET to define a global (^myglobal) in another namespace by using syntax such as the following: SET ^["Samples"]myglobal="Ansel Adams". If you specify a nonexistent namespace, InterSystems IRIS issues a <NAMESPACE> error. If you specify a namespace for which you do not have privileges, InterSystems IRIS issues a <PROTECT> error, followed by the global name and database path, such as the following: <PROTECT> ^myglobal,c:\intersystems\iris\mgr\.
A variable can be a piece or segment of a variable as specified in the argument of a $PIECE or $EXTRACT function.
A variable can be represented as an object property using obj.property or .. property syntax, or by using the $PROPERTY function. You can set an i%property instance variable reference using the following syntax:
SET i%propname = "abc"
SET accepts a variable name of any length, but it truncates a long variable name to 31 characters before assigning it a value. If a variable name is not unique within the first 31 characters this name truncation can cause unintended overwriting of variable values, as shown in the following example:
SET abcdefghijklmnopqrstuvwxyz2abc="30 characters"
SET abcdefghijklmnopqrstuvwxyz2abcd="31 characters"
SET abcdefghijklmnopqrstuvwxyz2abcde="32 characters"
SET abcdefghijklmnopqrstuvwxyz2abcdef="33 characters"
WRITE !,abcdefghijklmnopqrstuvwxyz2abc // returns "30 characters"
WRITE !,abcdefghijklmnopqrstuvwxyz2abcd // returns "33 characters"
WRITE !,abcdefghijklmnopqrstuvwxyz2abcde // returns "33 characters"
WRITE !,abcdefghijklmnopqrstuvwxyz2abcdef // returns "33 characters"
Special variables are, by definition, set by system events. You can use SET to assign a value to certain special variables. However, most special variables cannot be assigned a value using SET. See the reference pages for individual special variables for further details.
Refer to Variables for further details on variable types and naming conventions.
value
A literal value or any valid ObjectScript expression. Usually a value is a numeric or string expression. A value can be a JSON object or JSON array.
-
A numeric value is converted to canonical form before assignment: leading and trailing zeros, a plus sign or a trailing decimal point are removed. Conversion from scientific notation and evaluation of arithmetic operations are performed.
-
A string value is enclosed in quotation marks. A string is assigned unchanged, except that 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 no arithmetic operations are performed before assignment.
-
If a relational or logical expression is used, InterSystems IRIS assigns the truth value (0 or 1) resulting from the expression.
-
Object properties and object methods that return a value are valid expressions. Use the relative dot syntax (..) for assigning a property or method value to a variable.
JSON Values
You can use the SET command to set a variable to a JSON object or a JSON array. For a JSON object, the value is a JSON object delimited by curly braces. For a JSON array, the value is a JSON array delimited by square brackets.
Within these delimiters, the literal values are JSON literals, not ObjectScript literals. An invalid JSON literal generates a <SYNTAX> error.
-
String literal: You must enclose a JSON string in double quotes. To specify certain characters as literals within a JSON string, you must specify the \ escape character, followed by the literal. If a JSON string contains a double-quote literal character this character is written as \". JSON string syntax provides escapes for double quote (\"), backslash (\\), and slash (\/). Line space characters can also be escaped: backspace (\b), formfeed (\f), newline (\n), carriage return (\r), and tab (\t). Any Unicode character can be represented by a six character sequence: a backslash, followed by lowercase letter u, followed by four hexadecimal digits. For example, \u0022 specifies a literal double quote character; \u03BC specifies the Greek lowercase letter Mu.
-
Numeric literal: JSON does not convert numbers to ObjectScript canonical form. JSON has its own conversion and validation rules: Only a single leading minus sign is permitted; a leading plus sign is not permitted, multiple leading signs are not permitted. The “E” scientific notation character is permitted, but not evaluated. Leading zeros are not permitted; trailing zeros are preserved. A decimal separator must have a digit character on both sides of it. Therefore, the JSON numerics 0, 0.0, 0.4, and 0.400 are valid. A negative sign on a zero value is preserved.
For IEEE floating-point numbers, additional rules apply. Refer to the $DOUBLE function for details.
JSON fractional numbers are stored in a different format than ObjectScript numbers. ObjectScript floating point fractional numbers are rounded when they reach their maximum precision, and trailing zeros are removed. JSON packed BCD fractional numbers allow for greater precision, and trailing zeros are retained. This is shown in the following example:
SET jarray=[1.23456789123456789876000,(1.23456789123456789876000)] WRITE jarray.%ToJSON()
-
Special values: JSON supports the following special values: true, false, and null. These are literal values that must be specified as an unquoted literal in lowercase letters. These JSON special values cannot be specified using a variable, or specified in an ObjectScript expression.
-
ObjectScript: To include an ObjectScript literal or expression within a JSON array element or a JSON object value, you must enclose the entire string in parentheses. You cannot specify ObjectScript in a JSON object key. ObjectScript and JSON use different escape sequence conventions. To escape a double quote character in ObjectScript, you double it. In the following example, a JSON string literal and an ObjectScript string literal are specified in a JSON array:
SET jarray=["This is a \"good\" JSON string",("This is a ""good"" ObjectScript string")] WRITE jarray.%ToJSON()
The following JSON array example specifies an ObjectScript local variable and performs ObjectScript numeric conversion to canonical form:
SET str="This is a string" SET jarray=[(str),(--0007.000)] WRITE jarray.%ToJSON()
The following example specifies an ObjectScript function in a JSON object value:
SET jobj={"firstname":"Fred","namelen":($LENGTH("Fred"))} WRITE jobj.%ToJSON()
JSON Object
A value can be a JSON object delimited by curly braces. The variable is set to an OREF, such as the following: 3@%Library.DynamicObject. You can use the ZWRITE command with a specified local variable name to display the JSON value:
SET jobj={"inventory123":"Fred's \"special\" bowling ball"}
ZWRITE jobj
You can use the %Get() method to retrieve the value of a specified key using the OREF. You can resolve the OREF to the full JSON object value using the %ToJSON() method. This is shown in the following example:
SET jobj={"inventory123":"Fred's \"special\" bowling ball"}
WRITE "JSON object reference = ",jobj,!
WRITE jobj.%Get("inventory123")," (data value in ObjectScript format)",!
WRITE jobj.%Get("inventory123",,"json")," (data value in JSON format)",!
WRITE jobj.%ToJSON()," (key and data value in JSON format)"
A valid JSON object has the following format:
-
Begins with an open curly brace, ends with a close curly brace. The empty object {} is a valid JSON object.
-
Within the curly braces, a key:value pair or a comma-separated list of key:value pairs. Both the key and the value components are JSON literals, not ObjectScript literals.
-
The key component must be a JSON quoted string literal. It cannot be an ObjectScript literal or expression enclosed in parentheses.
-
The value component can be a JSON string or a JSON numeric literal. These JSON literals follow JSON validation criteria. A value component can be an ObjectScript literal or expression enclosed in parentheses. The value component can be specified as a defined variable specifying a string, a numeric, a JSON object, or a JSON array. The value component can contain nested JSON objects or JSON arrays. A value component can also be one of the following three JSON special values: true, false, null, specified as an unquoted literal in lowercase letters; these JSON special values cannot be specified using a variable.
The following are all valid JSON objects: {"name":"Fred"}, {"name":"Fred","city":"Bedrock"}, {"bool":true}, {"1":true,"0":false,"Else":null}, {"name":{"fname":"Fred","lname":"Flintstone"},"city":"Bedrock"}, {"name":["Fred","Wilma","Barney"],"city":"Bedrock"}.
A JSON object can specify a null property name and assign it a value, as shown in the following example:
SET jobj={}
SET jobj.""="This is the ""null"" property value"
WRITE jobj.%Get(""),!
WRITE "JSON null property object value = ",jobj.%ToJSON()
Note that the returned JSON string uses the JSON escape sequence (\") for a literal double quote character.
You can use the %Set()Opens in a new tab method to add a key:value pair to a JSON object.
You can use the %Get()Opens in a new tab method to return the value of a specified key in various formats. The syntax is:
jobj.%Get(keyname,default,format)
The default argument is the value returned if keyname does not exist.
The format argument specifies the format for the returned value. If no format is specified, the value is returned in ObjectScript format; if format="json", the value is returned in JSON format; if format="string", all string and numeric values are returned in ObjectScript format, but the JSON true and false special values are returned as JSON alphabetic strings rather than boolean integers; the JSON null special value is returned in ObjectScript format as a zero-length null string. This is shown in the following example:
SET x={"yep":true,"nil":null}
WRITE "IRIS: ",x.%Get("yep")," JSON: ",x.%Get("yep",,"json")," STRING: ",x.%Get("yep",,"string"),!
/* IRIS: 1 JSON: true STRING: true */
WRITE "IRIS: ",x.%Get("nil")," JSON: ",x.%Get("nil",,"json")," STRING: ",x.%Get("nil",,"string")
/* IRIS: JSON: null STRING: */
For further details, see Using JSON.
JSON Array
A value can be a JSON array delimited by square brackets. The variable is set to an OREF, such as the following: 1@%Library.DynamicArray. You can use the ZWRITE command with a specified local variable name to display the JSON value:
SET jary=["Fred","Wilma","Barney"]
ZWRITE jary
You can use the %Get()Opens in a new tab method to retrieve the value of a specified array element (counting from 0) using the OREF: %Get(n) returns the ObjectScript value; %Get(n,,”json”) returns the JSON value. %Get(n,”no such element”,”json”) specifies a default value to return if the specified array element does not exist. You can resolve the OREF to the full JSON array value using the %ToJSON() function. This is shown in the following example:
SET jary=["Fred","Wilma","Barney"]
WRITE "JSON array reference = ",jary,!
WRITE jary.%Get(1)," (array element value in ObjectScript format)",!
WRITE jary.%Get(1,,"json")," (array element value in JSON format)",!
WRITE jary.%ToJSON()," (array values in JSON format)"
A valid JSON array has the following format:
-
Begins with an open square bracket, ends with a close square bracket. The empty array [] is a valid JSON array.
-
Within the square brackets, an element or a comma-separated list of elements. Each array element can be a JSON string or JSON numeric literal. These JSON literals follow JSON validation criteria. An array element can be an ObjectScript literal or expression enclosed in parentheses. An array element can be specified as a defined variable specifying a string, a numeric, a JSON object, or a JSON array. An array element can contain one or more JSON objects or JSON arrays. An array element can also be one of the following three JSON special values: true, false, null, specified as an unquoted literal in lowercase letters; these JSON special values cannot be specified using a variable.
The following are all valid JSON arrays: [1], [5,7,11,13,17], ["Fred","Wilma","Barney"], [true,false], ["Bedrock",["Fred","Wilma","Barney"]], [{"name":"Fred"},{"name":"Wilma"}], [{"name":"Fred","city":"Bedrock"},{"name":"Wilma","city":"Bedrock"}], [{"names":["Fred","Wilma","Barney"]}].
You can use the %Push()Opens in a new tab method to add a new element to the end of the array. You can use the %Set()Opens in a new tab method to add a new array element or update an existing array element by position.
For further details, see Using JSON.
SET Command with Objects
The following example contains three SET commands: the first sets a variable to an OREF (object reference); the second sets a variable to the value of an object property; the third sets an object property to a value:
SET myobj=##class(%SQL.Statement).%New()
SET dmode=myobj.%SelectMode
WRITE "Default select mode=",dmode,!
SET myobj.%SelectMode=2
WRITE "Newly set select mode=",myobj.%SelectMode
Note that dot syntax is used in object expressions; a dot is placed between the object reference and the object property name or object method name.
To set a variable with an object property or object method value for the current object, use the double-dot syntax:
SET x=..LastName
If the specified object property does not exist, InterSystems IRIS issues a <PROPERTY DOES NOT EXIST> error. If you use double-dot syntax and the current object has not been defined, InterSystems IRIS issues a <NO CURRENT OBJECT> error.
For further details, refer to Object-Specific ObjectScript Features.
The following command sets x to the value returned by the GetNodeName() method:
SET x=##class(%SYS.System).GetNodeName()
WRITE "the current system node is: ",x
A SET command for objects can take an expression with cascading dot syntax, as shown in the following examples:
SET x=patient.Doctor.Hospital.Name
In this example, the patient.Doctor object property references the Hospital object, which contains the Name property. Thus, this command sets x to the name of the hospital affiliated with the doctor of the specified patient. The same cascading dot syntax can be used with object methods.
A SET command for objects can be used with system-level methods, such as the following data type property method:
SET x=patient.NameIsValid(Name)
In this example, the NameIsValid() method returns its result for the current patient object. NameIsValid() is a boolean method generated for data type validation of the Name property. Thus, this command sets x to 1 if the specified name is a valid name, and sets x to 0 if the specified name is not a valid name.
SET Using an Object Method
You can specify an object method on the left side of a SET expression. The following example specifies the %Get() method:
SET obj=##class(test).%New() // Where test is class with a multidimensional property md
SET myarray=[(obj)]
SET index=0,subscript=2
SET myarray.%Get(index).md(subscript)="value"
IF obj.md(2)="value" {WRITE "success"}
ELSE {WRITE "failure"}
Setting a List of Variables to an Object
When using SET with objects, multiple assignments set all of the variables in a list to the same OREF, as shown in the following examples:
SET (a,b,c)=##class(Sample.Person).%New()
SET (dyna1,dyna2,dyn3) = ["default","default"]
To assign each variable a separate OREF, issue a separate SET command for each assignment, as shown in the following examples:
SET a=##class(Sample.Person).%New()
SET b=##class(Sample.Person).%New()
SET c=##class(Sample.Person).%New()
SET dyna1 = ["default","default"]
SET dyna2 = ["default","default"]
SET dyna3 = ["default","default"]
You can also use the #dim preprocessor directive to assign all of the variables in a list to individual OREFs, as shown in the following examples:
#dim a,b,c As %ClassDefinition = ##class(Sample.Person).%New()
#dim dyn1,dyn2,dyn3 As %DynamicArray = ["default","default"]
Examples
The following example specifies multiple arguments for the same SET command. Specifically, the command assigns values to three variables. Note that arguments are evaluated in left-to-right order.
SET var1=12,var2=var1*3,var3=var1+var2
WRITE "var1=",var1,!,"var2=",var2,!,"var3=",var3
The following example shows the (variable-list)=value form of the SET command. It shows how to assign the same value to multiple variables. Specifically, the command assigns the value 0 to three variables.
SET (sum,count,average)=0
WRITE "sum=",sum,!,"count=",count,!,"average=",average
The following example sets a subscripted global variable in a different namespace using extended global reference.
NEW $NAMESPACE
SET $NAMESPACE="%SYS"
SET ^["user"]nametest(1)="fred"
NEW $NAMESPACE
SET $NAMESPACE="USER"
WRITE ^nametest(1)
KILL ^nametest
Order of Evaluation
InterSystems IRIS evaluates the arguments of the SET command in strict left-to-right order. For each argument, it performs the evaluation in the following sequence:
-
Evaluates occurrences of indirection or subscripts to the left of the equal sign in a left-to-right order to determine the variable name(s). For more information, refer to the Indirection Operator reference page.
-
Evaluates the expression to the right of the equal sign.
-
Assigns the expression to the right of the equal sign to the variable name or references to the left of the equal sign.
Transaction Processing
A SET of a global variable is journaled as part of the current transaction; this global variable assignment is rolled back during transaction rollback. A SET of a local variable or a process-private global variable is not journaled, and thus this assignment is unaffected by a transaction rollback.
Defined and Undefined Variables
Most ObjectScript commands and functions require that a variable be defined before it is referenced. By default, attempting to reference an undefined variable generates an <UNDEFINED> error. Attempting to reference an undefined object generates a <PROPERTY DOES NOT EXIST> or <METHOD DOES NOT EXIST> error. Refer to $ZERROR for further details on these error codes.
You can change InterSystems IRIS behavior when referencing an undefined variable by setting the %SYSTEM.Process.Undefined()Opens in a new tab method.
The READ command and the $INCREMENT function can reference an undefined variable and assign a value to it. The $DATA function can take an undefined or defined variable and return its status. The $GET function returns the value of a defined variable; optionally, it can also assign a value to an undefined variable.
SET with $PIECE and $EXTRACT
You can use the $PIECE and $EXTRACT functions with SET on either side of the equals sign. For detailed descriptions, refer to $PIECE and $EXTRACT.
When used on the right side of the equals sign, $PIECE and $EXTRACT extract a substring from a variable and assign its value to the specified variable(s) on the left side of the equals sign. $PIECE extracts a substring using a specified delimiter, and $EXTRACT extracts a substring using a character count.
For example, assume that variable x contains the string "HELLO WORLD". The following commands 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=",z
When used on the left side of the equals sign, $PIECE and $EXTRACT insert the value from the expression on the right side of the equals sign into the specified portion of the target variable. Any existing value in the specified portion of the target variable is replaced by the inserted value.
For example, assume that variable x contains the string "HELLO WORLD" and that variable y 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=",x
The $EXTRACT function extracts the string "THERE" from variable y and the $PIECE function 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, the system creates it and pads it with delimiters (in the case of $PIECE) or with spaces (in the case of $EXTRACT) as needed.
In the following example, SET $EXTRACT is used to insert the value of z into strings x and y, overwriting the existing values:
SET x="HELLO WORLD"
SET y="OVER EASY"
SET z="THERE"
SET $EXTRACT(x,7,11)=z
SET $EXTRACT(y,*-3,*)=z
WRITE "edited x=",x,!
WRITE "edited y=",y
Variable x now contains the string "HELLO THERE" and y contains the string "OVER THERE". Note that because one of the SET $EXTRACT operations in this example uses a negative offset (*-3) these operations must be done as separate sets. You cannot set multiple variables with a single SET using enclosing parentheses if any of the variables uses negative offset.
In the following example, assume that the global array ^client is structured so that the root node contains the client’s name, with subordinate nodes containing the street address and city. For example, ^client(2,1,1) would contain the city address for the second client stored in the array.
Assume further that the city node (x,1,1) contains field values identifying the city, state abbreviation, 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 the following code each use the $PIECE function to assign a specific portion of the array node value to the appropriate local variable. Note that in each case $PIECE references the comma (",") as the string separator.
ADDRESSPIECE
SET ^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 ",zip
QUIT
The $EXTRACT function could be used to perform the same operation, but only if the fields were fixed length and the lengths were known. For example, if the city field was known to contain only up to 9 characters and the state and ZIP fields were known to contain only 2 and 5 characters, respectively, the SET commands could be coded with the $EXTRACT function as follows:
ADDRESSEXTRACT
SET ^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 ",zip
QUIT
Notice 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".
StringPiece
SET A="1^2^3^4^5^6^7^8^9"
SET $PIECE(A,"^")="abc"
WRITE !,"A=",A
QUIT
A="abc^2^3^4^5^6^7^8^9"
The following example uses $EXTRACT to replace the first character in A (again, a 1) with the string "abc".
StringExtract
SET A="123456789"
SET $EXTRACT(A)="abc"
WRITE !,"A=",A
QUIT
A="abc23456789"
The following example replaces the third through sixth pieces of A with the string "abc" and replaces the first character in the variable B with the string "abc".
StringInsert
SET 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=",B
QUIT
A="1^2^abc^7^8^9"
B="abc23"
The following example sets $X, $Y, $KEY, and the fourth piece of a previously undefined local 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 (^).
SetVars
SET ($X,$Y,$KEY,$PIECE(A,"^",4))=20,X=$X,Y=$Y,K=$KEY
WRITE !,"A=",A,!,"K=",K,!,"X=",X,!,"Y=",Y
QUIT
A="^^^20" K="20" X=20 Y=20
SET with $LIST and $LISTBUILD
The $LIST functions create and manipulate lists. They encode the length (and type) of each element within the list, rather than using an element delimiter. They then use the encoded length specifications to extract specified list elements during list manipulation. Because the $LIST functions do not use delimiter characters, the lists created using these functions should not 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 returns the specified element of the specified list.
-
$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 the following tasks:
-
SET $LIST replaces the specified element(s) with the value given on the right side of the equal sign.
SET A=$LISTBUILD("red","blue","green","white") WRITE "Created list A=",$LISTTOSTRING(A),! SET $LIST(A,2)="yellow" WRITE "Edited list A=",$LISTTOSTRING(A)
SET A=$LISTBUILD("red","blue","green","white") WRITE "Created list A=",$LISTTOSTRING(A),! SET $LIST(A,*-1,*)=$LISTBUILD("yellow") WRITE "Edited list A=",$LISTTOSTRING(A)
You cannot use parentheses with SET $LIST to assign the same value to multiple variables.
-
SET $LISTBUILD extracts several elements of a list in a single operation. The arguments of $LISTBUILD are variables, 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 of interest.
In the following example, $LISTBUILD (on the right side of the equal sign) is first used to return a list. Then $LISTBUILD (on the left side of the equal sign) is used to extract two items from that list and set the appropriate variables.
SetListBuild SET J=$LISTBUILD("red","blue","green","white") SET $LISTBUILD(A,,B)=J WRITE "A=",A,!,"B=",B
In this example, A="red" and B="green".