YaGaRa12
YaGaRa12

Reputation: 1

Using a variable in tcl

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"
}

Upvotes: 0

Views: 51

Answers (1)

slebetman
slebetman

Reputation: 113896

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.

Upvotes: 2

Related Questions