Conditionals In TCL
A system can be in a certain condition out of several conditions. To find that condition, we use an if command or a switch command. Firstly, we will discuss about the if command and secondly we will discuss about the switch command.
As we have read in expr command In TCL that there is a security risk involved when we use,"" to pass arguments to a command in place of {}. This is also true for if command and others.
The if Command
Here we are going to write a file named ifcmd.tcl and then we will run it as, tclsh ifcmd.tcl
set x 10;
if {$x < 11} {
puts "$x is less than 11.";
}
if {$x < 11 } {
puts "$x is less than 11.";
} elseif {$x > 11} {
puts "$x is greater than 11";
} else {
puts "x is 11";
}
In the first if command, it is being checked whether the value of x is less than 11 and found true then the value of {$x <11} will be 1 or found false then the value of {$x < 11} will be 0.When false we know that either $x is greater than 11 or equal to 11 but we are not sure which one is true. In that case, the second one is useful.
The if command tests each condition sequentially from the start until it finds a true condition or an else condition and then executes the associated body of statements and exits the if commands.
The else condition or the default condition in the switch command, which we are going to discuss next, is the last resort.
Last but not least, we can use only one if condition and only one else condition but as many elseif condition as we wish.
The switch Command
Here we are going to write a file named switchcmd.tcl and then we will run it as, tclsh switchcmd.tcl
set svr "xyz"
switch $svr {
"tomcat" {
puts "It's tomcat server.";
}
"nginx" {
puts "It's nginx server.";
}
"apache" {
puts "It's apache server.";
}
default {
puts "It's unknown server.";
}
}
if {$svr == "tomcat"} {
puts "It's tomcat server.";
} elseif {$svr == "nginx"} {
puts "It's nginx server.";
} elseif {$svr == "apache"} {
puts "It's apache server.";
} else {
puts "It's unknown server.";
}
In the case of "tomcat", "nginx" and "apache", the respective body of statements will be get executed. For all other strings default condition will be executed. We have written it using the if command also but notice that it is a bit bulky.
At last, TCL language syntax is not as flexible as C language syntax. We should be careful when inserting a newline(Enter key) because we might encounter an error. In the if command always try to start the next condition on the same line on which the previous condition ends.
Happy reading and thank you. Meet you soon.
Comments
Post a Comment