tags:

views:

47

answers:

3

I just found myself in a position where I have two arrays in TCL/TK.

I'm given $W_Array and $P_Array

I need to traverse through one array not knowing what the size of each one is before hand, and execute a command only when there is a value for both arrays. Yes the array lengths could be different.

What is the best way of doing this?

+1  A: 

Not sure exactly what you mean by "a value for both arrays", but tcl's foreach supports iteration over multiple arrays at once... so you can say e.g. foreach w $W_Array p $P_Array { if {$w == $val && $p == $val} { ... } }

When the arrays are not of the same length, foreach will return all values from the longest array and the empty value {} for the missing elements in any shorter arrays.

ccmonkey
A: 

Use llength command to find out if the arrays contain a value.

if {[llength $W_Array] > 0 && [llength $P_Array] > 0} {
# Do something
}
Andrew Dyster
I don't think this comes close to answering the actual question. Admittedly the question is slightly vague.
Bryan Oakley
+3  A: 

The other answers jumped to using lists, I presume you mean Tcl's array, which are also called hash maps or associative arrays.

I think you're asking for something like:

array set a1 {a 1 b 2 c 3 d 4 e 5}
array set a2 {z 0 x 1 b 2 e 99}
foreach n [array names a1] {
  if {[info exists a2($n)]} {
    puts "Do something with $a1($n) and $a2($n)"
  }
}

# FOREACH LOOP RESULTS IN THESE TWO PRINTOUTS
Do something with 5 and 99
Do something with 2 and 2
Trey Jackson