Search code examples
stringtclstring-concatenation

Concatenating two strings in tcl


I need to concatenate two strings in tcl and then trim the concatenated string if there is any unwanted character like '_'. The strings are stored in tcl variables and the problem I am facing is that I need to concatenate these two strings like "$str1_$str2". Basically join two strings with an '_' in between them. I found the way to do it as below.

    set str1 "mystring1";  #string 1
    set str2 "mystring2";  #string 2. This string could be Empty String as well.

    set outString [append outString "_" $str2];
    set outString [string trimright '_'];

This gives me the value of outString as below :

    puts $outString;  
    mystring1_mystring2    #if $str2 is not empty
    mystring1              #if $str2 is empty. 

I am looking for a more optimized way to achieve my task. I tried to simply join the two strings like

    set outString "$str1_$str2"

But I get the error as "No such variable as $str1_" since '_' underscore can be part of variable name.

Any suggestions would be appreciated.


Solution

  • When interpolating a variable into a string, you can use curly braces to protect the variable name.

    set str1 "mystring1";
    set str2 "mystring2";
    set outString "${str1}_${str2}"
    

    (The same syntax works in shell scripts, in Perl, and probably in other scripting languages.)

    But I wouldn't count on this being "more optimized" that calling append. It's easier to read, which IMHO is a good enough reason to do it this way, but don't assume it's faster until you've measured it.

    Reference: http://www.tcl-lang.org/man/tcl8.6/TclCmd/Tcl.htm#M12