【问题标题】:Expect TCL counter within variable期望变量内的 TCL 计数器
【发布时间】:2015-11-16 20:42:20
【问题描述】:

举个例子,假设我定义了几个变量,然后我用计数器变量调用这些变量。 $interface$counter 的正确语法是什么?

set interface0 $env(interface0)
set interface1 $env(interface1)
set interface2 $env(interface2)

for {set i 0} {$i < $3} {incr i 1} {
puts $interface$i
}

【问题讨论】:

标签: tcl expect


【解决方案1】:
set interface0 A
set interface1 B
set interface2 C

for {set i 0} {$i < 3} {incr i 1} {
    puts [set interface$i]
}

动态变量名称始终是可以使用的 PITA。你需要让Tcl经过2轮替换:首先构造变量名,其次提取值。

更容易使用数组。可以直接取值

array set interface {}
set interface(0) A
set interface(1) B
set interface(2) C

for {set i 0} {$i < 3} {incr i 1} {
    puts $interface($i)
}

或者使用字典

set interface [dict create]
dict set interface 0 A
dict set interface 1 B
dict set interface 2 C

for {set i 0} {$i < 3} {incr i 1} {
    puts [dict get $interface $i]
}

但是,在这种情况下,您只有单调递增的整数值:您需要一个列表:

set interfaces [list $env(interface0) $env(interface1) $env(interface2)]

for {set i 0} {$i < $3} {incr i 1} {
    puts [lindex $interfaces $i]
}

【讨论】:

    【解决方案2】:

    可以是:

    for {set i 0} {$i < 3} {incr i 1} {
    send "This is count [set interface$i]\n"
    }
    

    谢谢

    【讨论】:

      猜你喜欢
      • 2015-03-20
      • 2012-11-10
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多