Version 1 of How can I get input from a user and then safely make use of it?

Updated 2003-09-02 13:48:31

Purpose: discuss general guidelines for gathering input and then making use of it in Tcl.


A new user often finds s/he has a problem when dealing with user input.

Sometimes, the problem is a file name with a space in it. Sometimes, the problem is a string with special characters like [ or $ .

On this page, please add notes to help a new programmer avoid these problems.


One important thing is to keep the type of the input string in mind as you code. While Tcl has the reputation of everything is a string, not every command expects all its arguments to be arbitrary strings. In the most obvious example, Tcl input or output commands which require a file handle expects that argument to be a string returned from an open type command. Just handing some arbitrary string is very likely not going to work.

Similarly, handing an arbitrary string to a command which expects an argument in a list format may very well not work either:

 set s "this is a test of [ ; and ]"
 puts [llength $s]

does not result in a number, but instead with the error:

 invalid command name "and"
    while executing
 "and "
    invoked from within
 "set s "this is a test of [ ; and ]""
    (file "/tmp/s1.tcl" line 3)

If in the above example, s was the result of a gets or read Tcl command, the developer could find the same error arising from arbitrary user input.

The reason is that llength's interface is documented as requiring a list as its argument - the input above isn't a properly quoted list.

DGP - uhhh... no. Look at the stack trace above. We never reach the llength command because the error occurs during command substitution of the arguments to set. This is a simple error in Tcl syntax having nothing to do with list/string issues.


Category Tutorial | Category Security