Narendra Kumar
Narendra Kumar

Reputation: 51

conversion string type into integer type in tcl script. like that a number is type of string and I want to increment it so how to fix it in tcl

How to convert string type into integer type in tcl script.like i fetch data from another file and it is string type. I want to increment that number which is string type so how to do it.

Upvotes: 1

Views: 25984

Answers (3)

Donal Fellows
Donal Fellows

Reputation: 137637

Tcl basically conceals all types from you; the value is the value regardless of its type, and all types are serializable as strings. It's common to say “everything is a string” and while that's formally inaccurate, the language conspires to make it appear as if it was true. Thus, if it looks like an integer, it is an integer from the perspective of incr (which is definitely the recommended idiomatic method of incrementing).

However, you can use the scan command to enforce integer-ness a bit more. (It's very much like sscanf() in C, if you know that.)

scan $myValue %d myInteger
incr myInteger

If you're going to use scan properly, you probably ought to check the result of it, which is the number of fields successfully scanned.

if {[scan $myValue %d%c myInteger dummy] != 1} {
    error "\"$myValue\" isn't a proper integer"
}
incr myInteger

You can also use string is integer; the -strict option should be used with this, for historical reasons.

if {![string is integer -strict $myValue]} {
    error "\"$myValue\" isn't a proper integer"
}
incr myValue

A lot of people don't bother with any of this and just increment the (variable containing the) value directly. It'll error out with a default error message if it is impossible.

incr myValue

Tcl always tries to tell you what went wrong when a problem occurs, and also where that problem actually was. Do remember to check the errorInfo global variable for a stack trace…

Upvotes: 6

Colin Macleod
Colin Macleod

Reputation: 4382

Ashish has the right answer. I tried to add an example as a comment on his answer but was unable to format it clearly, so I'm adding as a separate answer. Here is an example:

% set val "123"
123
% incr val
124
% puts $val
124
% set val "abc"
abc
% incr val
expected integer but got "abc"
% puts $val
abc
% 

Upvotes: 3

Ashish
Ashish

Reputation: 266

In Tcl everything is string. Read here http://wiki.tcl.tk/3018

If your are using incr to increment, it will interpret the value and if the value is interpreted to be an integer it will be incremented

Upvotes: 1

Related Questions