Flavie
Flavie

Reputation: 1

TCL Split string by special character

I have a string in tcl say:

set name "a_b_c_d"

and I want to get 4 variables out of it like $a would have the value, $b the value b, etc...

Thanks a lot !

Upvotes: 0

Views: 3881

Answers (2)

Jerry
Jerry

Reputation: 71538

Your requirement is a bit strange in my opinion, but that's how I would do it:

set name a_b_c_d
foreach item [split $name "_"] {
    set $item $item
}

You didn't ask for the following, but I believe it might be better if you use an array, so you know exactly where your variables are, instead of just being 'there' in the open:

set name a_b_c_d
foreach item [split $name "_"] {
    set items($item) $item
}

parray items
# items(a) = a
# items(b) = b
# items(c) = c
# items(d) = d

EDIT: Since you mentioned it in a comment, I'll just put it here: if the situation is as you mentioned, I'd probably go like this:

lassign [split $name "_"] varName folderName dirName

And it should still work most of the time. Dynamic variable names are not recommended and can 90% of the time be avoided for a safer, more readable and maintainable code. Sure, it works for things that you just need once in a blue moon, but you need to know what you are doing.

Upvotes: 0

Donal Fellows
Donal Fellows

Reputation: 137577

This is exactly what the split command is for. You just need to provide the optional argument that says what character to use to split the string into a list of its fields.

set fields [split $name "_"]

Note that if you have two of the split character in a row, you get an empty list element in the result.

Upvotes: 1

Related Questions