Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
773 views
in Technique[技术] by (71.8m points)

syntax - Why doesn't Tcl use a dollar sign before variable names when calling "set"?

I am just going to use Perl as a comparison here:

$foo = 5;
print $foo;

sets the variable $foo to 5, and then prints the contents of the variable (notice that $foo is always accessed as $foo).

In Tcl:

set foo 5
puts $foo

does the same thing as the Perl counterpart.

Why doesn't Tcl set variables with the "$", but need a "$" to access a variable? Why is this true for procedures too (e.g.proc bar {spam eggs} {...})? To me, the Tcl code looks like this (in pseudocode):

"foo" = 5 # Setting a string?
puts $foo # "$foo" is not defined.

(my comments only reflect what appears to be happening, not what is happening).

Another point I want to add is the clarity of this:

set foo foo

Yeah, I could always do set foo "foo", but isn't set $foo foo more consistent?

From what I know, "foo" can be a variable or a string, depending on the situation, as seen in my last example (set foo foo = set var string), but I don't get this syntax (maybe because I'm used to Python...)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think the original Tcl only had the set command, so the only way to fetch the contents of a variable "foo" was calling set foo. But as Tcl progressed into the domain of general-purpose scripting languages (recall that Tcl was envisioned as being an embeddable language where you use a thin layer of Tcl over compilcated components written in C, so one wasn't expected to use lots of variables), it was deemed that that $varname syntactic sugar is useful and so it was added.

In other words, Tcl does not use "$" in the same way as Perl does, in which the "$" means "interpret whatever follows as a scalar", neither does "$" in Tcl denote a variable. Instead it merely a syntactic sugar for "give me the value of a variable whose name is given by the immediately following word".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...