Hi,
I'm new to tcl and I'm having trouble passing arrays to and from procedures. I know it has something to do with upvar, but I can't find any documentation on it. Could someone please give an example?
Thanks,
Juno
Code: Select all
set arr(item1) "value2"
set arr(item3) "value4"
proc test5 {input1 input2} {
puts stdout "STANDARD VAR: $input1"
foreach a [array names input2] {
puts stdout "ARRAY: name = $a : value = $input2($a)"
}
}
proc test6 {input1} {
global arr
puts stdout "STANDARD VAR: $input1"
foreach a [array names arr] {
puts stdout "ARRAY: name = $a : value = $arr($a)"
}
}
test5 "hello" $arr
test6 "hello"
Doing this (for test5) would only generate a 'can't read "arr": variable is array' error.ppslim wrote:Arrays can be passed to and from procedures with ease, and don't need any special treatment.
See netbots.tcl for a lot of helpful examples of this. Something like the following.
Both the test5 and test6 procedure output the same thing, the only differance being,t he way these arrays are passed.Code: Select all
set arr(item1) "value2" set arr(item3) "value4" proc test5 {input1 input2} { puts stdout "STANDARD VAR: $input1" foreach a [array names input2] { puts stdout "ARRAY: name = $a : value = $input2($a)" } } proc test6 {input1} { global arr puts stdout "STANDARD VAR: $input1" foreach a [array names arr] { puts stdout "ARRAY: name = $a : value = $arr($a)" } } test5 "hello" $arr test6 "hello"
test5 is genraly safer, as you can modify the values within the array, without them becoming global.
Code: Select all
proc test5 {input1 input2} {
global $input2 ;# ofcourse, the array needs to be set globally
puts stdout "STANDARD VAR: $input1"
foreach a [array names $input2] {
puts stdout "ARRAY: name = $a : value = [lindex [array get $input2 $a] 1]" ;# split not needed since array get already returns a -list-
}
}
Code: Select all
test5 "hello" "arr"
Code: Select all
proc test5 {input1 input2} {
puts stdout "STANDARD VAR: $input1"
array set arr $input2
foreach a [array names $arr] {
puts stdout "ARRAY: name = $a : value = $arr($a)"
}
}
test5 "hello" [array get arr]