How do I use an or in a tcl switch statement?
Asked Answered
C

3

7

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"
   }
}
Criminology answered 5/3, 2013 at 1:28 Comment(0)
K
17

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"
   }
}
Kipton answered 5/3, 2013 at 3:9 Comment(0)
B
2

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"

Bogosian answered 9/9, 2016 at 8:37 Comment(0)
I
1

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

Incumbency answered 5/3, 2013 at 2:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.