Search code examples
foreachtcl

Tool Command Languare Byte String loop


I am using tcl and my data looks like this b'{{"George" "F" "Smith" "Nevada" "UCLA"} {"Mike" "Z" "Jones" "California" "NU"}}'

I am removing b' and the ending '.

set testData "b'{ {\"George\" \"F\" \"Smith\" \"Nevada\" \"UCLA\"} {\"Mike\" \"Z\" \"Jones\" \"California\" \"NU\"} }'"
set testData [string range $testData 2 end-1]

leaving {"George" "F" "Smith" "Nevada" "UCLA"} {"Mike" "Z" "Jones" "California" "NU"} How do I turn this into a list so I can loop over the data. What i have tried does not work.

set list2 [list $testData] (does not work)
foreach item $list2 {
    puts "[lindex $item 0 ] [lindex $item 1 ]" 
}

Solution

  • Remember in tcl, everything's a string, but if it looks like a list/number/etc., it can be used as a list/number/etc.

    After stripping the leading b' and trailing ', you're left with a string that looks like a single-element list - where that single element itself is a list. So you can do something like:

    foreach item [lindex $testData 0] {
        puts "[lindex $item 0] [lindex $item 1]" 
    }
    

    to iterate over its elements.