Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling numbers with leading zeros in Tcl

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?

like image 949
Christopher Bruns Avatar asked Jan 21 '10 16:01

Christopher Bruns


1 Answers

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
}
like image 73
glenn jackman Avatar answered Sep 29 '22 09:09

glenn jackman