Main Content

Lists in Tcl - fundamentals in a commented source code example

Archive - Originally posted on "The Horse's Mouth" - 2013-11-16 14:22:18 - Graham Ellis

When I'm writing code demonstrations during class, they usually start off tidy and then get a bit scruffy as I add things in to answer delegate questions. For once last week, a Tcl list demonstration didn't get too untidy, so I give it you here with comments about what each few lines does.

  # different ways of setting up a list
  # (each of these contains three members)
  
  set party "{Ann Marie} Brenda Charles"
  set party "\"Ann Marie\" Brenda Charles"
  set party {"Ann Marie" Brenda Charles}
  set party "Ann\ Marie Brenda Charles"
  set party {Ann\ Marie Brenda Charles}
  set party [list "Ann Marie" Brucella Charlie]
  
  # Append adds a string (so no space)
  # but lappend adds a list member (so spaced and protected)
  lappend party Brown
  lappend party Douggie
  
  puts $party
  # That prints:
  # {Ann Marie} Brucella CharlieBrown Douggie
  
  # How long is the "party" variable?
  puts [string length $party]
  puts [llength $party]
  # It's one list. Or a list with 4 indexed members. Or a string of 42 characters
  
  # What's the first item?
  set first [lindex $party 0]
  puts $first
  
  # What's the last item?
  set last [lindex $party [expr [llength $party] -1 ]]
  puts $last
  # surely there must be an easier way of doing that!
  set last [lindex $party end]
  puts $last
  
  # Here we are looping through each item of the list
  #Â in this example, we do NOT want to keep track of the position number
  foreach person $party {
    puts "Invite $person to the party"
    }
  
  # Here we are looping through each item of the list
  #Â in this example, we DO want to keep track of the position number
  for {set count 0} {$count < [llength $party]} {incr count} {
    set name [lindex $party $count]
    puts "I expect person $count will come (that's $name )"
    }


You can see sample output on the end of the code [here], and of course you can come on one of our courses to learn it yourself from me!