英文:
Unexpected switch command behavior in TCL
问题
我正在尝试使用TCL运行下面的switch块。根据switch语句的工作原理,我期望输出为10。但实际输出为Default。我不知道背后的解释以及如何修复。
set a 10
set data 10
switch $data {
$a {
puts "10"
}
default {
puts "Default"
}
}
输出是:
Default
英文:
I am trying to run the below switch block using TCL. I am expecting the output to be 10 based on how the switch statement works. But the output comes out to be Default. I am not what's the explanation behind that and how I can fix it.
set a 10
set data 10
switch $data {
$a {
puts "10"
}
default {
puts "Default"
}
}
The output is:
> Default
答案1
得分: 1
在Tcl中,用大括号{}括起来的字符串是字面量。字符串中的变量不会被替换。这个规则同样适用于传递给if/for/switch命令的{}块的语句。
所以在你的情况下,$a是一个字面字符串,而不是10,对于switch命令来说。
你可以重写你的switch块如下,这样在传递给switch命令之前,$a会被替换为10。
switch $data [list \
$a {
puts "10"
} \
default {
puts "Default"
} \
]
英文:
In tcl, the string enclosed in {} is literal. The variables in the string is not substituted. The same rule applies to the statements of the {} blocks passed to if/for/switch commands.
So in your case, $a is a literal string, not 10, for the switch command.
You may re-write your switch block as following thus $a is substituted to 10 before passed to switch command.
switch $data [list \
$a {
puts "10"
} \
default {
puts "Default"
} \
]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论