The set
command is used to assign values to variables in Tcl. It can also be used to retrieve the value of a variable.
set varName ?value?
Here, varName
is the name of the variable, and value
is the value to assign to the variable. If value
is omitted, set
returns the current value of varName
.
# Assign a value to a variable
set myVar "Hello, World!"
# Retrieve the value of the variable
puts $myVar ;# prints "Hello, World!"
# Update the value of the variable
set myVar "New Value"
puts $myVar ;# prints "New Value"
# Retrieve the current value without updating
set currentValue [set myVar]
puts $currentValue ;# prints "New Value"
The puts
command is used to print a message to the console. It can also write to a file if specified.
puts ?-nonewline? ?channelId? string
Here, string
is the message to print. The optional -nonewline
flag prevents a newline from being added at the end. channelId
specifies the output channel (default is stdout
).
# Print a simple message
puts "Hello, Tcl!"
# Print without a newline
puts -nonewline "Hello, "
puts "Tcl!" ;# prints "Hello, Tcl!" on the same line
# Print to a file
set fileId [open "output.txt" "w"]
puts $fileId "Writing to a file"
close $fileId
To begin, open a Linux terminal and execute tclsh
to launch the Tcl shell. Prior to diving into scripting, let's cover some foundational Tcl commands and concepts.
%> set variable 10
%> set result [expr $variable / 9]
%> puts $result
1
%> set result1 [expr $variable / 9.0]
%> puts $result1
1.1111111111111112
%> set variable1 10.0
%> set result2 [expr $variable1 / 9]
%> puts $result2
1.1111111111111112
Tcl supports five categories of operators:
Arithmetic operations in Tcl are similar to basic mathematical operations. Here are some examples:
Relational operators compare two values and return true or false. Examples include:
Logical operators evaluate the logical relationship between values. Examples include:
Bitwise operators perform operations on bits of a number. Common bitwise operators are:
The ternary operator (?:
) evaluates a condition and returns one of two values depending on whether the condition is true or false.