3
proc rep {name} {
    upvar $name n 
    puts "nm is $n"
}

In the above procedure, 'name' is a parameter which is passed to a procedure named 'rep'. When I run this program I got "error : Can't read "n" : no such variable". Could any one tell me what could be the possible cause for this error.

Donal Fellows
  • 133,037
  • 18
  • 149
  • 215
Praveen kumar
  • 597
  • 2
  • 14
  • 26

2 Answers2

5

That error message would be produced if the variable whose name you passed to rep did not exist in the calling scope. For example, check this interactive session with tclsh…

% proc rep {name} {
    upvar $name n 
    puts "nm is $n"
}
% rep foo
can't read "n": no such variable
% set foo x
x
% rep foo
nm is x

Going deeper…

The variable foo is in a funny state after the upvar if it is unset; it's actually existing (it's referenced in the global namespace's hash table of variables) but has no contents, so tests of whether it exists fail. (A variable is said to exist when it has an entry somewhere — that is, some storage to put its contents in — and it has a value set in that storage; an unset variable can be one that has a NULL at the C level in that storage. The Tcl language itself does not support NULL values at all for this reason; they correspond to non-existence.)

Donal Fellows
  • 133,037
  • 18
  • 149
  • 215
  • As for why your code is failing, I'm guessing you passed the wrong variable name in or called it from the wrong scope. Easily done. – Donal Fellows Feb 08 '13 at 08:57
  • This is so helpful. I was having similar issues but never thought of scope. – Raj Oct 18 '16 at 00:25
2

I ran into this too. I realized I was sending $foo instead of foo (note, no dollar sign).

% set foo 1
%
% rep $foo
can't read "foo": no such variable
%
% rep foo
nm is 1

Hope it helps.

Bijan
  • 7,737
  • 18
  • 89
  • 149
  • This answer does not explain the difference between evaluating a variable with the $ or just using the variable...but I can saw that from reading this it made me realize I too was trying to evaluate when I don't need to for an application. – Raj Oct 18 '16 at 00:27