I want to have a large list of options in my script. The user is going to give input that will only match one of those options. I want to be able to have multiple different options run the same commands but I cannot seem to get ORs working. Below is what I thought it should look like, any ideas on how to make the a or b line work?
switch -glob -- $opt {
"a" || "b" {
puts "you selected a or b, probably not both"
}
default {
puts "Your choice did not match anything"
}
}
The switch command matches its string argument against each of the pattern arguments in order. As soon as it finds a pattern that matches string it evaluates the following body argument by passing it recursively to the Tcl interpreter and returns the result of that evaluation.
You can use -
as the body for a case, to fall-through to the next body, as explained in the Tcl Manual:
If a body is specified as “-” it means that the body for the next pattern should also be used as the body for this pattern (if the next pattern also has a body of “-” then the body after that is used, and so on). This feature makes it possible to share a single body among several patterns.
Also, if your options are a big string of concatentated characters, you are going to have to bookend your option patterns with wildcards, or your cases will only match when opt
only contains a single option:
switch -glob -- $opt {
"*a*" -
"*b*" {
puts "you selected a or b, probably not both"
}
default {
puts "Your choice did not match anything"
}
}
Also working this:
switch -regexp -- $opt {
a|b {
puts "you selected a or b, probably not both"
}
default {
puts "Your choice did not match anything"
}
}
Attention: no spaces between "a|b"
There's two ways. From the switch documentation examples: "Using glob matching and the fall-through body is an alternative to writing regular expressions with alternations..."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With