How Do I Use an or in a Tcl Switch Statement?

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"
   }
}

3 Answers

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"
   }
}
0

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..."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest