return to misc index

This Tcl script provides a couple of procedures for handling lists.

Listing 1

proc getFromList { inputList pattern } {
    foreach item $inputList {
       set f [lsearch $item $pattern]
       if { $f != -1 } {
          set value [lindex $item 1]
          return $value
    return "error"
proc getComponent { inputText index } {
    set comps [split $inputText]
    return [lindex $comps $index]

The input parameters are:

    inputList    a list of items to be searched
    pattern      returns the value associated with this item
The inputList must be list of pairs of items.
For example,
    set mylist {
        { frame {2}} 
        { startcolor {0.4 0.5 1}}
        { radius {5}}
    # print the radius to the console
    puts "radius = [getFromList $mylist radius]"
    inputText  text containing 3 values
    index      the index of the value to be returned
    # print the red component of a color to the console
    set color [getFromList $mylist startcolor]
    set r [getComponent $color 0]
    puts "red component is $r"

© 2002- Malcolm Kesson. All rights reserved.