将字符串转换为tcl中的映射或列表

时间:2016-03-27 13:47:01

标签: list tcl

我有一个命令输出,因为这是一个例子

card-1-1-1   4   -Number  1  -type  Eth  -config        -GEPorts 4
card-1-3-1   3   -Number  2  -type  Eth  -config   Yes  -GEPorts 3

我需要将其转换为像

这样的列表
card-1-1-1   4
-Number  1  
-type  Eth  
-config  if_empty_insert_null  
-GEPorts 4
card-1-3-1   3   
-Number  2  
-type  Eth  
-config   Yes  
-GEPorts 3

1 个答案:

答案 0 :(得分:1)

好吧,如果您没有选择有时缺少相关值的选项,那么这将是非常微不足道的。事实上,我们需要更加小心。主要的棘手问题是使用regexp -all -inline解析到Tcl列表并使用for循环在检测到缺少参数时迭代所有内容。

# Process each line
foreach row [split $inputData "\n"] {
    # If there's a comment syntax or blank lines are allowed, you handle them here

    # Safely convert to a Tcl list
    set words [regexp -all -inline {\S+} $row]

    # First two words are used "as is"
    set pairs [lrange $words 0 1]

    # Can't use foreach here; non-constant step size prevents it
    for {set i 2} {$i < [llength $words]} {incr i} {
        set paramName [lindex $words $i]
        set next [lindex $words [expr {$i + 1}]]

        # Set the default for if the option is value-less
        set parameter "if_empty_insert_null"

        # Look for a value; slightly complex as I'm allowing for negative numbers
        if {$next ne "" && ![regexp {^-[a-zA-Z]} $next]} {
            set parameter $next
            incr i
        }

        # Now we can update the list as we know the pair of values to add
        lappend pairs $paramName $parameter
    }

    # Now print everything out; we can use foreach for this as we're guaranteed to
    # have an even number of values
    foreach {a b} $pairs {
        # Do more complex formatting if you want
        puts "$a $b"
    }
}
相关问题