Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tcl: default if variable is empty?

Tags:

string

tcl

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?

like image 816
DevSolar Avatar asked Jun 05 '12 08:06

DevSolar


2 Answers

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 dictionary 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"]
like image 165
kostix Avatar answered Oct 21 '22 06:10

kostix


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 : "--"}]"
like image 24
bmk Avatar answered Oct 21 '22 05:10

bmk