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.