Reputation: 15
Pass argument to proc, expected result is puts $cust_id
in proc
will print the 123
instead of $cust_id
proc hello {cust_id} {
puts $cust_id
}
set cust_id 123
puts $cust_id
hello {$cust_id}
Output is
123
$cust_id
Upvotes: 1
Views: 838
Reputation: 137767
When you call hello
, you give it a value and it prints that value that it was given (because you pass it to puts
inside the body). When you call:
puts $cust_id
You are telling Tcl to read the cust_id
variable and use that as the argument word to puts
. But if you do:
hello {$cust_id}
then you are disabling substitutions (that's the literal meaning of putting something in braces in Tcl, and always was) so you get $cust_id
passed into hello
(and printed).
You can pass variables to procedures. You do it by giving them the name of the variable, and then using upvar
to bind that to a local name. Like this:
proc hello {varName} {
upvar $varName someLocalName
puts $someLocalName
}
set cust_id 123
hello cust_id
Note that this is exactly the pattern used by the set
command above. It is not special (other than that it is provided for you by the Tcl runtime; it's standard library, not language per se).
Yes, the upvar
name is special (it converts a variable name into a variable) and it, along with uplevel
, is one of the key features of Tcl that other languages don't have.
Upvotes: 3