The subst Command

   

Practical Programming in Tcl & Tk, Third Edition
By Brent B. Welch

Table of Contents
Chapter 10.  Quoting Issues and Eval


The subst Command

The subst command is useful when you have a mixture of Tcl commands, Tcl variable references, and plain old data. The subst command looks through the data for square brackets, dollar signs, and backslashes, and it does substitutions on those. It leaves the rest of the data alone:

 set a "foo bar" subst {a=$a date=[exec date]} => a=foo bar date=Thu Dec 15 10:13:48 PST 1994 

The subst command does not honor the quoting effect of curly braces. It does substitutions regardless of braces:

 subst {a=$a date={[exec date]}} => a=foo bar date={Thu Dec 15 10:15:31 PST 1994} 

You can use backslashes to prevent variable and command substitution.

 subst {a=\$a date=\[exec date]} => a=$a date=[exec date] 

You can use other backslash substitutions like \uXXXX to get Unicode characters, \n to get newlines, or \-newline to hide newlines.

The subst command takes flags that limit the substitutions it will perform. The flags are -nobackslashes, -nocommands, or -novariables. You can specify one or more of these flags before the string that needs to be substituted:

 subst -novariables {a=$a date=[exec date]} => a=$a date=Thu Dec 15 10:15:31 PST 1994 

String Processing with subst

The subst command can be used with the regsub command to do efficient, two-step string processing. In the first step, regsub is used to rewrite an input string into data with embedded Tcl commands. In the second step, subst or eval replaces the Tcl commands with their result. By artfully mapping the data into Tcl commands, you can dynamically construct a Tcl script that processes the data. The processing is efficient because the Tcl parser and the regular expression processor have been highly tuned. Chapter 11 has several examples that use this technique.


       
    Top
     



    Practical Programming in Tcl and Tk
    Practical Programming in Tcl and Tk (4th Edition)
    ISBN: 0130385603
    EAN: 2147483647
    Year: 1999
    Pages: 478

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net