使用 `lmap` 过滤字符串列表

Using `lmap` to filter list of strings

假设我想从列表中获取所有 5 个字母的单词。

set words {apple banana grape pear peach}
lmap word $words {if {[string length $word] == 5} {expr {"$word"}} else continue}
# ==> apple grape peach

我对 expr {"$word"} 的引用混乱不满意。我希望这会起作用:

lmap word $words {if {[string length $word] == 5} {return $word} else continue}
# ==> apple

从 lmap 主体 "return" 字符串的优雅方法是什么?

我一般用set:

lmap word $words {if {[string length $word] == 5} {set word} else continue}

或有时(如果我确定 expr 不会重新解释 word 中的值):

lmap word $words {expr {[string length $word] == 5 ? $word : [continue]}}

当然还有这个:

lsearch -regexp -all -inline $words ^.{5}$

文档:continue, expr, if, lmap, lsearch, set, string

主要选择是使用 set 或使用 string cat(假设您是最新的)。为了清楚起见,我将下面的示例分成多行:

lmap word $words {
    if {[string length $word] != 5} {
        continue
    };
    set word
}
lmap word $words {
    if {[string length $word] == 5} {
        # Requires 8.6.3 or later
        string cat $word
    } else {
        continue
    }
}