2
votes

i have tcl list of strings

set NameList [list 'foo' 'moo 1' 'too 1 3' 'Enterprise 1'] 
and i try to check if "foo" is in the list but i get false
set test "foo"
 if {[lsearch -exact $NameList $test] >= 0} {    
        return 1
  }   

UPDATE
i changed the Double quotes with single quote BUT i set the Variable test with "foo"
but still it doesn't work

1
I have checked this and it is working fine. lsearch -exact $NameList "foo" will return 0, which represents the index of the element foo in the list NameList.Dinesh
The curly brackets are used in tcl to wrap string with spaces. In tcl all is a string, even the lists. So you did't do something wrong.Mario Santini
Single quotes are not a quoting character in Tcl.Brad Lanam
To emphasize what Brad said: single quotes are just plain characters in Tcl. The first element in $NameList is the 5-character string "'foo'"glenn jackman

1 Answers

5
votes

When I try your code, it works exactly correctly for me:

% set NameList [list "foo" "moo 1" "too 1 3" "Enterprise 1"] 
foo {moo 1} {too 1 3} {Enterprise 1}
% if {"foo" in $NameList} { puts "got it!" }
got it!
% lsearch -exact $NameList "foo"
0
% lsearch -exact $NameList "not there at all"
-1

The auto-quoting of the strings with {} instead of "" isn't anything you need to worry about. It won't affect the values in the list; they will be exactly the strings you specified.

Oh, and for simple literal value containment tests, do consider the in operator as I use it above. It's clearer and says what you mean more. Available in any currently supported release of Tcl (i.e., introduced in 8.5).