1

I need to 'upvar' variables from a source'd file (and I don't know their names)

Let's say I have a TCL file containing:

set v 7

Now this:

proc p {} {
  source t.tcl
}

p

puts $v
# => can't read "v": no such variable

The file t.tcl must not be changed.

I also can't have knowledge about the content of t.tcl. Let's assume it's passed as an env variable. How do I make v visible at the top level?

Jerry
  • 70,495
  • 13
  • 100
  • 144
Gert Gottschalk
  • 1,658
  • 3
  • 25
  • 37

1 Answers1

3

For the code you posted, change the definition of p to:

proc p {} {
    upvar 1 v v
    source t.tcl
}

or (to specifically connect the variable to the top level:

proc p {} {
    upvar #0 v v
    source t.tcl
}

(Note: the syntax highlighter thinks the string "#0 v v" is a comment, but it isn't.)

Members of the env are global, so you won't have that problem there.

However, if you don't know the names of the variables it's less simple, because you can't upvar a variable once it exists.

Is it possible to evaluate the source command in the top level, like this:

proc p {} {
    uplevel #0 source t.tcl
}

(Again, not a comment.)

Or do you have to evaluate it in p's level?

Documentation: proc, puts, set, source, uplevel, upvar

Documentation for env

(Note: the 'Hoodiecrow' mentioned in the comments is me, I used that nick earlier.)

Peter Lewerin
  • 13,140
  • 1
  • 24
  • 27
  • Hi Hoodiecrow,Note that I said : The file t.tcl must not be changed. I also can't have knowledge about the content of t.tcl. – Gert Gottschalk Jul 17 '14 at 22:55
  • @GertGottschalk: it's possible you didn't read my answer closely. Nothing in my answer suggests or requires changes to t.tcl. I did try to suggest a solution for the case where the variable names are unknown, though it depends on whether it is possible/allowed to evaluate the `source` command in the top level. – Peter Lewerin Jul 17 '14 at 23:10
  • Hi Hoodiecrow. Ah, I see. Yes, the code with uplevel works. (though I changed it to uplevel 1 so that it goes up only the 1 level for the proc. Thanks! That resolves my issue. – Gert Gottschalk Jul 18 '14 at 00:25