| [ Team LiB ] |
|
Searching Lists: lsearchlsearch returns the index of a value in the list, or -1 if it is not present. lsearch supports pattern matching in its search. Simple pattern matching is the default, and this can be disabled with the -exact option. The glob pattern matching lsearch uses is described in more detail on page 53. The -regexp option lets you specify the list value with a regular expression. Regular expressions are described in Chapter 11. In the following example, the glob pattern l* matches the value list, and lsearch returns the index of that element in the input list:
lsearch {here is a list} l*
=> 3
Example 5-7 shows ldelete as a combination of lreplace and lsearch: Example 5-7 Deleting a list element by value
proc ldelete { list value } {
set ix [lsearch -exact $list $value]
if {$ix >= 0} {
return [lreplace $list $ix $ix]
} else {
return $list
}
}
Tcl 8.4 added several features to lsearch, including typed searching, optimized searches for sorted lists, and the ability to find all matching elements of a list. The lsearch typed searches use the internal object representation for efficiency and speed. For example, if you have a list of numbers, the -integer option tells lsearch to leave the values in their native integer format. Otherwise it would convert them to strings as it did the search. If your list has been sorted, the -sorted option tells lsearch to perform an efficient binary search. Sorting lists is described on page 70. The -inline option returns the list value instead of the index. This is most useful when you are matching a pattern, and it works well with the -all option that returns all matching indices, or values:
set foo {the quick brown fox jumped over a lazy dog}
lsearch -inline -all $foo *o*
=> brown fox over dog
The lsearch options are described in Table 5-2:
|
| [ Team LiB ] |
|