Tcl: by default, if the variable is empty?

I โ€œinheritedโ€ some Tcl code, and although I worked with some textbooks and could understand the meaning of the language, there is no specific ... finesse in my own Tcl constructs.

For example, I have this code:

puts "Column 'name': [ $queryRs getString name ]" 

$queryRs is a collection of SQL query results. The [ $queryRs getString name ] construct retrieves the contents of the column for the name table from the current row in the result set. If the database field is NULL, puts does not print anything.

I would like to print the string "default", i.e. if [ $queryRs getString name ] gives nothing, I would 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 it has a more compact solution, which can be done inline instead of adding four lines and a temporary variable. Help me please?

+4
source share
2 answers

Two things.

First of all, Tcl does not have the concept of NULL ( nil , undefined or any other) value, and when you want to simulate such a value, you need to either use the variable, either check its existence or use the entry in the array dict ionary and check its existence. If such a variable / record exists, then the value is determined, otherwise it is not.

Unfortunately, the creator of your legacy code clearly did not like the case where the variable may be NULL , so NULLs are indistinguishable from variables that have default values โ€‹โ€‹(empty string).

Next, you can use the auxiliary procedure to perform the necessary actions:

 proc ValueOrDef {val {def --}} { expr {$val ne "" ? $val : $def} } 

and then follow these steps:

 puts [ValueOrDef [$queryRs getString name]] puts [ValueOrDef [$queryRs getString name] "some other default"] 
+9
source

You can use the x?y:z construct of the expr command. x is a condition, y is an alternative if the condition is met, and z is an alternative if x not met.

eg. (but still with a temporary variable):

 set nameVar [ $queryRs getString name ] puts "Column 'name': [expr {[string length $nameVar]>0 ? $nameVar : "--"}]" 
+3
source

Source: https://habr.com/ru/post/1416106/


All Articles