Decision in TCL

Decision

There will be many points where we need a decision in tcl in between choices while writing a script, there IF statement will help us. IF comes with ELSE also if there are more than one statement. Below diagram states the IF statement.

tcl-decision

 

First let’s understand the format to write the IF statement.

Formats

1. Only IF Statement

If {condition} {
##Execute statement
}

 

only-if-tcl-decision

EG. –

set a 10;
if {$a > 5} {
puts “Since condition is true hence statement will be executed”
}

Result:- Since condition is true hence statement will be executed

set a 10;
if {$a < 5} {
puts “Since condition is true hence statement will be executed”
}

Result: <Nothing will be printed>

2. IF ELSE Statement

If {condition} {
##Execute statement which is true
} else {
##Execute statement which is false
}

 

if-else-statement-tcl-decision

EG.

set a 10;
if {$a > 5} {
puts “Since condition is true hence statement will be executed”
} else {
puts “Since condition is false hence statement will be executed”
}

Result: Since condition is true hence statement will be executed

set a 10;
if {$a < 5} {
puts “Since condition is true hence statement will be executed”
} else {
puts “Since condition is false hence statement will be executed”
}

Result: Since condition is false hence statement will be executed

set a 10;
if {$a > 5} {
puts “Since condition $a < 5 is true hence statement will be executed”
} elseif {$a > 8} {
puts “Since condition $a < 8 is true hence statement will be executed”
} else {
puts “Since condition is false hence statement will be executed”
}

Result: Since condition 10 > 5 is true hence statement will be executed
Since condition 10 > 8 is true hence statement will be executed.

3. NESTED IF Statement

Nested IF means there are if statements inside a statement. (IF inside IF)

if {condition_1} {
puts “since the condition_1 is true hence this statement will be executed”
if {condition_2} {
puts “If condition_2 is true hence this statement will be executed”
}
}

 

nested-if-tcl-decision

EG.

Set a 10;
If {$a > 5} {
Puts “Since condition 1 is true hence the statement will be executed”
If {$a > 8} {
Puts “Since condition 2 is true hence the statement will be executed”
}
}

Result: Since condition 1 is true hence the statement will be executed
Since condition 2 is true hence the statement will be executed

4. Switch Statement

The way we control the electric switches in our house with the condition of different electric equipment’s, similarly we control different statement in TCL as well with conditions using SWITCH statement. Let’s understand more with format and flow diagram.

Format:
switch <condition> {
match_condition1 {
Body
}
match_condition2 {
Body
}
}

Flow Diagram:

switch-statement-tcl-decision

 

EG.

set speed 60;
switch $speed {
80 {
puts “speed is 80”;
}
60 {
puts “speed is 60”;
}
default {
puts “Invalid Speed”
}
}

Result: Speed is 60

Admin
Admin

Leave a Reply