Handling numbers with leading zeros in Tcl

Christopher Bruns picture Christopher Bruns · Jan 21, 2010 · Viewed 11.6k times · Source

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?

Answer

glenn jackman picture glenn jackman · Jan 21, 2010

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
}