0

Let's say I have a regular variable that contains the name of an existing array.

array set myarr {
    key_1 val_2
    key_2 val_2
}

set myvar myarr

I can found nowhere how I can iterate over myarr from myvar!

2
  • 1
    Just write $myvar where you would otherwise write myarr. Such as in array names $myvar. Commented May 22, 2015 at 15:56
  • Thanks Peter! The following seems to work: foreach {key value} [array get $myvar] { puts "$key => $value" } Commented May 22, 2015 at 16:07

1 Answer 1

2

The variable myvar is a simple variable that is holding the name of another variable. You can use a read from it (with $ or set) anywhere where you'd expect to use the name of the variable:

foreach {key value} [array get $myvar] {
    puts "$key => $value"
}

What you can't do directly is use the name to access the contents of the array. To do that, you'd usually use upvar 0 to map the named thing to something that you can work with more easily:

upvar 0 $myvar v
foreach key [lsort [array names v]] {
    puts "$key => $v($key)"
}

(In this case, and provided you're using Tcl 8.6, you could use the -stride option to lsort to work with array get instead of array names, which would let you avoid making the alias. But that's a different way to achieve the same output really, and only applies if you're doing key-sorted array iteration…)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.