Search code examples
tclns2

tcl error in set nf[open out.nam w]


the following code

#Create a simulator object
set ns [new Simulator]
#Open the nam trace file
set nf[open out.nam w]
$ns namtrace-all $nf
#Define a 'finish' procedure
proc finish {} {
global ns nf
$ns flush-trace
#Close the trace file
close $nf
#Execute namon the trace file
exec nam–a out.nam&
exit 0
}
#Create two nodes
set n0 [$ns node]
set n1 [$ns node]
#Create a duplex link between the nodes
$ns duplex-link $n0 $n1 1Mb 10ms DropTail
#Call the finish procedure after 5 seconds of simulation time
$ns at 5.0 "finish"
#Run the simulation
$ns run

produces this error

can't read "nffile5": no such variable
    while executing
"set nf[open out.nam w]"
    (file "Desktop/sample.tcl" line 4)

it is my first time in tcl. so what is the problem. i just run this by this statement: > ns sample.tcl


Solution

  • You're missing a space after the variable name:

    set nf [open out.nam w]
    

    Tcl is very dependent on proper use of whitespace. The entire language can be described in 12 rules, listed here. Rule 3: "Words of a command are separated by white space (except for newlines, which are command separators)."

    What was actually happening in your script:

    • Tcl breaks the command into 2 words: the command set and the argument nf[open out.nam w]
    • the command in brackets is executed and the result (the filehandle name returned is file5) is substituted.
    • the set command is executed with its one argument, nffile5
      • when given a single argument, the set command will return the value of the given variable.
      • since you never assigned a variable by that name, set returns an error.