That's right, there should be no problem with creating variables within the action of a
switch command. The variables should be within the same scope as the
switch statement.
In general, Tcl has a very simple scoping model:[ul][li]Code executed outside of a procedure is in the global scope. Any variables created are global variables, and will exist until explicitly
unset.[/li]
[li]Code executed within a procedure (a
proc body) is local to that invocation of the procedure. Any variables created are local to that scope, and are automatically deleted when the procedure returns.[/li]
[li]Code executed within a procedure cannot "see" any global variables unless you explicitly access them as discussed below.[/li][/ul]
You can "break" this scoping model with the
global and
upvar commands. (I'm ignoring
uplevel for the sake of simplicity. Besides, virtually nobody uses
uplevel unless they
really know what they're doing or are
really confused.) You use
global within the body of a procedure to declare that all the variables listed as arguments to
global are global variables rather than local. You
never use
global outside of a procedure; outside of a procedure you're already in the global scope, so it's redundant to declare a variable as global. (On the other hand,
upvar allows you to create aliases to variables both inside and outside of your scope. I'm not going to get into a discussion of
upvar in this post.) But the point to remember is that a procedure always has to "invite" global variables in; global variables are never "forced" inside of a procedure without its permission. Thus:
Code:
set x 42 ;# Global x
proc myProc {} {
global x ;# Get access to the global x
puts "Global x: $x"
set y "San Francisco, CA" ;# Local y
puts "Local y: $y"
}
# Local y doesn't exist out here
By the way, another way to access global variables is to use namespace syntax. If you use a variable reference of [tt]::x[/tt], it refers to a variable named "x" in the global scope. For example:
Code:
set x 42 ;# Global x
proc myProc2 {} {
# Access x directly from the global scope
puts "Global x: $::x"
}
- Ken Jones, President
Avia Training and Consulting
866-TCL-HELP (866-825-4357) US Toll free
415-643-8692 Voice
415-643-8697 Fax