如何在 TCL 列表中获取 "multi word"、"mono word" 和空字符串?我得到一个 "non uniform" 大括号格式化字符串的列表

How to get "multi word", "mono word" and empty strings all of them inside a TCL list? I get a list of "non uniform" curly braced formatted strings

我是TCL的新手。阅读一些手册,我尝试修改我在这里和那里找到的一些脚本,到目前为止,我一直很好地管理我的需求......直到今天。

我正面临一个(可能)愚蠢的问题(对于专业人士而言),但对我来说不是微不足道的,特别是因为我仍然没有完全掌握概念(字符串、数组等... )

我的情况是这样的:

我有一个第 3 方应用程序,当我请求它们时 returns 字符串。这些字符串可以是多个单词(space ' ' 分隔)、一个单词或空字符串。 这些字符串是不可预测的,我无法从上述 3 种类型中知道任何询问的字符串的类型。

典型的执行示例如下:

list [format "%s" [lindex [some_function 0] 0] [format "%s" [lindex [some_function 1] 0] [format "%s" [lindex [some_function 2] 0] [format "%s" [lindex [some_function 3] 0]

可能不是最优的,但它 returns 这个:(多词,空,1 词,多词)

{Hi you} {} finishing {this is string 3}

这种格式似乎还可以,但它不规则,足以破坏我的 swift 解析器(在处理它时,将 4 个字符串分成 4 个成员的数组)

理想情况下,我希望在所有返回的字符串中都有大括号,无论是多词、单词还是空字符串。 不知何故,"TCL is irregular" 在处理单字字符串时...我怎样才能实现这种理想情况?

{Hi you} {} {finishing} {this is string 3}

大括号在那里是因为它是典型的 separator/operator TCL returns,但我也可以接受这样的东西:

"Hi you" "" "finishing" "this is string 3"

我应该如何重写我的 4 个示例字符串的原始命令?

提前问候和感谢。

您不应使用其他工具解析 tcl 列表。它很容易出错,因为 tcl 列表可以采用各种格式,尤其是转义。

如果您需要通过其他工具处理tcl 列表,那么您应该将其转换为某种格式,以便该工具可以读取。例如,json 或类似的内容。

但是,您可以将列表转换为您描述的简单格式。例如:

set mylist {{Hi you} {} finishing {this is string 3}}
set out "{[join $mylist "} {"]}"
puts $out

这会给你:

{Hi you} {} {finishing} {this is string 3}

但是你会与值中的 {} 符号发生冲突。

或者:

set mylist {{Hi you} {} finishing {this is string 3}}
set out "\"[join $mylist "\" \""]\""
puts $out

这会给你:

"Hi you" "" "finishing" "this is string 3"

现在,您将与值中的 " 符号发生冲突。

因此,这些解决方案并不完美。

proc quote_words {mylist} {
    join [lmap elem $mylist {format {"%s"} [string map {{"} {\"}} $elem]}]
}

然后

quote_words [list foo "" bar {a string "with quotes"}]

给你

"foo" "" "bar" "a string \"with quotes\""