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"} ""
lsearch -exact -not {"aa" "fred"} ""
lsearch -inline -exact -not {"" "fred"} ""
lsearch -inline -exact -not {"aa" "fred"} ""

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"
lsearch -inline -not $l "aac"

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 ""
% lsearch -inline -not $l {}

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

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