Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Returning arrays from procedures

1,641 views
Skip to first unread message

Cassy

unread,
Aug 9, 2005, 8:32:40 AM8/9/05
to
Dear all,

Is it possible to return arrays from procedures ? When I do so in my
procedure, the compiler says "Can't read array variable <name of the
variable>"

What's the solution ?

Bye.
H.

mgaurav

unread,
Aug 9, 2005, 8:44:01 AM8/9/05
to
Use pass by refernce for arrays i.e. "upvar". For example:

#!/bin/env tclsh
proc foo { } {
upvar myArr localArr
array set localArr { 1 one 2 two 3 three }
}

array set myArr {}
foo
parray myArr

-Gaurav

suchenwi

unread,
Aug 9, 2005, 9:02:13 AM8/9/05
to
Or serialize the array to return it:

proc example {} {
set foo(1) hello
set foo(2) world
array get foo
}
array set bar [example]

mgaurav schrieb:

Cassy

unread,
Aug 9, 2005, 10:31:43 AM8/9/05
to
Thanks Suchenwi,

That worked perfect, now how can I pass arrays to procedures, had some
problems just now, wasted an hour ...

how can i do something like :

proc example {myArr} {
.
foreach ele [array names myArr] {
puts $ele
}

It seems like I have to do a sequence of array get and set again ???
Please explain with an illustration like before, thanks.

Robert Seeger

unread,
Aug 9, 2005, 10:45:05 AM8/9/05
to
What you want is:

proc example {myArrName} {
upvar 1 $myArrName myArr

foreach elem [array names myArr] {
puts $elem
}
}

array set data {a 1 b 2 c 3}
example data
-> a 1
b 2
c 3


The upvar ties a variable in an upper context level (up 1 level in this
case) of the specified name (which was passed in in myArrName) to a
local variable (myArr).

As an aside, if you're using Tcl 8.5, consider using Dicts instead. They
work much like arrays, but can be passed by value instead of name.

Rob Seeger

0 new messages