Tcl Tutorial Lesson 8

Textual Comparison - switch

The switch command allows you to choose one of several options in your code. It is similar to switch in C, except that it is more flexible, because you can switch on strings, instead of just integers. The string will be compared to a set of patterns, and when a pattern matches the string, the code associated with that pattern will be evaluated.

It's a good idea to use the switch command when you want to match a variable against several possible values, and don't want to do a long series of if... elseif ... elseif statements.

The syntax of the command is:

   switch ?options? string {
       pattern1 {
           body1
       }
       ?pattern2 {
           body2
       }?
       ...
       ?patternN {
           bodyN
       }?
   }

string is the string that you wish to test, and pattern1, pattern2, etc are the patterns that the string will be compared to. If string matches a pattern, then the code within the body associated with that pattern will be executed. The return value of the body will be returned as the return value of the switch statement. Only one pattern will be matched.

If the last pattern argument is the string default, that pattern will match any string. This guarantees that some set of code will be executed no matter what the contents of string are.

If there is no default argument, and none of the patterns match string, then the switch command will return an empty string.

The options can be used to change the interpretation of the patterns. By default "glob" style pattern matching is used, where an asterisk (*) matches any number of characters, that is, a pattern "lesson*" matches "lesson", "lessons", "lession 2" etc. Other options are: -exact, causing the patterns to be literal strings and -regexp, in which case the patterns follow the rules of regular expressions (see Regular Expressions 101).


Example

set x "ONE"
set y 1
set z ONE

# Note that patterns are not subject to substitutions if
# contained in braces

switch $x {
    "$z" {
        set y1 [expr {$y+1}]
        puts "MATCH \$z. $y + $z is $y1"
    }
    ONE {
        set y1 [expr {$y+1}]
        puts "MATCH ONE. $y + one is $y1"
    }
    TWO {
        set y1 [expr {$y+2}]
        puts "MATCH TWO. $y + two is $y1"
    }
    THREE {
        set y1 [expr {$y+3}]
        puts "MATCH THREE. $y + three is $y1"
    }
    default {
        puts "$x is NOT A MATCH"
    }
}

  Resulting output
MATCH ONE. 1 + one is 2