检查过程是否返回列表或带有子列表的列表
我面临的问题是如何检查程序返回的列表是否由单个列表组成或者内部可能包含子列表。
#simple list
set a { 1 2 3 4}
# list consisting of sub list
set a { {1 2 3 4} {5 6 7 7} }
如上所述,有时变量 a
将有一个列表,有时 proc 将返回由子列表组成的列表。
更新部分
set a [mysqlsel $db "SELECT * FROM abc" -list]
我不知道天气查询会返回单个列表或由子列表组成的列表
I am facing problem how to check whether the list returned by the procedure consist of a single list or may have sub list inside.
#simple list
set a { 1 2 3 4}
# list consisting of sub list
set a { {1 2 3 4} {5 6 7 7} }
As above some times the variable a
will have a list and sometime proc will return list consisting of sub list.
Update part
set a [mysqlsel $db "SELECT * FROM abc" -list]
I do not know weather query will return a single list or list consisting of sublist
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您确实应该重新考虑您的方法:由于 Tcl 是无类型的,因此您无法真正判断 {{1 2 3 4} {5 6 7 8}} 是两个列表的列表还是两个字符串的列表或文字字符串 < code>{1 2 3 4} {5 6 7 8},因为所有这些命题是否正确取决于您如何让 Tcl 解释该值。
另一件事是,即使您要在每个顶级元素上尝试诸如
catch {lindex $element 0}
或string is list $element
之类的操作来查看是否它可以被解释为一个列表,只有真正不能被解析为列表的字符串才会被视为非列表,例如aaa { bbb
。字符串foo
也是一个真列表(长度为 1,包含“foo”作为其唯一元素)。您可以考虑使用的一种方法是将返回值包装在另一个值中,该值附加了某种“标签”——这种技巧在其他一些无类型语言(如 LISP 和 Erlang)中经常使用。看起来像这样:
1 2 3 4
,请返回{flat {1 2 3 4}}
。{1 2 3 4} {5 6 7 8}
,则返回{nested {{1 2 3 4} {1 2 3 4 5}}}
。然后在客户端代码中打开“tag”元素并解封装有效负载:
You should really rethink your approach: since Tcl is typeless, you can't really tell if {{1 2 3 4} {5 6 7 8}} is a list of two lists or a list of two strings or a literal string
{1 2 3 4} {5 6 7 8}
, because all these propositions are true depending on how you make Tcl interpret this value.Another thing, is that even if you were to try something like
catch {lindex $element 0}
orstring is list $element
on each top-level element to see if it can be interpreted as a list, that would qualify as being non-lists only strings that really can't be parsed as lists, likeaaa { bbb
. And stringfoo
is also a proper list (of length 1, containing "foo" as its sole element).One approach you can consider using is wrapping the returned value in another value which has some sort of "tag" attached to it--the trick routinely used in some other typeless languages like LISP and Erlang. That would look like this:
1 2 3 4
, return{flat {1 2 3 4}}
instead.{1 2 3 4} {5 6 7 8}
, return{nested {{1 2 3 4} {1 2 3 4 5}}}
.Then in the client code do switch on the "tag" element and decapsulate the payload: