【问题标题】:Set char variable "-" in tcl在 tcl 中设置 char 变量“-”
【发布时间】:2018-04-08 07:18:39
【问题描述】:

我正在使用 tcl 模拟用户对 shell 的输入

if {$toOperand == 0} {
 set operand +
} elseif {$toOperand == 1} {
 set operand -
} elseif {$toOperand == 2} {
 set operand *
} elseif {$toOperand == 3} {
set operand :
} elseif {$toOperand == 4} {
 set operand @
} else {set operand #}

所有字符都可以正常工作,除了“-”。这是错误:

": must be -i, -h, -s, -null, -0, -raw, -break, or --
   while executing
"send "$operand\r""

感谢任何帮助

【问题讨论】:

  • 你可能想要考虑将你相当冗长的 if-elseif-else 探戈变成一个操作数列表,toOperand 作为列表索引:set opnds {+ - * : @ #}; set operand [lindex $opnds $toOperand]; ...这假设 toOperand 默认以某种方式到end,代表您的else 分支。
  • @mrcalvin 嘿,谢谢你的建议
  • switch 命令将是另一种选择。

标签: shell unix tcl sh expect


【解决方案1】:

答案:

在操作数之前插入一个-- 伪选项以宣布后面没有更多选项。


关于选择字符的注意事项:

您的if 构造没有任何问题,如果您对它感到满意,您应该使用它。不过,还有一些替代方案可能更紧凑、更易于阅读。

由于您的 toOperand 变量包含看起来像列表索引的值,您可以这样做:

set operands {+ - * : @}
if {0 <= $toOperand && $toOperand < [llength $operands]} {
    set operand [lindex $operands $toOperand]
} else {
    set operand #
}

这也有效(允许传递不匹配任何值的索引,它只会导致空字符串):

set operands {+ - * : @}
set operand [lindex $operands $toOperand]
if {$operand eq {}} {
    set operand #
}

如果toOperand 值不是直接索引(不连续或非法的索引值),上述方法将不起作用。 dict 也可以做类似的事情(因为dict get不允许允许不匹配的键,我们需要先检查键是否匹配):

set operandValues {0 + 1 - 2 * 3 : 4 @}
if {[dict exists operandValues $toOperand]} {
    set operand [dict get operandValues $toOperand]
} else {
    set operand #
}

在这两种情况下,您基本上都可以随意更改操作数集,而无需更改使用它的代码。

另一种可能是使用switch 命令:

switch $toOperand {
    0 {
        set operand +
    }
    1 {
        set operand -
    }
    2 {
        set operand *
    }
    3 {
        set operand :
    }
    4 {
        set operand @
    }
    default {
        set operand #
    }
}

文档: && (operator), < (operator), <= (operator), dict, eq (operator), if, lindex, llength, set, switch

【讨论】:

  • 真正的问题是send 接受选项并假设参数词是选项,如果它们以- 开头。在$operand\r 之前传递-- 会停止所有这些事情。
  • @DonalFellows:这就是答案,只是被关于语法的评论蒙上了一层阴影。希望现在更清楚了。
猜你喜欢
  • 2016-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-20
  • 2016-10-03
  • 1970-01-01
相关资源
最近更新 更多