1 minute read

Like other programming languages, TCL also provides support to switch case. It is used to test multiple conditions. In TCL switch, we don’t need to write break statement like other languages. To achieve switch case functionality we can also use if else statements .

Let us see syntax of switch case :

switch option switch_expression switch_expression_1  { body_1 } switch_expression_2 { body_2 } switch_expression_3 { body_3 } default { default_body }

switch_expression can be a number, alphabet or string . If switch_expression match with any subsequent switch_expressions then body corresponding to that expression will be executed. default block will be executed if switch_expression doesn’t match with any subsequent expressions.

options can be :

-exact : Use exact matching (default)

-glob : When matching string to the patterns like *, ? (i.e. the same as implemented by the string match )

-regexp : When matching string to the patterns, use regular expression.

Let us see some examples : 1. switch case with numbers :


#!/usr/bin/tclsh 

set number 5;

switch $number

1 { puts "One" }

2 { puts "Two" }

3 { puts "Three" }

default { puts "Invalid Number." } } 

Output : $tclsh main.tcl Invalid Number.

 

2. Switch case with string :

#!/usr/bin/tclsh

set country_code "US";

switch $country_code { 
US { puts "United States of America" }
IN { puts "India" }
UK { puts "United Kingdom" }
default { puts "Invalid Country Code" }
} 

 Output: $tclsh main.tcl United States of America

 

3. Switch using option:

#!/usr/bin/tclsh

set var _string computer;

switch -glob $var _string
{ 
  com\*er { puts "Matched with com\*er" } 
  default { puts "Invalid !" } } 

Output: $tclsh main.tcl Matched with com*er

Categories:

Updated: