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

前端 未结 4 1731
悲哀的现实
悲哀的现实 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-04 02:18

    The real answer, if any, could only be given by the original language designers (John Ousterhout) I guess. So the rest is open to speculation or (educated) guesses. There is some history on TCL available here, but upon a quick reading there is no direct answer there.

    Why doesn't Tcl set variables with the "$", but need a "$" to access a variable?

    My take would be that this way it is closer aligned to (UNIX) shell languages. TCL was conceived at Berkeley, arguably a strong UNIX (or BSD for that matter) environment.

    UNIX shells also don't use the $ sign (or equivalent for the respective shell) when declaring or assigning variables, but require it when referencing it:

    # bourn shell like shells (sh, bash, ksh, ...)
    foo=foo
    echo "The value of the variable foo is $foo."
    

    Even the unholy Windows CMD.EXE processor uses a comparable method (although I guess that was not what TCL designers had in mind ;-)

    REM DOS COMMAND.COM / Windows CMD.EXE
    set foo=foo
    echo The value of the variable is %foo%.
    

    Also, "string values" (although shells are notoriously weak typed) don't generally require quotes if there are now spaces in the string value.

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

    Well, it wasn't for the TCL designers/creators ;-)

    EDIT I almost forgot: You could actually do the following in TCL:

    set foo bar
    set $foo something
    puts $bar
    

    This will actually output "something". The second line actually sets the string "something" to the value of the variable "foo", thus setting a variable named "bar" and assigning it the value "something".

提交回复
热议问题