TCL中开关命令行为的意外更改

huangapple go评论57阅读模式
英文:

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"
    } \
]

huangapple
  • 本文由 发表于 2023年2月16日 07:57:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75466535.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定