Logical Operations in Tcl
1. AND Operation
set A "1"
set B "0"
set c [expr "$A && $B"]
puts "This is the result for AND operation $c"
# Output: This is the result for AND operation 0
2. OR Operation
set set A "1"
set B "1"
set c [expr "$A || $B"]
puts "This is the result for OR operation $c"
# Output: This is the result for OR operation 1
3. NOT Operation
Example 1
set A "0"
set B "1"
set c [expr "!$B"]
puts "This is the result for NOT operation $c"
# Output: This is the result for NOT operation 0
Example 2
set A "0"
set B "1"
set c [expr "!$A"]
puts "This is the result for NOT operation $c"
# Output: This is the result for NOT operation 1
Bitwise Operations in Tcl
Bitwise operations work on the bit level of variables.
1. AND Operation
set A "218"
set B "235"
set c [expr "($A & $B)"]
puts "This is the result for AND operation $c"
# Output: This is the result for AND operation 202
Explanation:
- A in decimal: 218 → binary: 1010 1101
- B in decimal: 235 → binary: 1011 1110
- AND each bit: 1010 1100 → decimal: 202
2. OR Operation
set A "218"
set B "235"
set c [expr "($A | $B)"]
puts "This is the result for OR operation $c"
# Output: This is the result for OR operation 251
Explanation:
- A in decimal: 218 → binary: 1010 1101
- B in decimal: 235 → binary: 1011 1110
- OR each bit: 1011 1111 → decimal: 251
Other Logical Operations:
^
XOR operation<<
Shift left operation>>
Shift right operation
hints : don't write numbers on decimal system in TCL shell
Wrong Result |
Lists in Tcl
1. Creating Lists
Method 1: Using spacing and double quotes
set L1 "1 2 3"
# Output: 1 2 3
Method 2: Using spacing and curly brackets
set L2 {A B C}
# Output: A B C
Method 3: Using list command
set L3 [list apple banana mango]
# Output: apple banana mango
2. List Commands
set L1 "1 2 3"
puts "$L1"
# Output: 1 2 3
Get the length of a list
set L1 "1 2 3"
llength $L1
# Output: 3
Get elements of a list
set L1 "1 2 3"
lindex $L1 0
# Output: 1
lindex $L1 1
# Output: 2
lindex $L1 2
# Output: 3
Get the last element of a list
set L1 "1 2 3"
lindex $L1 end
# Output: 3
Get the element before the last in a list
set L1 "1 2 3"
lindex $L1 end-1
# Output: 2
Sorting a list
set L3 [list d b c a]
lsort $L3
# Output: a b c d
Append an item to a list
set fruits [list apple banana cherry]
lappend fruits "date"
puts $fruits
# Output: apple banana cherry date
Get a sublist
set fruits [list apple banana cherry]
puts [lrange $fruits 1 2]
# Output: banana cherry
Loop Structures in Tcl
1. For Loop
for {set i 0} {$i < 5} {incr i} {
puts "Iteration $i"
}
Output:
Iteration 0 Iteration 1 Iteration 2 Iteration 3 Iteration 4
2. While Loop
set i 0
while {$i < 5} {
puts "Iteration $i"
incr i
}
Output:
Iteration 0 Iteration 1 Iteration 2 Iteration 3 Iteration 4
3. Foreach Loop
set L1 "0 1 2 3"
foreach List_item $L1 {
puts "Element $List_item"
}
Output:
Element 0
Element 1
Element 2
Element 3
0 Comments