An odd quirk about Tcl, something that gets many engineers hung up, is that everything can be represented as a string. We’ll see how this impacts the way we assign variables in Tcl. To assign a variable we use
set variable value
which sets the contents of
set word tom
set number 5
set phrase1 "Multiple words must be contained within double quotes"
set phrase2 {Or they can be contained within braces}
set number; #returns 5
Creating arrays is very easy using the set command. Simply add parentheses and an index to the first argument as shown
set array(0) "Storing an array"
set array(1) "is pretty simple."
set array(-1) "The indices can be negative"
set array(tom) "Or even strings, because everything is a string"
set array(2) 8
Let’s say you want to assign a variable the contents of another variable. You’d first have to dereference the variable before assigning it using the $ character before the variable. In Tcl, the compiler performs a round of substitution before executing the command looking for all $ characters and substituting those variables with their contents.
set myAge 37
set yourAge $myAge
Printing out the content of variables is easy, just use the puts command with a dereferenced variable.
set children(1) Jessica
set children(2) Christopher
set children(3) Julie
puts $children(1)
puts $children(2)
puts $children(3)
Most of the time you’ll want to print text with the variable. For that simply use puts with the text and dereferenced variable enclosed in quotes. Note: If you use braces to group your text and variable together the compiler skips the substitution process and treats $ as a normal character, the end result is the variable is not
puts "yourAge = $yourAge!"; #this will print yourAge = 37!
puts {yourAge = $yourAge!}; #this will print yourAge = $yourAge!
puts "yourAge = \$yourAge!"; #this will print yourAge = $yourAge!
Take a moment and practice creating variables with the set command and printing them with the puts command. Feel free to experiment and try different things. This will help you learn the quirks of the language and get you more comfortable programming in Tcl.
Exercise
For this exercise we’re going to create common messages that might be used when working with Electronic Design Automation (EDA) tools. The messages will be printed to the console using the puts command.
- Create a variable storing today’s date using the set command (the date can be whatever format you like best)
- Next, create an array of 3 messages (if you don’t remember how to create an array, look at the code examples above for help). The messages should look like
- info: The script has finished executing successfully
- Warning: The selected component is out of date. Consider updating
- Error: Could not finish executing script because an error occurred
- Finally, print out today’s date and one of the messages all on the same line.