Programmer
Programmer

Reputation: 8707

TCL how to traverse and print all values for a variable having string and list

I have a 3rd party APIs that gives me below output:

puts [GetDesc $desc " "] #prints below data
#A_Name 9023212134(M) emp#121 M { 41 423 }

How can I access all the token of the value printed and the list { 41 423 }?

Upvotes: 0

Views: 683

Answers (2)

Donal Fellows
Donal Fellows

Reputation: 137567

You can iterate over the values in the result with foreach:

foreach value [GetDesc $desc " "] {
    puts ">>> $value <<<"
}

This will print something like this (note the extra spaces with the last item; they're part of the value):

>>> A_Name <<<
>>> 9023212134(M) <<<
>>> emp#121 <<<
>>> M <<<
>>>  41 423  <<<

Another approach is to use lassign to put those values into variables:

lassign [GetDesc $desc " "] name code1 code2 code3 pair_of_values

Then you can work with $pair_of_values easily enough on its own.

Upvotes: 0

Andreas
Andreas

Reputation: 5301

The output is a list of 5 items, where the last is a list of two elements. You extract elements in a list using lindex:

set var {A_Name 9023212134(M) emp#121 M { 41 423 }}; # A_Name 9023212134(M) emp#121 M { 41 423 }
lindex $var 0; # A_Name
lindex $var 4; # 41 423 (Note: leading and trailing spaces are preserved)
lindex $var 4 0; # 41
lindex $var 4 1; # 432

Upvotes: 1

Related Questions