Search code examples
switch-statementtcltk-toolkit

Unexpected switch command behavior in TCL


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


Solution

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