I'm sourcing 2 files into my TCL script. Both having some variables with same name but different values. I've to use the both files and I can't modify them. How can i overcome this problem..?
-
Can you source them in different namespaces? – Leon Nov 08 '16 at 14:21
1 Answers
The two ideas that come immediately to mind are to try namespaces or interpreters.
Separating Scripts with Namespaces
In this case, we're just doing:
namespace eval A {
source script-a.tcl
}
namespace eval B {
source script-b.tcl
}
It's not guaranteed that these won't conflict — they're not strongly separated — but they might work. It's definitely an easy first thing to try, and the variables and procedures created should be separated.
Separating Scripts with Interpreters
This method definitely walls scripts off from each other, but can be more awkward to work with since it also walls them off from the rest of your application (unless you provide appropriate cross-interp aliases):
interp create Acontext
interp eval Acontext {
source script-a.tcl
}
interp create Bcontext
interp eval Bcontext {
source script-b.tcl
}
As I noted above, this doesn't let the scripts see anything done by the main script by default; the walling off is pretty much total. To grant access to a command in the main interpreter, you need to make an alias:
proc mainContextOperation {callee args} {
puts "this is in the main context called from ${callee}: $args"
}
interp alias Acontext DoMyThing {} mainContextOperation Acontext
interp alias Bcontext DoMyThing {} mainContextOperation Bcontext
Make these aliases before you do the source
calls (but after the interp create
calls), and those scripts will be able to use the DoMyThing
command to write a message out while the main context will have a really good idea what is going on.
Tcl uses this mechanism as a basis for safe interpreters, which are how you can evaluate untrusted Tcl code without exposing much ability to cause mischief.

- 133,037
- 18
- 149
- 215