4 ms·
Tcl has always allowed one to set the variable 'b' to 'c' with set a b set $a c And while it took some getting used to, one could do it in a disciplined fash
by julius_geezer 16y ago
Tcl has always allowed one to set the variable 'b' to 'c' with
set a b
set $a c
And while it took some getting used to, one could do it in a disciplined fashion, with a proc, and so create/set only certain variables in a calling proc. One did not have to spatter the whole scope with who knew what variables when pulling stuff out of an associative array.
- bradleyland 16y agoMany languages support "variable variables", but not as directly as Tcl and PHP. Any language that has the ability to evaluate strings as code can do it. # Ruby a = "some text" b = "a" eval b # => "some text" # Python a = "some text" b = "a" eval(b) # => "some text" # Javascript a = "some text"; b = "a"; eval(b) // => "some text" I've found the the more "quick and dirty" a language is, the simpler it is to use variable variables. And I don't mean quick and dirty as an insult. Bash supports this, and while I consider it quick and dirty, you can pry bash from my cold dead hands. # Bash a="some text" b="a" echo ${!b} # => "some text" Having said all that, using variable variables is a great way to piss off whoever has to maintain your code, so use them sparingly, and only when appropriate. There is little or no opportunity for context with variable variables. To add insult to injury, variable variables can result in gaping security holes as well. Think of the implications were an attacker able to substitute the value of the variable variable in any situation where the output is sent to the client. The attacker could randomly guess at variable names, dumping all manner of information. Anything in the global scope. Yikes! There are far better ways to do this in modern languages. For example, use a hash or dictionary construct. A Ruby example: # Ruby myhash = { :a => "some text" } b = "a" myhash[b.to_sym] # => "some text" A Python example using a dict: # Python mydict = { 'a' : "some text" } b = "a" mydict[b] # => "some text" A hash or dictionary gives you the opportunity to give your collection a meaningful name, scopes the evaluation to that object (so you can't arbitrarily retrieve variable data), and provides context.
- invisible 16y agoAnd make sure that register_globals is off for all that is holy.
- davidw 16y agoIn Tcl, $ is shorthand for [set foo], so that $foo == [set foo]. You can use this to do 'double indirection' if you really need to: set foo bar set bar 5 puts [set [set foo]] OTOH, $$foo does not work in Tcl.