在tcl中拆分列表后出现流浪字符 [英] stray characters coming after splitting the list in tcl

查看:61
本文介绍了在tcl中拆分列表后出现流浪字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的列表中经常会出现类似"{\\ {"之类的字符,这是简单列表的结果,该简单列表是按空格连接或拆分的.

More often than not I get characters like "{\\ {" in my list which is the result of simple list which is concatenated or split by space .

只需查找这些字符背后的原因.

Just looking for the reason behind these characters.

我知道在等式中可以忽略后跟空格的特殊符号,但是 \\是什么意思?

I know that the backspace followed by a special sign can be ignored from the equation but what does \\ mean ?

推荐答案

很久以前,Tcl中的所有内容都在内部以字符串形式存储,包括列表.选择空白来分隔列表元素,以便以后可以将它们区分开来.

A long time ago, everything in Tcl was stored internally as a string, including lists. Whitespace was chosen to separate list elements so they could be distinguished from each other later...

set planets [list "mercury" "venus" "march"] ;# stored in planets as "mercury venus march"
puts [lindex $planets 2] ;# lindex treats it's first (string) argument as a list, and splits on whitespace to find the third element

...但是为了使这些字符存储在实际的列表元素中,需要某种转义/引用空白字符的方法. {}用于此...

...but then some way to escape/quote whitespace characters was needed to be able to store these in the actual list elements. { and } were used for this...

set programs [list "hello world" "primes"] ;# stored in programs as "{hello world} primes"

...现在您需要能够转义{}等.

...and now you need to be able to escape { and }, etc.

在现代Tcl版本中,列表在内部更有效地存储,但是从脚本编写者的角度来看,出于向后兼容性和其他原因,仍然以这种方式存储列表.因此,当您将列表用作字符串时,将获得列表的字符串表示形式,并带有空格,大括号和反斜杠.

In modern Tcl versions, lists are stored more efficiently internally, but from the script writers point of view it's still stored that way for backwards compability and maybe for other reasons. So when you use a list as a string, you get this string representation of the list, with spaces, braces and backslashes.

这个问题的简单解决方案是永远不要将列表视为字符串,即不要在命令需要字符串的情况下将列表作为参数发送.这样一来,除非您将它们实际放在一个元素中,否则您将看不到任何特殊的转义序列.

The simple solution to your question is to never treat a list as a string, i.e. don't send a list as an argument where the command expects a string. Then you'll never see any special escape sequences unless you actually put them in an element.

puts $mylist ;# bad unless used for debugging
puts [join $mylist] ;# good

也不要将字符串也视为列表:

And don't treat strings as lists either:

set mystring "word1 {hello word3"
puts [lindex $mystring 1] ;# will throw an error
puts [lindex [split $mystring] 1] ;# good

这篇关于在tcl中拆分列表后出现流浪字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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