如何正确地将值分配给TCL中的列表?

时间:2012-03-29 13:21:31

标签: list foreach tcl

我对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无法读取。

1 个答案:

答案 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
        }
    }
}

或者,创建一个结合了employeeListemployeeType

的数据结构
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
            }
        }
    }
}