将字符串转换为 tcl 中的映射或列表
convert a string to a map or list in 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
好吧,如果不是因为您的某些选项有时 缺少关联值,这将是微不足道的。事实上,我们需要更加小心。主要的棘手位是使用 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"
}
}
我有一个命令输出,下面是一个例子
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
好吧,如果不是因为您的某些选项有时 缺少关联值,这将是微不足道的。事实上,我们需要更加小心。主要的棘手位是使用 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"
}
}