Setting Tcl Script Variables

In my new job, I deal with Tcl scripts, among other languages. In one of the scripts which I inherit, I often see lines such as:

set server testserver1
set server testserver2

The engineer who wrote this script often need to run this script against testserver1, but from time to time wants to run it against testserver2, so he simply edit the script and swap the two lines to achieve the desired effect. This approach works fine, but it requires to keep editing the script every time he wants to change the server. Besides the trouble of having to edit the script, which could unintentionally introduce bugs, I can think of a couple of cases where this solution is less than ideal. One case concerns the scalability. Instead of just one variable, what if the script needs to deal many? For example:

set server testserver1
set port 9900
set user test1
set password password1
set verbose 1

My solution to this problem is to customize these variables using command line parameters and with Tcl, it is so simple to do. In the script, right after the block that set these variables, insert the following line:

eval “variable $argv”

Here are some examples of what the command line arguments look like:

tclsh myscript.tcl server testserver2 port 9500
tclsh myscript.tcl user test2 password password2 verbose 0

That should do it. How does the whole thing works? Let examine the eval line. When a user invokes the script, Tcl stores the command line arguments in the variable argv, thus the string will expands to something like this:

variable server testserver2 port 9500

and the eval command executes that like. For those whole are unfamiliar with the Tcl’s variable command, the above is equivalent to:

set server testserver2
set port 9500

Thus accomplish our objectives with just one line of code. The caveat is one has to take care not to incorrectly spell the variable names because the script will set the wrong variable and goes on. As usual, I would like to hear comments, suggestions, and questions from the readers. Please post them under the comment section. Thank you for reading this post.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s