Tcl switch tips

This page is part of the Tcl/Tk page of the Airplug documentation.
Back to the Tcl/Tk page / Back to Airplug documentation page.

The following tcl shell script named for instance switch.tcl will not give the expected result when using ./switch.tcl toto while this will be ok with ''./switch.tcl tutu.

#!/usr/bin/tclsh
 
set stored "toto"
set input  $argv
 
switch -- $input {
	$stored {
		puts stdout "The argument is equal to variable stored (=$stored)."
	} \
	"tutu" {
		puts stdout "The argument is equal to string \"tutu\"."
	} \
	default {
		puts stdout "default case, the argument is not equal to variable stored nor to string \"tutu\"."
	}
}
ducourth@mouette:~/SRC/TCL$ ./switch.tcl tutu
The argument is equal to string "tutu".
ducourth@mouette:~/SRC/TCL$ ./switch.tcl toto
default case, the argument is not equal to variable stored nor to string "tutu".

This is because the global { } just after the switch prevent any variable replacement and the input will not be compared to “toto” but to “$stored”. Instead, the switch statement should be written as follows:

#!/usr/bin/tclsh
 
set stored "toto"
set input  $argv
 
switch -- $input \
	$stored {
		puts stdout "The argument is equal to variable stored (=$stored)."
	} \
	"tutu" {
		puts stdout "The argument is equal to string \"tutu\"."
	} \
	default {
		puts stdout "default case, the argument is not equal to variable stored nor to string \"tutu\"."
	}
$ ./switch.tcl tutu
The argument is equal to string "tutu".
$ ./switch.tcl toto
The argument is equal to variable stored (=toto).
$ 

<br>


This page is part of the Tcl/Tk page of the Airplug documentation.
Back to the Tcl/Tk page / Back to Airplug documentation page.

 
Back to top
en/doc/pub/tcltk/tips/switch.txt · Last modified: 2017/04/04 19:45 (external edit)
 
 
Driven by DokuWiki