Search code examples
filetclns2

Get the value for a variable from file using tcl


set lambda 1

set lambdaR [open LamdaValue.tr r]
  set Reader [read $lambdaR]
  close $lambdaR

foreach {x} $Reader {
   set lambda $x
  }
set $lambda [expr {$lambda + 1.0}]
set LambdaW [open LamdaValue.tr w]
puts $LambdaW "$lambda"

I'm trying to use this snippet of code to read the value of lambda from a file, modify it, and then write it to the file again. I'm using ns-2 which deals with tcl execution files. But the value of lambda doesn't change... Can you spot where's the error?


Solution

  • It's best to write a small procedure to read the file and return its contents, and another to write the value back out.

    proc readfile {filename} {
        set f [open $filename]
        set data [read $f]
        close $f
        return $data
    }
    proc writefile {filename data} {
        set f [open $filename w]
        puts -nonewline $f $data
        close $f
    }
    

    Then you can simplify the rest of your code a lot:

    set lambda 1
    # The catch means we use the fallback if the file doesn't exist
    catch {set lambda [readfile LamdaValue.tr]}
    
    set lambda [expr {$lambda + 1.0}]
    
    writefile LamdaValue.tr $lambda
    

    The other problem you were having was that you were doing set $lambda. This creates a variable with a strange name. In Tcl, you need to distinguish between reading the variable, when you use $, and naming variable (so a command can update it), when you don't use $. Unless you're wanting to keep the name of one variable in another variable, but it's best to only use that with upvar really to reduce confusion, or to switch to using array elements.