Handling numbers with leading zeros in Tcl

integer, octal, parsing, tcl

Solution

You'll want to read Tcl and Octal Numbers at the Tcl wiki. The canonical way is to treat your input as a string and use the `scan` command to extract the numbers. That leads to this, yes multiline, proc:

proc forceInteger { x } {
    set count [scan $x %d%s n rest]
    if { $count <= 0 || ( $count == 2 && ![string is space $rest] ) } {
        return -code error "not an integer: \"$x\""
    }
    return $n
}

Problem

I am having trouble in Tcl using numbers with leading zeros. I am parsing some numbers that can have leading zeros, such as "0012", which should be interpreted as the integer "twelve". ``` $ tclsh % set a 8 8 % set b 08 08 % expr $a - 1 7 % expr $b - 1 expected integer but got "08" (looks like invalid octal number) ``` What is the best way to handle numbers that might have a leading zeros in Tcl? On a side note, what would constitute a valid octal number in Tcl, if "08" is an invalid one?

Original source