Jerre_111
Jerre_111

Reputation: 79

Tcl placing a value of a variable as the name a the variable

I'm having some issues with Tcl. I have a variable that has a string in it. Butt now I want this string to be the name of a next variable.

I have found some similar questions on the web, but these are all about placing the value from a variable into another variable. not using it as the name of the variable.

Here is a sample code to help explaining:

    foreach key [array names ::openedFiles] {
    puts $::openedFiles($key)
    set filename [file tail $::openedFiles($key)]
    set parts [split $filename .]
    set name [lindex $parts 0]

    puts $name

    $L1 create cell $name

    set "value of $name" [ layout create $::openedFiles($key) -dt_expand -log LUN.log]

So bassicly it has to do the following. The array has some path string in it. I get only the name of the file out of the path without the file extension.

Butt then I want to create a variable "cell" that is the value of "$name". So when the filename is "Test", the value of $name will be "Test" and I want to do the last line like this

     set Test [ layout create $::openedFiles($key) -dt_expand -log LUN.log]

So that the value of $name will be the name of the new variable. And so I can creat a variable with the name of all the values in the array.

Any help or pointers would be great!

Thank you very much!

Upvotes: 2

Views: 3806

Answers (2)

glenn jackman
glenn jackman

Reputation: 246744

I'm thinking you want upvar to create an "alias" variable name

$ tclsh
% set name Test
Test
% upvar 0 cell $name
% set cell 42
42
% puts $Test
42

Upvotes: 0

Johannes Kuhn
Johannes Kuhn

Reputation: 15163

The correct solution is to use $name as first parameter to set

set name "foo"
set $name "bar"
puts $foo ;# -> bar

But if you try to use $name it will yield foo, not bar (Which is what you do in your code according to the comments. I don't know why you need a variable whose name you don't know, but anyway:

puts [set $name] ;# -> bar

will give you the correct thing. The same works with objects:

set topcell [[set $name] topcell]

So I have to ask you: what do you want to do with the dynamic named variable then?

Upvotes: 4

Related Questions