English 中文(简体)
Tcl - Variables
  • 时间:2024-11-03

Tcl - Variables


Previous Page Next Page  

In Tcl, there is no concept of variable declaration. Once, a new variable name is encountered, Tcl will define a new variable.

Variable Naming

The name of variables can contain any characters and length. You can even have white spaces by enclosing the variable in curly braces, but it is not preferred.

The set command is used for assigning value to a variable. The syntax for set command is,

set variableName value

A few examples of variables are shown below −

#!/usr/bin/tclsh

set variableA 10
set {variable B} test
puts $variableA
puts ${variable B}

When the above code is executed, it produces the following result −

10
test

As you can see in the above program, the $variableName is used to get the value of the variable.

Dynamic Typing

Tcl is a dynamically typed language. The value of the variable can be dynamically converted to the required type when required. For example, a number 5 that is stored as string will be converted to number when doing an arithmetic operation. It is shown below −

#!/usr/bin/tclsh

set variableA "10"
puts $variableA
set sum [expr $variableA +20];
puts $sum

When the above code is executed, it produces the following result −

10
30

Mathematical Expressions

As you can see in the above example, expr is used for representing mathematical expression. The default precision of Tcl is 12 digits. In order to get floating point results, we should add at least a single decimal digit. A simple example explains the above.

#!/usr/bin/tclsh

set variableA "10"
set result [expr $variableA / 9];
puts $result
set result [expr $variableA / 9.0];
puts $result
set variableA "10.0"
set result [expr $variableA / 9];
puts $result

When the above code is executed, it produces the following result −

1
1.1111111111111112
1.1111111111111112

In the above example, you can see three cases. In the first case, the spanidend and the spanisor are whole numbers and we get a whole number as result. In the second case, the spanisor alone is a decimal number and in the third case, the spanidend is a decimal number. In both second and third cases, we get a decimal number as result.

In the above code, you can change the precision by using tcl_precision special variable. It is shown below −

#!/usr/bin/tclsh

set variableA "10"
set tcl_precision 5
set result [expr $variableA / 9.0];
puts $result

When the above code is executed, it produces the following result −

1.1111
Advertisements