I am trying to populate an array dynamically rather than setting it manually by running a counter like below:
set all_list { <my list>}
set num_pc_a_b 10
for {set i 0 ;set j 0 ; set k 0} {$j < $num_pc_a_b} {incr j; incr i ;incr k} {
array set link_map {[lindex $all_list $i] $j $k 0 }
}
and hoping to access the variables like below:
foreach {key value value1 value2} [array get link_map] {
puts "key is $key"
puts "value is $value"
puts "value is $value1"
puts "value is $value2"
}
But it doesn’t work . Am I doing something wrong here ?
It’s not immediately obvious to me what you really wanted to do, so I’ll make some guesses.
In either case note that your usage of
array set ...appears to be wrong: this command takes the name of an array and a list which it interprets as alternating keys and values, creating an entry in that array for each key mapped to the value following that key. You seem to want to just set a specific key to a specific value on each iteration — this is done byset array(key) valuesyntax.Also note that in your example the
j,iandkvariables seem to have the same values on each iteration. Supposedly it’s just a left-over from a real-world code, but otherwise just one variable would be enough.Guess one: you want to map each key to a list of values. This won’t work like in your example as in Tcl an array maps each key to one value; this value might be a list though. If my guess is correct, the way to go is:
Guess two: judging from your usage of
foreachfor displaying, you might want to not use an array at all, but rather a list:You could as well make not a flat list but a list of alterating keys and values, with each value being a
[list $j $k 0]as in the first guess example.Update
Guess three. You tagged our question as
multidimensional-array. I do not see any trace of multi-dimentionality in your snippets, but if you really wanted it, the usual paradigm in Tcl for this is to use compound keys. For instance, if you want to key your array by values ofj,iandkthese variables have on each iteration, use something like:This creates a string concatenating three values using a comma and uses the result as the key.
The usage of
foreach ... breakto explode a list is a neat trick, but if you have Tcl 8.5 or later, uselassign $list v1 v2 v3instead.