tags:

views:

127

answers:

3

Hi,

I am trying to substitute variable value inside array so as to update array values based on command line inputs. e.g. I am receiving IP address as command line argument for my TCL script and trying to update commands with recvd IP value.

My array is:

array set myArr { 1 myCmd1("192.268.2.1","abc.txt")
                  2 myCmd2("192.268.2.1","xyz.txt")
                  3 myCmd3("192.268.2.1","klm.txt")
                }

Here, "192.268.2.1" will actually be supplied as command line argument.

I tried doing

array set myArr { 1 myCmd1($myIP,"abc.txt")
                  2 myCmd2($myIP,"xyz.txt")
                  3 myCmd3($myIP,"klm.txt")
                }

and other combinations like ${myIP}, {[set $myIP]} but none is working.

Thanks in advance for any help/inputs.

A: 

try:

array set myArr [list myCmd1($myIP, "abc.txt") 2 myCmd2($myIP, "xyz.txt") ... ]

Why? Because when you write {$var} in Tcl, it means $var and not the contents of the variable var. If you use list to create the list instead of the braces, variables are still evaluated.

Miguel Ventura
That's more than a bit broken. The quoted bits `"abc.txt"` have a space before (multiple elements?) and a character after (parse error!).
Donal Fellows
+3  A: 

Use the list command

% set myIP 0.0.0.0
0.0.0.0
% array set myArr [list 1 myCmd1($myIP,"abc.txt") 2 myCmd2($myIP,"xyz.txt") 3 myCmd3($myIP,"klm.txt")]
% puts $myArr(1)
myCmd1(0.0.0.0,"abc.txt")
% puts $myArr(3)
myCmd3(0.0.0.0,"klm.txt")
%
Andrew Stein
+1  A: 

I think your code will be easier to understand and easier to maintain if you don't try to use array set in this instance. You can get away with it if you are careful (see answers related to using list) but there's really no reason to do it that way when a more readable solution exists.

Here's my solution:

set myArr(1) "myCmd1($myIP,\"abc.txt\")"
set myArr(2) "myCmd2($myIP,\"xyz.txt\")"
set myArr(3) "myCmd3($myIP,\"klm.txt\")"
Bryan Oakley