Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Is it possible to return an array ??

Status
Not open for further replies.

ruigo

Programmer
Oct 21, 2000
1
PT
Can I return an array from a Tcl procedure?

Thanks in advance. [sig]<p>Rui Gouveia<br><a href=mailto:ruigo@caleida.pt>ruigo@caleida.pt</a><br><a href= Personal Homepage</a><br>[/sig]
 
The short answer is no. In order to make your code efficient, Tcl forces you to pass arrays to procedures by reference. This simply means that the procedure has a parameter which the name of the array, and the procedure uses &quot;upvar&quot; to access it.

However you can return lists from procedures, and note that the &quot;array set&quot; takes a list of name and value pairs as an argument. So the effect of returning an array can be achieved by returning the list to drive an array set command. Consider the following example:
Code:
% proc x {} { return [list molly 2 fred 3 tom 6] }
% array set r [x]
% array names r
tom fred molly
% set r(fred)
3
% set r(molly)
2
% set r(chris)
can't read &quot;r(chris)&quot;: no such element in array
 
What I do routinely is to compute the array inside the procedure, then use &quot;array get&quot; to create a list (still inside the procedure), then return the list. Then I set the target array in the calling program with &quot;set arrayx [procname]&quot;
 
What I do routinely is to compute the array inside the procedure, then use &quot;array get&quot; to create a list (still inside the procedure), then return the list. Then I set the target array in the calling program with &quot;array set arrayx [procname]&quot;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top