- Tcl - Home
- Tcl - Overview
- Tcl - Environment Setup
- Tcl - Special Variables
- Tcl - Basic Syntax
- Tcl - Commands
- Tcl - Data Types
- Tcl - Variables
- Tcl - Operators
- Tcl - Decisions
- Tcl - Loops
- Tcl - Arrays
- Tcl - Strings
- Tcl - Lists
- Tcl - Dictionary
- Tcl - Procedures
- Tcl - Packages
- Tcl - Namespaces
- Tcl - File I/O
- Tcl - Error Handling
- Tcl - Built-in Functions
- Tcl - Regular Expressions
- Tk - Overview
- Tk - Environment
- Tk - Special Variables
- Tk - Widgets Overview
- Tk - Basic Widgets
- Tk - Layout Widgets
- Tk - Selection Widgets
- Tk - Canvas Widgets
- Tk - Mega Widgets
- Tk - Fonts
- Tk - Images
- Tk - Events
- Tk - Windows Manager
- Tk - Geometry Manager
- Tcl/Tk Useful Resources
- Tcl/Tk - Quick Guide
- Tcl/Tk - Useful Resources
- Tcl/Tk - Discussion
Tcl - Switch Statement
A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.
Syntax
The syntax for unquoted switch statement in Tcl language is as follows −
switch switchingString matchString1 {body1} matchString2 {body2} ... matchStringn {bodyn}
The syntax for unquoted switch statement in Tcl language is as follows −
switch switchingString {
matchString1 {
body1
}
matchString2 {
body2
}
...
matchStringn {
bodyn
}
}
The following rules apply to a switch statement −
The switchingString is used in a switch statement; used between the different blocks by comparing to the matchString.
You can have any number of matchString blocks within a switch.
A switch statement can have an optional default block, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true.
Flow Diagram
Example : Unquoted version
#!/usr/bin/tclsh
set grade C;
switch $grade A { puts "Well done!" } B { puts "Excellent!" } C { puts "You passed!" } F { puts "Better try again" } default { puts "Invalid grade" }
puts "Your grade is $grade"
When the above code is compiled and executed, it produces the following result −
You passed! Your grade is C
Example : Quoted version
#!/usr/bin/tclsh
set grade B;
switch $grade {
A {
puts "Well done!"
}
B {
puts "Excellent!"
}
C {
puts "You passed!"
}
F {
puts "Better try again"
}
default {
puts "Invalid grade"
}
}
puts "Your grade is $grade"
When the above code is compiled and executed, it produces the following result −
Excellent! Your grade is B