tcl 数组问题 - 带引号的键

发布于 2024-10-14 13:31:29 字数 290 浏览 0 评论 0原文

这让我感到惊讶

>set foo("bar") 12
12
>parray foo
foo("bar") = 12
>set foo(bar) 12
12
>parray foo
foo("bar") = 12
foo(bar)   = 12

,似乎字面量 foo 与“foo”不同。然而

>string length foo
3
>string length "foo"
3

我还是不明白什么

this surprised me

>set foo("bar") 12
12
>parray foo
foo("bar") = 12
>set foo(bar) 12
12
>parray foo
foo("bar") = 12
foo(bar)   = 12

it seems that the literal foo is not the same as "foo". And yet

>string length foo
3
>string length "foo"
3

what am I failing to understand

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

蒗幽 2024-10-21 13:31:29

" 字符仅对 Tcl 的解析器来说是特殊的,位于单词的开头(或者当然是由 " 开头的单词的结尾)。事实上,如果您在其中添加空格,则会出现错误:

% set foo("b a r") 2
wrong # args: should be "set varName ?newValue?"

在执行 string length 调用的情况下," 在单词的开头,因此它很特殊。如果我们放置一个额外的前导垃圾字符,我们会发现 " 的特殊性消失了:

% string length x"bar"
6

如果您正在使用数组做一些复杂的事情 。索引,我认为将元素的名称放入变量本身通常更容易,因为这样就更清楚发生了什么(并且通常也更容易调试):

set idx "bar"
set foo($idx) 12

The " character is only special to Tcl's parser at the start of a word (or the end of a word that was started by ", of course). In fact, if you'd put spaces in you would have got an error:

% set foo("b a r") 2
wrong # args: should be "set varName ?newValue?"

In the case where you're doing the string length calls, the " is at the start of a word so it is special. If we put an extra leading junk character, we see that the specialness of " goes away:

% string length x"bar"
6

If you're doing something complicated with array indices, I think it's usually easier to put the name of the element in a variable itself, since then it's clearer what's going on (and usually easier to debug too):

set idx "bar"
set foo($idx) 12
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文