HOWTO: reference elements of an array if array name is in a variable 
Author Message
 HOWTO: reference elements of an array if array name is in a variable

Here is a pretty little hack that probably everyone already knows but I have
not seen documented anywhere. Maybe we can convince LWV to put it in the

Q: How do you reference array elements if the array name is in a variable?

A: Suppose you have a variable named "foo" which contained the name of an
array "zot1":

        set count 1
        set foo [format {%s%d} "zot" $count]

The best way I can think of to reference zot1's elements is to use
an "alias" variable. Do this by using the "upvar" command.

        upvar 0 $foo bar
        set bar(1) {element one}
        set bar(2) {element two}

        puts $zot1(1)
                --> element one

You can also do weird things with the "eval" command but I have found using
the "upvar" method both more efficient because it only has to dereference
the array name once, and easier to use.

I actually started to type an example of using the "eval" command to
do this and my example became so hard to read that I decided to delete
it. If anyone wants to see this method, let me know and I will send it
to you.

Perry Statham

Fri, 23 Jan 1998 03:00:00 GMT  
 HOWTO: reference elements of an array if array name is in a variable

Two notes - any time you have a piece of information which you feel would
work well in a FAQ or some sort of Tcl/Tk reference document, be sure to
EMAIL the person maintaining the appropriate FAQ.  Some of us have quirky
news sites and miss particular postings (I never did see Dr O's announcement
of the Tcl and Tk patches - just stumbled over them a week or two ago).

The other note - Here is the list of who maintains what FAQ - in case
you want help figuring out to whom a piece of email should go:


:s My new WWW home is coming...
:s Unless explicitly stated to the contrary, nothing in this posting should
:s be construed as representing my employer's opinions.

Mon, 26 Jan 1998 03:00:00 GMT  
 [ 2 post ] 

 Relevant Pages 

1. Access Array Elements by Arrays Reference

2. Shifting array element & regex on array element

3. Arrays: Build array in multiple for loops or replace array elements

4. how to access arrays with variable for array names and index

5. access to array if name of array is variable

6. HOWTO: LinkVar with Tcl array elements and Tcl bugs

7. array name in variable variable

8. HowTo sort an Array not vor Names but for Values

9. Passing array elements by reference

10. access type referencing nested array element

11. for every element of array find bounds in another array

12. Array and creation of the elements of the array


Powered by phpBB® Forum Software