Why doesn't Tcl use a dollar sign before variable names when calling “set”?

前端 未结 4 1729
悲哀的现实
悲哀的现实 2020-12-04 01:52

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 conte

4条回答
  •  我在风中等你
    2020-12-04 02:07

    Well, I decided to comment upon the last bits of the original question, but the comment overgrown the limit, and so I'll post it as an answer even while it does not address the indicated question. I'll hope it will clarify some things which appear to be implied in the question though.

    A note about the consistency of set foo foo: you're approaching Tcl in a somewhat wrong way. Tcl is radically different from Perl or Python in that it has almost no syntax (really, like LISPs). "set foo foo" is not a syntax for setting a variable as it could be in another language, it's a call to a command currently available under the name "set" and passing it two arguments--"foo" and "foo"; it's whatever is registered under the "set" command name decides what is the name of a variable and what is the value to set it to. Likewise, looping commands are not syntax, they are commands. Really, it worth stopping here and think that

    for {set i 0} {$i < 10} {incr i} {
      puts $i
    }
    

    is not merely a whimsical language designer's idea to go with curly braces instead or "normal" parentheses like in C. Instead, here the Tcl parser parses out five words, takes the first one to be the name of a command, looks it up, and passes it the rest of the words; it's the implementation of for which interprets those {set i 0}, {$i < 0} etc and executes them appropriately. The syntax is there only to specify how there words are parsed out from the input stream of characters. And since everything is implemented using commands, your commands are able to behave no different from builtin ones; this allows you to create custom commands as powerful as for or switch (something akin to macros in LISPs). In another language this would be equal to the ability to extend sytnax in arbitrary ways.

    When this idea "clicks" , Tcl will no longer appear to be weird. And it's this property which makes Tcl so easily extensible (and embeddable): because the commands you provide from your C side behave absolutely the same as all builtin commands.

提交回复
热议问题