Version 18 of In

Updated 2011-03-22 17:50:00 by Lordmundi

From Tcl 8.5 [L1 ], expr operator for list inclusion test.

 if {$el in $list} ...

is equivalent to, but much nicer than

 if {[lsearch -exact $list $el] >= 0} ...

The negation ("not in") is ni. So 8.5 Tcl really makes us knights who say 'ni'... For users of earlier versions, the following little helper comes in handy:

 proc in {list el} {expr [lsearch -exact $list $el] >= 0}}
 ...
 if [in $list $el] ...

- rs 2007-04-26


Let's see - so it would be something like:

 set el Mon
 if {$el in {Mon Tue Wed Thu Fri Sat Sun}} {
   puts "Valid day abbreviation"
 } else {
   puts "Invalid day abbreviation"
 }

Lordmundi 2011-03022

How come these aren't equivalent?

% set item foo
foo
% set list "1 2 3 4 5 foo"
1 2 3 4 5 foo
%
% if { $item in $list } { puts "Yep" }                                    
Yep
% expr ($item in $list)
invalid bareword "foo"
in expression "(foo in 1 2 3 4 5 foo)";

it seems when using expr, you have to do some funky explicit casting:

% expr ("$item" in [list $list])
1