Reputation: 3
TCL Program Sample:
proc fun { x } {
puts "$$x = $x"
}
set a 10
fun $a
In this above program which prints the output as $10 = 10
But i would like to get a = 10
has the output. The variable which passes the values has to be read and the corresponding values as well. Is there a way to read the variable name.
Upvotes: 0
Views: 2630
Reputation: 113
Obviously there is another way which I found on some other forum pages.
upvar is faster if accessing/using the var more than once, otherwise if only used once and it is a global var "[set ::[set name]]" could be better.
The proc below uses the global namespace to check it exists and sets a default value if not. The prints the current value.
proc setvardefault {name value} {
# if global var name does not exist set it to value
if {![info exists ::[set name] ]} { set ::[set name] $value }
# print the current value of global var name
puts "# INFOCHECK $name : [set ::[set name]]"
#upvar 1 $name var
#puts "# INFOCHECK $name : $var"
}
Only puts is needed for the printing part.
Upvotes: 0
Reputation: 13252
proc fun name {
upvar 1 $name var
puts "$name = $var"
}
set a 10
fun a
The upvar command takes a name and creates an alias of a variable with that name.
Documentation: proc, puts, set, upvar
Upvotes: 2
Reputation: 137567
If you've got a currently-supported version of Tcl (8.5 or 8.6), you can use info frame -1
to find out some information about the caller. That has all sorts of information in it, but we can do a reasonable approximation like this:
proc fun { x } {
set call [dict get [info frame -1] cmd]
puts "[lindex $call 1] = $x"
}
set a 10
fun $a
# ==> $a = 10
fun $a$a
# ==> $a$a = 1010
Now, the use of lindex
there is strictly wrong; it's Tcl code, not a list (and you'll see the difference if you use a complex command substitution). But if you're only ever using a fairly simple word, it works well enough.
Upvotes: 1
Reputation: 16428
% set x a
a
% set a 10
10
% eval puts $x=$$x
a=10
% puts "$x = [subst $$x]"
a = 10
% puts "$x = [set $x]"
a = 10
%
If you are passing the variable to a procedure, then you should rely on upvar
.
Upvotes: 0