user32882
user32882

Reputation: 5877

Tcl: Why is the dollar sign used in the first argument to `upvar`?

The tcl docs provide the following example on how to use the upvar command:

proc add2 name {
    upvar $name x
    set x [expr {$x + 2}]
}

Inside this procedure, x acts as a reference to the variable name which belongs to the scope outside of add2.

I don't understand why the first argument to upvar has to be provided with the dollar sign, and the second argument not. Shouldn't it simply be upvar name x, since we are referencing name rather than its value?

Upvotes: 0

Views: 158

Answers (2)

Alex P
Alex P

Reputation: 96

Donal's answer might be illustrated this way:

proc addfred {} {
   upvar fred fr
   incr fr 2
}
% set fred 3
3
% addfred
5
proc addfred {} {
   upvar "fred" fr
   incr fr 2
}
% addfred
7

I.e. you need not have the upvar-ed variable in the proc's parameters at all, to make it work.

With "level" option of upvar, you can add even more resourcefulness to this.

Upvotes: 1

Colin Macleod
Colin Macleod

Reputation: 4382

Here's an example of how add2 might be used:

(Tcl) 2 % set fred 3
3
(Tcl) 3 % add2 fred
5

Here add2 is called with its parameter called "name" set to the value "fred". If the code then did upvar name x it would be operating on a variable literally called "name" but we need it to operate on the variable called "fred" so we write $name to get the value "fred" from the parameter called "name".

Upvotes: 3

Related Questions