Skip to content
Tcl Source Code View Ticket
Login

View Ticket

expr comparison operator result does not follow the documentation

Closed / Invalidaa69bce71e214872af462de3a3050a46eec61385Created 3 years agoUpdated 3 years ago
Descriptionplain2024-03-11 21:26:09
I wanted to know if the 'expr' command when using the < operator compares its arguments as numbers or as strings. So I checked the documentation for expr. This is what it says:

>> These operators may be applied to strings as well as numeric operands, in which case string comparison is used. <<

https://tcl.tk/man/tcl/TclCmd/expr.htm#M12

From this, I expect that I can compare two string, or I can compare two numbers, both will be ok for the operator. It should always compare as strings - as it says that strig comparison is used.

But the implementation does not follow it

% expr {12<2}
0
% expr {"12"<"2"}
0

When compared as strings the first should be smaller than the second. The result should be 1.

The string comparison should be like this:

% string compare 12 2
-1

I.e. the first string is less than the second.

Or maybe the documentation is wrong?
sebresmarkdown2024-03-11 23:06:37

From point of view of the Tcl-parser the tokens "12" and 12 (but also {12}) are the same. See Tcl language syntax for basic details how Tcl-parser works.

The mentioned documentation clarifying only that there is a fallback operation which would compare them as string, if one of the operands is not numeric. However by the operators like <, it'd always prefer numeric comparison (no matter whether it is enclosed in quotes or not).

Since 8.7 (TIP 461), there is a lot of other operators which always use string comparison.

In this case:

% expr {12 lt 2}
1
% expr {"12" lt "2"}
1
% expr {{12} lt {2}}
1

(again, no matter they are enclosed in quotes or not).

Before that (for 8.5 or 8.6) there are only two string comparison operators available - eq and ne, so one'd use [string compare] either.

Another possibility would be to use the trick with string-concatenation to word-tokens, in order to force string comparison:

% set a 12; set b 2; expr {$a < $b}
0
% set a 12; set b 2; expr {"s$a" < "s$b"}
1
oehharwiki2024-03-12 08:14:04

please use "string compare" to compare strings in a relyable way with TCL 8.6.

Log in (anonymous is fine) to add a comment.