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

global var

This command is used to declare a global variable. It is only required within the body of a procedure.

incr var value

This command will increment the value stored in var by the value provided. Value must contain an integer. If no value is passed, the command defaults to increase the value by one (1).

set var value

This command sets var to the value provided. Conversely, the value may contain a Tcl command, the results of which will be utilized as the final value. The Command must be enclosed within square braces.

unset var var var

The unset command deletes one or more variables. If the nocomplain flag is passed as the first argument, all the errors are suppressed. Variable names are NOT comma delimited.

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.32.222