The switch statement allows you to compare a string to various patterns. If the string matches a pattern then the body of that pattern is executed, similar to conditional statements. Switch statements are best used when the string being compared can only take on a limited number of specific values rather than a range. For instance, if the user could select between four different tests to exercise HDL code a switch statement might be used.
The syntax for switch statements is
switch string pattern1 body1 … stringN bodyN default body
However, just like we could reformat the conditional statements for better readability we can do the same with the switch statements as shown.
switch string {
pattern1 {
body1
}
pattern2 {
body2
}
…
patternN {
bodyN
}
default {
body
}
}
However, using the above method prevents substitution on the pattern (meaning you can’t use a variable as the pattern) though substitution will still work inside the body. If substitution on the pattern is required then the following syntax should be used.
switch string pattern1 {
body1
} pattern2 {
body2
} … patternN {
bodyN
} default {
body
}
The default pattern and body are optional and the default body is only executed if the string fails to match any patterns. If the default case is omitted and the string fails to match a pattern then none of the bodies are executed and the program moves on.
set x Test4
set option Test4
switch $x {
Test1 {
#substitution still occurs within the body
puts “Run Test 1. \$x = $x”
}
Test2 {
puts “Run Test 2. \$x = $x”
}
Test3 {
puts “Run Test 3. \$x = $x”
}
$option {
puts “Run Test 4. \$x = $x”
#because of the brace after switch $x substitution does not occur
# on the patterns.
#Test1 is compared to the literal string $option.
}
default {
puts “Invalid selection”
}
}
set x Test2
set option Test2
switch $x Test1 {
puts “Run Test 1”
} $option {
puts “Run Test 2”
#brace directly following $x has been removed.
#substitution works correctly
} Test3 {
puts “Run Test 3”
} Test4 {
puts “Run Test 4”
} default {
puts “Invalid selection”
}
Copy and paste the above examples into the widget below and play around. See what happens when you change x to something different or add new cases. Have fun and learn!