I've "inherited" some Tcl code, and while I worked through some tutorials and can make sense out of the language, my own Tcl constructs lack a certain... finesse.
For example, I have this code:
puts "Column 'name': [ $queryRs getString name ]"
$queryRs
is the result set of a SQL query. The [ $queryRs getString name ]
construct retrieves the content of the table column "name" from the current row in the result set. If the database field is NULL, the puts
does not print anything.
I would like to print a "default" string instead, i.e. if [ $queryRs getString name ]
results in nothing, I'd like to replace it with "--"
.
Now, I could do something like this:
set nameVar "[ $queryRs getString name ]"
if { [ string length $nameVar ] == 0 } {
set nameVar "--"
}
puts "Column 'name': $nameVar"
But there has to be a more compact solution, something that can be done inline instead of adding four lines and a temporary variable. Help, please?
Two things.
First, Tcl doesn't have a notion of NULL
(nil
, undefined
or whatever) value, and when you want to simulate such a value you have to either use a variable and test for its existence or use an entry in an array
of dict
ionary and test for its existence, too. If such a variable/entry exists, then the value is defined, otherwise it's not.
Unfortunately, the creator of your inherited code apparently did not care about the case where a variable can be NULL
so NULLs
are indistinguishable from variables having default values (an empty string).
Next, you can use a helper procedure to do what you need:
proc ValueOrDef {val {def --}} {
expr {$val ne "" ? $val : $def}
}
and then go like this:
puts [ValueOrDef [$queryRs getString name]]
puts [ValueOrDef [$queryRs getString name] "some other default"]
You could use the x?y:z
construct of the expr
command. x
is the condition, y
is the alternative if the condition is met and z
is the alternative if x
is not met.
E.g. (but still with a temporary variable):
set nameVar [ $queryRs getString name ]
puts "Column 'name': [expr {[string length $nameVar]>0 ? $nameVar : "--"}]"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With