SFNYC
May 15, 2009, 1:15pm
1
I am just learning Tcl and there are few things about it that is perplexing me. I have a question about the switch statement.
Why are these two switch statements giving me different results?
$ cat test_switch.tcl
#!/usr/bin/tcl
set foo "abc"
switch abc a - b {puts "No. 1"} $foo {puts "No.2"} default {puts "Default"}
switch abc {
a - b {puts "No.1"}
$foo {puts "No.2"}
default {puts "Default"}
}
exit 0
$ ./test_switch.tcl
No.2
Default
The "$foo" inside the switch was not replaced and therefore it fall through to the default branch. However, if you set foo to be $foo, it works.
switch {$foo} {
a - b { puts 1 }
$foo { puts 2 }
default { puts 3 }
}
I think you got the thing wrong
% switch
wrong # args: should be "switch ?switches? string pattern body ... ?default body
?"
You should treat the 2nd argument as the input string and match the pattern. In the below example, I use glob to do matching. You can also use regular expression (-regexp) if you want
switch -glob -- $input {
{to be*} { puts 1 }
{*Not to be} { puts 2 }
{*or*} { puts 3 }
default { puts 4 }
}
BTW, you need to understanding the difference between double quotes ("") and curly braces in Tcl