Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Why is searching an element with "[]" in a list == -1?

Status
Not open for further replies.

firelex

Programmer
Jan 10, 2002
118
DE
Hello all!

I have such a script
[tt]
.......
set list {{a b} {a b (c)} {a b ([d])}}
puts stdout "$list"

foreach el $list {
puts stdout &quot;<$el> --> [lsearch $list $el]&quot;
}
puts stdout &quot;[lsearch $list {a b ([d])}]&quot;
.......
[/tt]

Why is searching of the last element of the list always [tt]-1[/tt]?

Thanks.
 
I don't know why but if you change &quot;[d]&quot; to &quot;(d)&quot; it works fine. I think the [] is trying to invoke &quot;d&quot;? Bob Rashkin
rrashkin@csc.com
 
Right.
This may seem to work:
lsearch -regexp $list &quot;\[d\]&quot;

But really it doesn't work either.
set list {a b} {a b (c) dd} {a b ([d])}
lsearch -regexp $list &quot;\[d\]&quot;
1

This is a problem and the fix is somewhat
complicated.
Try this thread:
 
Thanks, marsd!
It was a good example, but I've found yesterday that -->
[tt]
.......
set list {{a b} {a b (c)} {a b ([d])}}
puts stdout &quot;$list&quot;

foreach el $list {
puts stdout &quot;<$el> --> [lsearch -exact $list $el]&quot;
}
puts stdout &quot;[lsearch -exact $list {a b ([d])}]&quot;
.......
[/tt]

works also. Really incredible .............
 
Yes, using the lsearch -exact option is by far the easiest and safest way to search, as long as you don't need wildcard abilities in the pattern. lsearch can be a bit confusing, as it's one of the few commonly-used commands that I can think of that defaults to glob-style matching (that is, the same wildcards as supported by the string match command).

By the way, Tcl 8.4 added several useful new options to the lsearch command. You might want to check out the reference page at to find out more about them. - Ken Jones, President, ken@avia-training.com
Avia Training and Consulting, 866-TCL-HELP (866-825-4357) US Toll free
415-643-8692 Voice
415-643-8697 Fax
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top