Navigation Logo 2.7  Command Substitution Navigation Logo

 

 

So far, you have seen that procedures and commands are invoked with lines of the form,

command ARG1 ARG2 ... ARGn
and that their return values are thrown away. To use the return value, invoke the command with this syntax:

[command ARG1 ARG2 ... ARGn]
within another command line. This form is useful anyplace where the return value will be useful. The square brackets cause a form of substitution to happen. First, the command line inside the square brackets is executed. Second, the result of that command is substituted in place of the square brackets. This process is called command substitution.

For example, when executing the command,

set X [set Y 0]
there will be a substitution phase for the overall command line. During this phase the command line,
set Y 0
is executed and its value replaces everything in the square brackets. After that substitution, Y contains 0 and the overall command line looks like:
set X 0
This latter form is immediately executed. The overall effect is to set both X and Y to 0.

Exercise 2.7a

Explain the following.
%  [puts {Hellow Orld}]
Hellow Orld
empty command name ""

Solution

Now, we are ready to finish the while command in the file copying example. As a reminder, it looks like this.

while {-1 != the value obtained by executing gets $InFile Line} {
  puts $OutFile $Line
}

Try to figure out what the pseudostep should be before reading the answer which comes next.

The pseudostep will use command substitution to execute a procedure which reads an input line. The result of command substitution will be compared with -1 to see if the attempt to read an input line succeeded.

So the while statement looks like this:

while {-1 != [gets $InFile Line]} {
  puts $OutFile $Line
}

Exercise 2.7b

  1. Assume that Z contains 2. Describe the substitutions that take place when this command is executed.
    set X [set Y $Z]
    
    Pay particular attention to when the substitutions happen.

  2. Use command substitution to finish the statement,
    set Z ...
    
    so that Z will contain a string that consists of whatever is in the variable X followed immediately by "_ext" (without the quotes).

Solution

 

 

[Sample TK Application]
Author's Home Page
Navigation Logo [Book's Cover]
Order from Amazon.