0

I'm trying to use a global variable in other proc in tcl.

Here's a short example:

proc myname {} {
    set ::name [gets stdin]
}

proc myname2 {} {
    puts "your name is: $name"
}
tcl_shell> proc myname

Jhon <--- "Jhon" should be stored in varible called *name*

tcl_shell> proc myname2

your name is Jhon <-- I want something like this.

But I'm still seeing this error: Error: can't read "name": no such variable

I also have tried this:

proc myname {} {
    global name
    set name [gets stdin]
}
    
proc myname2 {} {
    puts "your name is: $name"
}

1 Answer 1

2

You are trying to read a variable name that is in the myname2 scope:

proc myname2 {} {
  puts "your name is: $name"
}

Of course there is no variable name inside the myname2 function. The variable you saved to is in global (::) scope so you can either do:

proc myname2 {} {
  global name
  puts "your name is: $name"
}

or

proc myname2 {} {
  puts "your name is: $::name"
}

Unlike C/C++ tcl hides the global scope by default. You need to deliberately import variables from global scope into your functions.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.