Variables
As with all the programming languages, it is the variable that allows for true flexibility and usability. Tcl differs from some scripted languages, as, there is no need to implicitly declare the variable type. For example a variable of "3" will be stored within Tcl with the same internal representation, as if it have been defined as the integer 3. If the variable is then used in a calculation, Tcl will then convert it to an integer for computation. This is referred to as shimmering in Tcl.
Basic variable commands
Variable command |
Explanation |
---|---|
|
This command is used to declare a global variable. It is only required within the body of a procedure. |
|
This command will increment the value stored in |
|
This command sets |
|
The unset command deletes one or more variables. If the |
In the following examples, we will create a variable with an integer value of 3, increment that value, and then delete the variable.
Getting Ready
To complete the following examples, launch your Tcl Shell as appropriate, based on your operating platform.
How to do it…
For setting a variable, enter the following command:
% set x 3 3
How it works…
The set command returns 3
to confirm that the value was set correctly.
There's more…
Enter the following command:
% incr x 3 6
The incr
command has increased the value of x
by 3
and returned 6
.
Unsetting a variable
Enter the following command:
% unset x %
The unset
command deletes the variable x
and simply returns to the command prompt.
If the named variable does not exist, an error will be generated, as shown in the following example:
% unset y can't unset "y": no such variable
To avoid error reporting for variables, include the nocomplain
switch, as illustrated here:
% unset nocomplain y %
In this instance, the unset
command has ignored the error and simply returned to the command line. This is invaluable when passing a list of variables to unset
to ensure non-existing variables do not generate an error. Additionally, you should insert --
(double minus, no spaces) after all the options, in order to remove a variable that has the same name as the many options.