Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tcl lsearch on list of list

Tags:

list

tcl

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.

like image 315
MKo Avatar asked May 05 '11 06:05

MKo


People also ask

How to use lsearch in Tcl?

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.

How do you find the index of an element in a list in Tcl?

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.

What is Lsearch?

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.


1 Answers

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.

like image 166
TrojanName Avatar answered Oct 20 '22 10:10

TrojanName