. More list commands - lsearch, lsort, lrange .
[ Previous | Index | Next ]
Lists can be searched with the lsearch command, sorted with the lsort command, and a range of list entries can be extracted with the lrange command.
- lsearch list pattern
- searches list for an entry that matches pattern, and returns the index for the first match, or a -1 if there is no match.
- lsort list
- sorts list and returns a new list in the sorted order. By default, it sorts the list into alphabetic order.
- lrange list first last
- returns a list composed of the first through last entries in the list. If first is less than or equal to 0, it is treated as the first list element. If last is end or a value greater than the number of elements in the list, it is treated as the end. If first is greater than last then an empty list is returned.
By default, lsearch uses the globbing method of finding a match. Globbing is the wildcarding technique that most Unix shells use.
globbing wildcards are:
- *
- Matches any quantity of any character
- ?
- Matches one occurrence of any character
- \X
- The backslash escapes a special character in globbing just the way it does in Tcl substitutions. Using the backslash lets you use glob to match a * or ?.
- [...]
- Matches one occurrence of any character within the brackets. A range of characters can be matched by using a range between the brackets. For example, [a-z] will match any lower case letter.
--
. Example .
set list [list {Washington 1789} {Adams 1797} {Jefferson 1801} \
{Madison 1809} {Monroe 1817} {Adams 1825} ]
set x [lsearch $list Washington*]
set y [lsearch $list Madison*]
incr x; incr y -1 ;# Set range to be not-inclusive
set subsetlist [lrange $list $x $y]
puts "The following presidents served between Washington and Madison"
foreach item $subsetlist {
puts "Starting in [lindex $item 1]: President [lindex $item 0] "
}
set x [lsearch $list Madison*]
set srtlist [lsort $list]
set y [lsearch $srtlist Madison*]
puts "\n$x Presidents came before Madison chronologically"
puts "$y Presidents came before Madison alphabetically"
|