Question

After some frustrating debug, I realize that my understanding of string and list is superficial. Here is the code dragging me down:

1   set a1 "set a 1"
2    set l1 {}
3    lappend l1 [list $a1]
4    puts "l1=$l1"
5    foreach e $l1 { puts $e; eval $e}

The error is at line 5, it needs to be

5    foreach e $l1 { puts $e; set e2 [join $e]; eval $e2}

Basically I need to use a join to convert the list to a string, otherwise the script to eval is "{set a 1}" instead of "set a 1".

I cooked the following test script during the debug:

set li {{set a 1} {set b 2}}
foreach l $li { puts $l; eval $l}

It works fine, I do not need "join".

Yes, I read the on-line doc about list and string. But still cannot wrap my hands around head. Still something not lighting up.

Could you shed some light? I am not sure where I am stuck why cannot appreciate the difference.

Était-ce utile?

La solution

Well, the 'culprit' in your initial code is that you are using lappend l1 [list $a1]. You should be getting:

l1={{set a 1}}

When you use puts "l1=$l1" and what the above means is that you have a list within another list, which is itself in yet another list! (you lose the outermost braces when you print a list)

Indeed, when you do [list $a1], you are appending a list containing the list/element {set a 1} (i.e. {{set a 1}}) to the list $l1 while if you did lappend l1 $a1, you would be adding the string/list {set a 1} to the list $l1.

I think what you actually meant to use is something a bit more like this:

set a1 [list set a 1]
# Where you get a list containing the 3 elements "set" "a" and "1"
set l1 {}
lappend l1 $a1
foreach e $l1 {puts $e; eval $e}

Maybe another way to look at it:

set a1 [list set a 1]
puts $a1
# => set a 1

set a1 {set a 1}
puts $a1
# => set a 1

set a [list $a1]
puts $a
# => {set a 1}  -- A list within a list

set l {}
lappend l $a1
puts $l
# => {set a 1}

lappend l $a
puts $l
# => {set a 1} {{set a 1}}
#      list    list in list  -- and $l is the list containing those two.
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top