When Is a Number Not a Number?

Tcl’s primary data type is the string, but commands are free to interpret numeric strings as integers and floating-point values. Expr and incr are such commands; the evaluation mechanism in expr is also used for conditional testing in if, while, and for commands.

Tcl has a few rules for interpreting numbers, some of which are obvious. A string of digits is a decimal integer; with a decimal point or scientific notation, it’s a floating-point value. The two often overlooked number specifications are octal (base 8) and hexadecimal (base 16).

Tcl interprets a sequence of digits as an octal integer if it begins with a leading “0”. Numbers that begin with a leading “0x” are interpreted as base 16. Thus, “012” is decimal 10 and “0x100” is decimal 256. Sometimes hexadecimal values are easy to spot, since they contain a non-numeric character. Octal numbers are harder to recognize, since the string is composed of all numeric characters.

Unexpected results often arise when octal numbers are used inadvertently in expressions. To illustrate, assume you are writing a procedure to calculate a future date. Tcl’s clock command can return a date string in the same format as the Unix date program, and you begin by parsing out the day number of the month (we will ignore month and year rollover issues, as well as better possible implementations, for now), as in the following code:

set currentTime [clock seconds]
puts [clock format $currentTime]

produces the following output: ...

Get Tcl/Tk in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.