Tuesday, 1 April 2014

difference between the "eq" and "==" operators in TCL


TCL Background

Unlike many programming languages (such as Python) TCL stores all values as strings. By using operators or commands these values can be interpreted as different data types (such as integers, binary etc).
 

'eq' vs '=='

Though, on the surface, the 2 TCL operators 'eq' and '==' appear similar, ie  both return a boolean (i.e True or False) should the 2 values match. In fact they work extremely differently.

The difference between these 2 operators is that 'eq' is a string based operator, were as '==' is numerical based. Meaning that, as all values within TCL are strings, when using '==' both strings are converted to numbers.
 

Does it Matter ?

Firstly, extra clock cycles are required to convert each string to a number.
Secondly the numerical representation of the (string) isn't always as clear as you may think. Let me show you what I mean.

Below shows you some examples of how TCL coerces the data into a number,

Example,

set i_Dinesh 5
set f_Dinesh 5.0

# Test 1 
if { $i_Dinesh == $f_Dinesh } {
    puts "== Operator always compares as number\n"
} else {
    puts "== Operator always compares as strings\n"
}

# Test 2
if { $i_Dinesh eq $f_Dinesh } {
    puts "eq Operator always compares as number\n"
} else {
    puts "eq Operator always compares as strings\n"
}

O/P:

# Test1 --> == Operator always compares as number
# Test2 --> eq Operator always compares as strings