Search code examples
tclexpect

How to create a file with given name and contents in tcl?


What is the tcl equivalent of the following?

cat <<EOF > example/file.txt
example
file
contents
EOF

What I have so far:

set outfile [open "example/file.txt" w]
try {
  puts $outfile "example
file
contents"
} finally {
  close $outfile
}

What I dislike:

  1. open, set, try/finally, puts, close - too many trees for the forest to hide behind
  2. The first line of the contents has to be formatted oddly or else I get an additional empty line at the beginning of the file

Solution

  • The way to deal with the “complexity” is to put the code in a procedure. Then you can ignore the complexity.

    proc writefile {filename contents} {
        set outfile [open $filename w]
        try {
            puts $outfile $contents
        } finally {
            close $outfile
        }
    }
    
    writefile example/file.txt "example
    file
    contents"
    

    If you want, you can add in suitable trimming of the contents before writing (Tcl doesn't trim things unless you ask it to).

    proc writefile {filename contents} {
        set outfile [open $filename w]
        try {
            puts $outfile [string trim $contents "\n"]
        } finally {
            close $outfile
        }
    }
    
    writefile example/file.txt "
    example
    file
    contents
    "
    

    If you want more complex trimming (or other processing) rules, putting them in the procedure means that you don't have to clutter up the rest of your code with them. But the scope of possible rules is very wide; you're rapidly getting into totally application-specific stuff.