Search code examples
tclproc

How to access a variable from a proc in Tcl


I have a test.tcl file that sources another common.tcl file which contains common procs. Here's a sample content of the common.tcl :

set top_path  path.to.top
set path_a    $top_path.a

proc x { level } {
  if { $level == "top" } {
    puts $top_path
  }
  if { $level == "a" } {
    puts $path_a
  }
}

proc y {
  puts $env(WORKAREA)
}

And here's how the test.tcl looks like :

source $env(PATH_TO_COMMON)/common.tcl
x top
y

The error I'm getting is that the variables (the ones set at the topmost 2 lines of common.tcl) and even the environment variable WORKAREA could not be read (no such variable). No matter if I use set ::env(top_path) and try to read it inside the proc as puts $::env(top_path), I see the same error. Any simple way to resolve this ? There are many lines of setting variables that I need to update.


Solution

  • I don't fully understand your question. How about re-write the script like the following? Add global namespace qualifier :: before the variable names. Also add $ before variable level. And use "eq" instead of "==".

    set top_path  path.to.top
    set path_a    $top_path.a
    
    proc x { level } {
      if { $level eq "top" } {
        puts $::top_path
      }
      if { $level eq "a" } {
        puts $::path_a
      }
    }
    
    proc y {
      puts $::env(WORKAREA)
    }