TCL how to pass out array from a func?

In the following sample code, I could print array in a function, but could not do it outside of that function.

proc foo { ...  } {

    parray internalArr

    return internalArr
}

array set externalArr [foo]
parray externalArr
array set externalArr [array get [foo]]
parray externalArr

Also how to initialize/cleanup array to be empty one? How to convert array to list?
gs_kanataAsked:
Who is Participating?
 
fridomConnect With a Mentor CEO/ProgrammerCommented:
E.g like this:

proc foo {} {
    set return_arr(0) "element0"
    set return_arr(1) "element1"
    array get return_arr
}


array set arr [foo]


parray arr

Open in new window

0
 
Duncan RoeSoftware DeveloperCommented:
return internalArr simply returns the string internalArr. If you had wanted to work an array at a higher level, you should have used upvar.
In Tcl, everything is a string. Your calling program can work if foo returns the right string:
18:31:13$ cat ee74.sh 
#!/bin/sh
# sh obeys the next line but tclsh treats it as a comment continuation \
exec tclsh "$0" "$@"
proc foo {} {
    array set internalArr {a b c d}
    parray internalArr
    return [array get internalArr]
}
puts [foo]
array set externalArr [foo]
parray externalArr
18:31:19$ ./ee74.sh
internalArr(a) = b
internalArr(c) = d
a b c d
internalArr(a) = b
internalArr(c) = d
externalArr(a) = b
externalArr(c) = d
18:31:24$ 

Open in new window

The extra puts is there to show what the output from foo looks like
0
 
Duncan RoeConnect With a Mentor Software DeveloperCommented:
In regard to initialising an aray, array unset of an array will remove it altogether. If you really want to re-make it with no elements, add an element to a new array and then remove only that element:
18:15:26$ tclsh
% array set a {a b}
% parray a
a(a) = b
% array unset a a
% parray a
% exit
19:25:17$ 

Open in new window

0
 
Duncan RoeSoftware DeveloperCommented:
array get converts an array to a list - with alternate list elements being indexes and values
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.