I have set 3 global variables as below in a file FILE1:
set VAR1 2
set VAR2 3
set VAR3 4
Now I want to use these 3 variables in another file FILE2 in iterative way:
Means, something like this:
for {set a 1} {$a < 4} {incr a} {
$::VAR$a
}
where VAR$a - should be incremented each time to VAR1,VAR2,VAR3 etc...
But if I try like this using the global variable I get error in tcl
Any better solution for this?
Either make your meaning clearer to the interpreter
set ::VAR$a
(you are aware that this is just getting the variable's value without doing anything with the value, that is, a pointless operation, right?)
Or use an array, which is basically a two-part variable name:
set ::VAR($a)
in which case you need to initialize as an array:
set VAR(1) 2
etc, or
array set VAR {1 2 2 3 3 4}
The reason why $::VAR$a doesn't always work is AFAICT that the variable substitution becomes ambiguous. Given these definitions:
set foobar 1
set a foo
set b bar
what should $a$b substitute into? To avoid ambiguity, the substitution rules are kept simple: the first substitution stops before the second dollar sign, and the whole expression evaluates to the string foobar. How about $$a$b to substitute the value of foobar, then? No, a dollar-sign followed directly by a character that can't be a part of a variable name means that the first dollar sign becomes just a dollar sign: you get $foobar. The best way to handle this is to reduce the levels of substitution using the set command to get a value: set $a$b. Bottom line: variable substitution using $ does not always work well, but the set always does the job.
Documentation:
set,
Summary of Tcl language syntax
Related
I'm learning about Tcl just now. I've seen just a bit of it, I see for instance to create a variable (and initialize it) you can do
set varname value
I am familiarizing with the fact that basically everything is a string, such as "value" above, but "varname" gets kind of a special treatment I guess because of the "set" built-in function, so varname is not interpreted as a string but rather as a name.
I can later on access the value with $varname, and this is fine to me, it is used to specify varname is not to be considered as a string.
I'm now reading about lists and a couple commands make me a bit confused
set colors {"aqua" "maroon" "cyan"}
puts "list length is [llength $colors]"
lappend colors "purple"
So clearly "lappend" is another one of such functions like set that can interpret the first argument as a name and not a string, but then why didn't they make it llength the same (no need for $)?
I'm thinking that it's just a convention that, in general, when you "read" a variable you need the $ while you don't for "writing".
A different look at the question: what Tcl commands are appropriate for list literals?
It's valid to count the elements of a list literal:
llength {my dog has fleas}
But it doesn't make sense to append a new element to a literal
lappend {my dog has fleas} and ticks
(That is actually valid Tcl, but it sets the odd variable ${my dog has fleas})
this is more sensible:
set mydog {my dog has fleas}
lappend mydog and ticks
Names are strings. Or rather a string is a name because it is used as a name. And $ in Tcl means “read this variable right now”, unlike in some other languages where it really means “here is a variable name”.
The $blah syntax for reading from a variable is convenient syntax that approximately stands in for doing [set blah] (with just one argument). For simple names, they become the same bytecode, but the $… form doesn't handle all the weird edge cases (usually with generated names) that the other one does. If a command (such as set, lappend, unset or incr) takes a variable name, it's because it is going to write to that variable and it will typically be documented to take a varName (variable name, of course) or something like that. Things that just read the value (e.g., llength or lindex) will take the value directly and not the name of a variable, and it is up to the caller to provide the value using whatever they want, perhaps $blah or [call something].
In particular, if you have:
proc ListRangeBy {from to {by 1}} {
set result {}
for {set x $from} {$x <= $to} {incr x $by} {
lappend result $x
}
return $result
}
then you can do:
llength [ListRangeBy 3 77 8]
and
set listVar [ListRangeBy 3 77 8]
llength $listVar
and get exactly the same value out of the llength. The llength doesn't need to know anything special about what is going on.
I have to print multiple variables in a single puts like this
puts "$n1_$n2_$n3_$n4"
where n1 , n2 , n3 , n4 are 4 variables.
It wont print and will show error n1_ : no such variable
Expected output should be something like this (example)
01_abc_21_akdd
Variable names in Tcl can be any string in Tcl, there are no restrictions but if you want to use special characters (those not in the range of a-z, 0-9 and _, and letters in different languages depending on the platform and locale), you have to either brace the expression names or use other workarounds (like with the answer of Hoodiecrow).
What this means is that if you have a variable named abc.d, and if you use $abc.d, the Tcl engine will try to find the variable $abc because . is not a 'normal' character.
But if you have a variable named abc and use $abcd, or $abc_d, then the engine will start looking for the variables abcd or abc_d and not abc.
Because of this, you will have to use braces between the variable name for example:
${n1}
The reason why putting a backslash works is that \ is not a 'normal' character and after reading the above, it should be a little more obvious how things worked.
There are a few things that yet can go in variable names which don't need bracing and still mean something, except that something is 'special':
::: This is usually used for scoping purposes. For instance if you have a global variable named my_var, you can also use $::my_var to refer to it. Here :: tells Tcl that my_var is a global variable. Note that if there are more than two : in a row they will not add up:
% set ::y 5
5
% set ::::y
5
% set :::y
5
:: is usually used to define the namespace the variable is in. For example, $mine::var is a variable called var in the namespace with a name of mine.
(): These are used for arrays. $arr(key) is a variable with two parts: the array name arr and the key name key. Note: you can have an array named and a key named because...
% set () abc
abc
% puts $()
abc
% array get ""
{} abc
There might be some more, but those are the basics you could look out for.
Two other ways:
puts "${n1}_${n2}_${n3}_${n4}"
puts [format "%s_%s_%s_%s" $n1 $n2 $n3 $n4]
Documentation: format
(Note: the 'Hoodiecrow' mentioned in Jerry's answer is me, I used that nick earlier.)
I am a newbie in TCL Programming. I was having confusion about curly braces, answer to this question tcl curly braces cleared most of my doubts.
I can understand $var, {var}, and {$var}, But recently I came across another use of curly braces, ${var}. How is this interpreted by TCL?
I have seen this is used when accessing variables in namespaces when namespaces name is in variable.
for example:
set x myNamespace ;#myNamespace is name of namespace
puts [set ${x}::var1] ;#var1 is variable in the namespace
It gives error when you don't use curly braces around 'x'.
And I also don't understand the difference between {a b c} and [list a b c], what is the difference in result of interpretation of these two commands by TCL interpretation.
elaborated explanation would be highly appreciated.
See rule 8 of the manual. It allows you to have variable names that might get mis-interpreted. For instance:
% set dotted.name 1
1
% puts $dotted.name
can't read "dotted": no such variable
% puts ${dotted.name}
1
Read section 8 carefully as it actually explains all this quite explicitly.
Update to answer edited question
In the example you provide using a namespace name in a variable you must consider section 8 part 1: a variable name includes letters, digits, underscores and namespace separators. This means that x::var1 is a valid variable name. So $x::var1 will attempt to dereference the var1 variable in the x namespace. As this is not what you meant, you must dereference your x variable separately. There are two ways to do this. You can either use the set command or the dollar operator.
set x myNamespace
puts [set ${x}::var1]
puts [set [set x]::var1]
The two puts statements are equivalent here with the second version showing an explicit separate pass to obtain the value of the x variable which is then substituted into the expression for the outer set command. The same occurs in the first version but just uses the grouping operator to restrict the effect of the dollar to the x variable name.
x is a list of device names (device-1, device-2, device-3)
There is a variable created for each device1 by concatenating the string port so you end up with $device-1port.
looping over x creates
[expr $${x}port-2000 ] #x is device-1 so it is trying $device-1port-2000 which throws error.
I would like to get the numeric value of $device-1port into a variable without a dash.
set xvar $${x}port
[expr $xvar-2000 ]
or can i wrap the $${x}port in something within the expr statement.
To read a variable with interpolations in its name, use single-argument set:
set withoutadash [set device-${x}port]
Generally, it's better to use arrays for this kind of thing.
One of the nicest ways to work with such complex variables is to use the upvar command to make a local “nice” alias to the variable. In particular, upvar 0 makes a local alias to a local variable; slightly tricky, but a known technique.
upvar 0 ${x}port current_port
Now, we have any read, write or unset of current_port is the same as a read/write/unset of the port with the awkward name, and you can write your code simply:
puts [expr { $current_port - 2000 }]
set current_port 12345
# etc.
The alias will be forgotten at the end of the current procedure.
Of course, you probably ought to consider using arrays instead. They're just simpler and you don't need to work hard with computed variable names:
set x 1
set device($x,port) 12345
puts [expr {$device($x,port) - 2000}]
here is an example of what I'm trying to do.
set t SNS
set ${t}_top [commands that return value]
Want to get the info stored at ${t}_top
puts “${t}_top”
SNS_top (really want the data stored there?)
Thought it was : ${{$t}_top} , maybe that was perl but {} inside the {} do not work.
One of the really interesting things about Tcl is that you can create variable names dynamically, as you are doing in the question you posted. However, this makes it tricky to write and makes your code harder than necessary to understand.
Instead of trying to figure out how to do the equivalent of ${{$t}_top}, it's arguably better to avoid the problem altogether. You can do that by using an associative array.
For example, instead of this:
set t SNS
set ${t}_top [commands that return value]
...
puts [set ${t}_top]
Do this:
set t SNS
set top($t) [commands that return value]
...
puts $top($t)
Most people agree that the latter example is much more readable.
try
puts [set ${t}_top]
Each line of code in Tcl is run through the substitution phase (in which variables, commands, etc are substituted) only once... generally. As such, something like
set var1 1
set var2 var1
set var3 $$var2
won't wind up with var3 equaling 1, since the substitutor will replace "$$var2" with "the value of the variable named '$var2' (literally)" and stop.
What you need it to either go about things another way or to force another round of substitution. The other way is generally to avoid needing a second round of substitution (as shown by Jackson):
set var3 [set $var2]
Here, the $var2 is replaced, during substitution, by "var1"... then [set var1] returns 1... then var3 gets set to the value of "1"... and you're good.
The syntax
puts [expr $${t}_top]
works as well, and avoids using the 'set' operation so a syntax error shouldn't overwrite your data.