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

gle*_*man 2 tcl

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

set words {apple banana grape pear peach}
lmap word $words {if {[string length $word] == 5} {expr {"$word"}} else continue}
# ==> apple grape peach
Run Code Online (Sandbox Code Playgroud)

我对引用的混乱不满意expr {"$word"}.我希望这会奏效:

lmap word $words {if {[string length $word] == 5} {return $word} else continue}
# ==> apple
Run Code Online (Sandbox Code Playgroud)

什么是从lmap主体"返回"字符串的优雅方式?

Don*_*ows 5

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

lmap word $words {
    if {[string length $word] != 5} {
        continue
    };
    set word
}
Run Code Online (Sandbox Code Playgroud)
lmap word $words {
    if {[string length $word] == 5} {
        # Requires 8.6.3 or later
        string cat $word
    } else {
        continue
    }
}
Run Code Online (Sandbox Code Playgroud)