Why filename is not getting rendered properly

2020-05-06 14:08发布

问题:

I am in need to redirect output of program to a file and below is the code that I am using to create the output log file name:

set filename "C:\tools\tcl\bin\my.log"
puts "The log file $filename"

But this prints :

 The log file C: ools    cinmy.log

Note I can also receive the filename as argument to script:

set logfile [lindex $argv 1]

How can I resolve the issue for both case when receive logfile as arg and as constant?

回答1:

Tcl will do backslash substitution and these substitution will happen only with double quotes. If you need a literal backslash, you have to escape it. When enclosed with braces, these substitution will not happen.

So, you can define your variable as

set filename "C:\\tools\\tcl\\bin\\my.log"

or

set filename {C:\tools\tcl\bin\my.log}

About the command line argument stuff, don't bother. Tcl will take care of it. It will be received as it is from your terminal.



回答2:

But this prints :

The log file C: ools cinmy.log

This is because a literal string between double quotes is subjected to backslash substitution. For example, "\t" is interpreted as the tab control character, and not as a file-path element with \ as separator.

Your options:

  • Escape the single backslashes: "\t" becomes "\\t"
  • Use curly braces, which prevents backslash substitution from happening: "\t" becomes {\t}
  • Use Tcl's [file] command to assemble the file path:

    file nativename [file join C:/ tools tcl bin my.log]

The latter option is the preferred one.



标签: tcl