How do I set default values ​​for Tcl variables?

I have several Tcl scripts that are executed by defining variables in a command line call:

$ tclsh84 -cmd <script>.tcl -DEF<var1>=<value1> -DEF<var2>=<value2>

      

Is there a way to check if var1 and var2 are not defined on the command line and then assign them a set of default values?

I've tried the global, variable and set keywords but they all give me this error when I say "if {$<var1>==""}"

:"can't read <var1>: no such variable"

0


a source to share


3 answers


I am not familiar with the -def option on tclsh.

However, to check if a variable is set, instead of using "catch", you can also use "info exist":



if { ![info exists blah] } {
  set blah default_value
}

      

+5


a source


Alternatively, you can use something like the cmdline package from tcllib. This allows you to customize and describe the default binary flags and name / value arguments so that a formatted help message can be displayed. For example, if you have a program that requires an input file name, and possibly an output file name, and a binary option to compress the output, you could use something like:

package require cmdline
set sUsage "Here you put a description of what your program does"
set sOptions {
    {inputfile.arg ""  "Input file name - this is required"}
    {outputfile.arg "out.txt"     "Output file name, if not given, out.txt will be used"}
    {compressoutput       "0"      "Binary flag to indicate whether the output file will be compressed"}
}

array set options [::cmdline::getoptions argv $sOptions $sUsage]
if {$options(inputfile) == ""} {puts "[::cmdline::usage $sOptions $sUsage]";exit}

      



The .arg suffix indicates that it is a name / value pair argument, if not listed it will assume it is a binary flag.

+1


a source


You can catch

your command to prevent the script error from being interrupted.

if { [ catch { set foo $<var1> } ] } {
    set <var1> defaultValue
}

      

(Warning: I haven't tested the exact syntax with the TCL interpreter, the above script should just give an idea).

0


a source







All Articles