Richard Bucker

Find the First Non Empty String

Posted at — Jul 20, 2020

There is a common programming problem… you have some number of variables that may or may not have an empty string or sentinal value and in some predetermined priority order you want the first or maybe the last non sentinal value.

SQL has a pretty simple solution where the sentinal value is NULL (the … is not a language construct but to indicate that more are possible):

coalesce( value1, value2, value3, ...)

Another SQL use-case when the sentinal is an empty string. In this case the sentinal string is converted to a null and then the coalesce takes over as above.

coalesce( nullif(value1, ''), nullif(value2, ''), nullif(value3, ''), ...)

NOTE: coalesce is left to right only.

While this post is not specifically a language competition here is a similar implementation in tcl

lsearch -exact -not {"" "fred"} ""
1
lsearch -exact -not {"aa" "fred"} ""
0
lsearch -inline -exact -not {"" "fred"} ""
fred
lsearch -inline -exact -not {"aa" "fred"} ""
aa

Notice that in the above {"aa" "fred"} implies a list. So here is another example with the same results:

set l [list aa bb]
lsearch -not $l "aac"
0
lsearch -inline -not $l "aac"
aa

and then there is the design closer to the SQL but handles a NULL.

% proc eitherExists {varname default} {
    upvar $varname _varname
    expr {[info exists _varname] ? $_varname : $default}
}
% set l [list [eitherExists aa ""] bb cc]
{} bb
% lsearch -inline -not $l ""
bb
% lsearch -inline -not $l {}
bb

While tcl does not have an option for lsearch… there is a way to get from right to left.

% lsearch -inline -not [lreverse $l] {}
cc