Search code examples
shellscriptingtcltclsh

Open file in Tcl with variables inside


I want to open a file called filelist.txt which contains only the string ${PATHFILE}/test.txt, read the line and open the file test.txt. The file test.txt is present inside the folder ~/testfile.
Consider this sample code:

#!/usr/bin/env tclsh

set PATHFILE "~/testfile"

set fp [open "filelist.txt" r]
set lines [split [read $fp] "\n"]
close $fp   

foreach line $lines {
    set fp1 [open $line r]
    close $fp1
}

The problem is that it seems that the "open" command cannot find the PATHFILE variable and i get this error:

couldn't open "${PATHFILE}/test.txt": no such file or directory

If i try to open the file with set fp1 [open "${PATHFILE}/test.txt" r] i don't have any errors.


Solution

  • Yes, you can use the TCL subst command to evaluate the PATHFILE variable. Note that you might still have an issue with the tilde ~ - it may be better to use full path names.

    #!/usr/bin/env tclsh
    
    set PATHFILE "~/testfile"
    
    set fp [open "filelist.txt" r]
    set lines [split [read $fp] "\n"]
    close $fp   
    
    foreach line $lines {
        set fp1 [open [subst $line] r]
        close $fp1
    }