expr command In TCL

 Until now, we have learnt to assign a value to  a variable using the set command. But if we'd like to add, subtract or to perform some other types of math operations then we can use expr command to perform such operations. 

We have read in Using A Value Returned By A Command In TCL to capture the returned value by a command. So we can use expr command inside [] and use the value returned by expr command. 

Before seeing expr in action, we have read in Grouping Strings In TCL  that a variable value is not substituted inside {}. So, to stop TCL interpreter to substitute the value of a variable before expr command has an opportunity to evaluate it, we often enclose arguments to expr inside {} as a security measure.

Here we are going to write a file named exprp1.tcl and then we will run it as, tclsh exprp1.tcl 

set a 20;
set b 020; # It's an octal value and its value is 16.
puts [expr {$a + $b}]; # 36
puts [expr {$a - $b}]; # 4

In the above example, we have used an octal number which starts with 0 and includes digits from 0 to 7. So, we can't write 081, 094, and so on. The place values are 1, 8, 64, 512, and so on.

Here we are going to write a file named exprp2.tcl and then we will run it as, tclsh exprp2.tcl 

puts "2 raised to the power of 5 is: [expr {2**5}]"; # 32
puts "The remainder, when 12 is divided by 5, is: [expr {12 % 5}]"; # 2
set x 5; # Assign the value of x whatever you want
puts "If the value of x is greater than 0 then we will get 1 else 0: [expr {$x > 0}]";

We'll learn about more operators in the future posts.

Here we are going to write a file named security.tcl and then we will run it as, tclsh security.tcl 
set y {[exit]}
puts $y
puts [expr {$y != 1}]
puts [expr "$y != 1"]

From the output of the second line, we see that [exit] is being substituted in place of $y. But on the third line, since $y is inside braces it is not substituted as usual and the expr command takes control and substitutes $y and compares with 1 and returns 1 because [exit] is not equal to 1, which is being printed by the puts command.
On the fourth line, $y is inside double quotes, so it is being substituted as usual and when the expr command takes control, [exit] is being executed and program ends. This is why we will use braces in place of double quotes to pass arguments to a command in the future.

Happy reading and thank you. Meet you soon.

Comments

Popular posts from this blog

Bash Shell In Linux

Creating An Animation Using A Text Editor