Basic+ is a dynamically-typed language, and sometimes the system will attempt to change the type of a variable before using it in an operation. For example, if we have variable containing a numeric value as a string, and we attempt to compare it to a variable containing an actual numeric value, then the former will be coerced to a numeric format before the comparison, e.g.:
StrVar = "3" ; // String representing an integer NumVar = 7 ; // Integer Ans = ( StrVar = NumVar ) ; // Ans is FALSE$ and StrVar ; // is converted to an Integer
This works well in the vast majority of cases, but causes issues when attempting to compare strings that that could be numbers but really aren’t for the purposes of the comparison. For example, consider the following:
Var1 = "12" ; // String Var2 = "012" ; // String Ans = ( VarA = VarB ) ; // Ans = TRUE$ - should be FALSE$!!
The system first attempts to coerce the operands to a numeric format, and of course it can because they both evaluate to the number 12, and are therefore treated as equal. If you wish to compare them both as strings, the usual solution has been to change them so that they cannot be converted to a number, usually by prefixing them with a letter or symbol like so:
Var1 = "12" ; // String Var2 = "012" ; // String Ans = ( ( "X" : VarA ) = ( "X" : VarB ) ) ; // Ans = FALSE$
Although this works it hurts performance and can be a cumbersome solution.
OpenInsight 10.2 introduces a new set of extended comparison operators to Basic+ that ensure both operands are coerced to a string type (if needed) before being evaluated, and provides the following benefits:
- Removes the need for any concatenation thereby avoiding unnecessary copying
- Removes the need to check if a variable can be a number before the comparison
- Makes it obvious that you are performing a “string-only” comparison so your code looks cleaner.
The new (case-sensitive) operators are:
|_nes||Not Equals operator|
|_lts||Less Than operator|
|_les||Less Than Or Equals operator|
|_gts||Greater Than operator|
|_ges||Greater Than Or Equals operator|
There is also matching set of case-insensitive operators too:
|_eqsc||Case-Insensitive Equals operator|
|_nesc||Case-Insensitive Not Equals operator|
|_ltsc||Case-Insensitive Less Than operator|
|_lesc||Case-Insensitive Less Than Or Equals operator|
|_gtsc||Case-Insensitive Greater Than operator|
|_gesc||Case-Insensitive Greater Than Or Equals operator|
So we could write the previous example like so:
Var1 = "12" ; // String Var2 = "012" ; // String Ans = ( VarA _eqs VarB ) ; // Ans = FALSE$
Hopefully you’ll find this a useful addition when performing string-only comparisons in your own applications.