Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

tcl

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"
   }
}
like image 598
SuperTetelman Avatar asked Mar 05 '13 01:03

SuperTetelman


People also ask

What is switch command in Tcl?

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.


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"
   }
}
like image 97
Ergwun Avatar answered Sep 29 '22 14:09

Ergwun


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"

like image 26
Fedor Avatar answered Sep 29 '22 14:09

Fedor


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

like image 23
potrzebie Avatar answered Sep 29 '22 14:09

potrzebie