2

我在从字符串中取出某些部分时遇到了麻烦。

这是我的代码:

  set top [layout peek $::openedFiles($key) -topcell]
  set dim [layout peek $::openedFiles($key) -bbox $top] 
 # yields output "{name{x1 y1 x2 y2}}"

  set coord [split $dim " "]
  set x1 [lindex $coord 0]
  set x2 [lindex $coord 2]
  set y1 [lindex $coord 1]
  set y2 [lindex $coord 3]

当我调用 commandset dim [layout peek $::openedFiles($key) -bbox $top]时,我会从加载的文件中取回尺寸。这些维度是坐标。输出总是这样:"{name {x1 y1 x2 y2}}".

例如 :{test {0 0 100 100}}

我想从字符串中取出四个坐标,以便将它们放在一个数组中。我尝试根据空格拆分字符串,但没有成功。(继续得到这个error: can't read "coord\{clock \{0 0 99960 99960\}\}": no such variable

有人有想法吗?

4

2 回答 2

4

如果您使用的是足够新的 Tcl,或者带有适当软件包的旧 Tcl - 抱歉,我不记得细节了;如果你想让我去把它们挖出来,请告诉我——然后你就可以了

set dim [layout peek $::openedFiles($key) -bbox $top]
lassign $dim firstBit coords
lassign $coords x1 x2 y1 y2

使用较旧的版本,并且没有扩展,

set dim [layout peek $::openedFiles($key) -bbox $top]
set coords [lindex $dim 1]
set x1 [lindex $coords 0]

# etc.

编辑

事实证明,[layout peek...]工作方式略有不同,所以最终的工作代码是

set dim [layout peek $::openedFiles($key) -bbok $top]
set temp [lindex $dim 0]
set coords [lindex $temp 1]
set x1 [lindex $coords 0]
set x2 [lindex $coords 1]
set y1 [lindex $coords 2]
set y2 [lindex $coords 3]

OP 使用的是 Tcl8.4,没有 TclX。

可能有改进变量名的空间,但是......

于 2013-05-28T08:31:26.630 回答
0

您可以使用正则表达式从该字符串中提取所有数字,然后照常分配:

# Assume dim = "{test {0 0 100 100}}"
set coord [regexp -inline -all {\d+} $dim]; # coord is now a list: "0 0 100 100"
set x1 [lindex $coord 0]
# set x2, y1, y2, ...
于 2013-05-29T14:25:02.010 回答