luc.de...@gmail.com wrote:
> Hi everybody,
>
> I'm new to TCL, if it's not the right place to ask the question,
> please let me know.
This is the right place for these kinds of questions.
Although you also did not tell us which version of Tcl you are using,
so my answers below won't work unless you are at least using version 8.5.
[this quote is a bit out of order....]
> After reading the doc, it looks like multidimensional table dosn't
> exist, I'm wrong somewhere...
They do exist. They just are not called 'arrays'. They are called
"nested lists":
# multi-dimensional array (3x3)
set arr [list [list 1 2 3] \
[list 4 5 6] \
[list 7 8 9]]
puts "Item at 1,1 is [lindex $arr 1 1]"
Running this you get:
Item at 1,1 is 5
> I've a string, that I want to access like a table, list or
> assiociative array, but I'm a little bit lost...
>
> If I print my table :
>
> puts "table $mytable"
>
> It print :
>
> table {{
> name lala
> nodeaddr 8.5.2.1
> port 80
> }} {{
> name lolo
> nodeaddr 5.2.1.4
> port 80
> }}
Ok, first, drop the doubled curly brackets, you don't really need
those, this works just fine too:
set mytable "{
name lala
nodeaddr 8.5.2.1
port 80
} {
name lolo
nodeaddr 5.2.1.4
port 80
}"
Now, what you have there is a string that can be accessed as a list
(note, while this does work, if you get that string from some other
source, you need to be sure they always properly format it as a valid
string representation of a Tcl list, otherwise you'll get weird data
dependent errors that seem to occur randomly.
What you have here is a list with two outer elements.
> If I try to access each value :
>
> foreach item $bigstring {
> puts "item $item"
> }
This iterates over the outer elements (note that foreach only "unwraps"
one layer of a nested list, the current top most one for whatever
string you give it). You then want to further look inside the things
you get back from foreach (but all you do below is "puts" them, so you
are partially on the right track, you just didn't go far enough.
>
> It print :
>
> item {
> name lala
> nodeaddr 8.5.2.1
> port 80
> }
> item {
> name lolo
> nodeaddr 5.2.1.4
> port 80
> }
In your list, your two elements are formatted as Tcl 'dicts' (again,
same warning for data dependent errors applies here). You just need to
go one level lower and "unwrap" the dicts you receive from foreach
> How can I do something like :
>
> foreach item $bigstring {
> puts "name = item(name)"
> }
Like this:
foreach item $mytable {
dict for {key value} $item {
puts "$key=$value"
}
}
If you combine the above with my "set mytable" a bit earlier, and run
it, you'll get this:
name=lala
nodeaddr=8.5.2.1
port=80
name=lolo
nodeaddr=5.2.1.4
port=80