Tcl在使用`$`符号时添加花括号 [英] Tcl adds curly braces when using `$` sign

查看:1081
本文介绍了Tcl在使用`$`符号时添加花括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

set B {pc_0::!mx_0 pi::$mx_0}
puts $B

set A ""
foreach x $B {
    lappend A $x
}

puts $A

该程序的输出为

pc_0::!mx_0 pi::$mx_0
pc_0::!mx_0 {pi::$mx_0}

奇怪的是,tcl在第二个输出中添加了花括号.我猜是因为它使用了$符号.但是我确实需要使用它,并且我不想插入大括号.该如何解释以及如何避免使用括号?

It is strange that tcl adds curly braces in second output. I guess it is because it uses $ symbol. But I really need to use it and I don't want the braces to be inserted. How this can be explained and how to avoid the braces?

推荐答案

通常,不要将列表视为字符串.假设它们没有字符串表示形式. (字符串表示形式仅对序列化,调试有用,而对用户无效).

As a general rule, don't treat lists as strings. Pretend that they don't have a string representation. (The string representation is only useful for serialization, debugging, but not for the user).

要将文本(尤其是用户输入)转换为列表,请使用 split .
要将其转换回,请使用 join .

To convert text (especially user-input) to a list use split.
To convert it back, use join.

您想要的秀:

puts [join $A]

背景:

一个列表具有转义Tcl使用的所有元字符的副作用.当您 eval 此列表时,将不会进行进一步的替换.对于生成稍后将执行的回调/代码,这是非常重要的属性:

Background:

A list have the sideeffect of escaping all meta-characters used by Tcl so no further subsitution takes place when you eval this list. This is a very important property for generating Callbacks/code that will be later executed:

set userinput [gets stdin]
set code [list puts $userinput]
eval $code

无论用户在此处输入什么,输出始终与用户输入的相同,没有任何替代.

No matter what the user enters here, the output is always the same as the user entered, without any substitution.

如果不能逃避$,则评估将尝试替换$mx_0,这很可能会失败.

If the $ would not be escaped, then an evaluation would try to substitute $mx_0, which will most likly fail.

这篇关于Tcl在使用`$`符号时添加花括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆