Reputation: 1028
I did some research but only find ugly hacks, which uses unique name for each array element and save the names into a list. Is there any way to do this right?
Upvotes: 2
Views: 4066
Reputation: 247210
Instead of arrays, you want to use dictionaries: http://www.tcl.tk/man/tcl8.5/TclCmd/dict.htm
Dictionaries are first-class variables and can be passed around (and placed in a list) just like other variables.
% set d1 [dict create a b c d]
% set d2 [dict create e f g h i j]
% set lst [list $d1 $d2]
% set lst ;# ==> {a b c d} {e f g h i j}
Upvotes: 2
Reputation: 40783
At work, we still use Tcl 8.4. I know that dict has been back-ported, but it is not part of the standard packages. For 8.4, we use keyed list from the Tclx package. here is an example:
# Problem: I want to create a list of arrays
# Solution: For 8.5, I can have list of dict, but for 8.4, use
# keyedlist in place of dict. This script is written for 8.4
package require Tclx
# Create individual users and a list
keylset user1 id 101 alias john; # {{id 101} {alias john}}
keylset user2 id 102 alias ally; # {{id 102} {alias ally}}
set users [list $user1 $user2]
# Show the list
foreach user $users {
puts "ID: [keylget user id]"
puts "Alias: [keylget user alias]"
puts ""
}
Output:
ID: 101
Alias: john
ID: 102
Alias: ally
Upvotes: 2