Version 1 of Tcl and octal numbers

Updated 2001-11-13 15:03:59

Purpose: discuss the common pitfall of Tcl and octal numbers


Since Tcl many things in an obvious manner, people are frequently surprised when they try this kind of code:

 # somehow get today's date and time into MMM DDD YYY HH MM SS variables

 set newtime [expr $HH + 1]

and get an error at 8am. The problem - Tcl tries to do

  expr 08 + 1

and complains. 08, you see, isn't really the string of the decimal number that comes after 7. Instead, it is an error. Tcl sees the leading 0 and treats the digits after it as representing a base 8 number. But there are no 8s (or 9s) in a base 8 number. So it generates an error.


The fix is to use:

    scan $HH %d HH

which strips hazardous leading zeros. This is also safer than [string trimleft $HH 0] which can fail if $HH ever ends up containing "00" for example.

DKF


glennj: one potential pitfall of scan is that it might mask potential errors:

        set n 09blah42
        incr n

fails as expected with the error message:

        expected integer but got "09blah42"
        while evaluating {incr n}

However:

        set n 09blah42
        scan $n %d n
        incr n ;# ==> n is now 10

Application writers might actually want to trap an invalid entry like that.