There is a list of list in Tcl.
set somelist {{aaa 1} {bbb 2} {ccc 1}}
How to search the list's element which first item is "bbb"?
I tried this way but it doesn't work.
lsearch $somelist "{bbb *}"
Thanks.
lsearch returns the index of the first element in list that that matches pattern, or -1 if there are no matches. Before Tcl 8.5 introduced the in operator, lsearch was very frequently used to test for the existence of a value in a list.
To see if an element exists within a list, use the lsearch function: if {[lsearch -exact $myList 4] >= 0} { puts "Found 4 in myList!" } The lsearch function returns the index of the first found element or -1 if the given element wasn't found.
DESCRIPTION. The lsearch() function shall linearly search the table and return a pointer into the table for the matching entry. If the entry does not occur, it shall be added at the end of the table. The key argument points to the entry to be sought in the table.
Use -index, it's designed for exactly this case. As ramanman points out, when you have a list, use list procedures. Have you thought about what happens if you have multiple matches?
In your case, I would just do this:
% lsearch -index 0 -all -inline $somelist bbb
{bbb 2}
% lsearch -index 0 -all $somelist "bbb"
1
% lsearch -index 0 -all $somelist "ccc"
2
You use -index of 0 to specify that you are interested in the first index of the outer list. -all returns all results. And you can use -inline if you just want the value of list element that matches, omit it if you just want the index of the matching element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With