我对tcl中的列表有疑问,将值分配给列表的正确方法是什么?
set employeeList ""
set TYPEID_3456 8
set TYPEID_9876 6
set TYPEID_6578 7
if {$employeeType=="1"} {
set employeeList "8"
} elseif {$employeeType=="2"} {
set employeeList "6 7"
} else {
prints "failed"
}
foreach employee $employeeList {
if {$employee==$TYPEID_3456} {
#do something
} elseif {$employee==$TYPEID_9876} {
#do something
} elseif {$employee==$TYPEID_6578} {
#do something
}
}
这是正确的方法吗?因为它告诉我TYPEID_3456无法读取。
答案 0 :(得分:2)
您所写的内容是正确的:字符串值将被解释为foreach
命令中的列表。
但是我会这样写它以更清楚你的意图,并使用switch
命令更简洁:
set employeeList [list]
set TYPEID_3456 8
set TYPEID_9876 6
set TYPEID_6578 7
switch -exact -- $employeeType {
1 {lappend employeeList 8}
2 {lappend employeeList 6 7}
default {puts "failed"}
}
foreach employee $employeeList {
switch -exact -- $employee {
$TYPEID_3456 {
#do something
}
$TYPEID_9876 {
#do something
}
$TYPEID_6578 {
#do something
}
}
}
或者,创建一个结合了employeeList
和employeeType
:
array set employeeList {
1 {8}
2 {6 7}
}
set TYPEID_3456 8
set TYPEID_9876 6
set TYPEID_6578 7
if { ! [info exists employeeList($employeeType)]} {
puts "no employee list for employee type '$employeeType'"
} else {
foreach employee $employeeList($employeeType) {
switch -exact -- $employee {
$TYPEID_3456 {
#do something
}
$TYPEID_9876 {
#do something
}
$TYPEID_6578 {
#do something
}
}
}
}