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"
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.
a source to share