Gargi Sharma
Gargi Sharma

Reputation: 15

Iterate over list with unmatched open braces

I have the following code:

set m "value {1{0}"
foreach i $m {puts $i}

This results in the error "unmatched open brace in list". Looks like TCL does not consider m to be a valid list due to the unmatched braces. Is there a way to get around this?

Upvotes: 0

Views: 1081

Answers (1)

Chpock
Chpock

Reputation: 682

To avoid such, errors you should not use "strings" where "lists" are expected. The foreach procedure implies a list for its second argument. Your string is incorrect in terms of TCL lists. TCL interpreter is smart, but it doesn't know how to convert this value to the correct list.

The first option is to set the variable as a list:

set m [list "value" "{1{0}"]
foreach i $m {puts $i}

The second option is convert the sting to a list (split the string by a space in this example):

set m "value {1{0}"
set m [split $m " "]
foreach i $m {puts $i}

And again, don't use "strings" where "lists" are expected. Strings can be used, but you should fully understand what you are doing and ensure that the string is in the correct format to be converted into a list.

Upvotes: 3

Related Questions