Tcl sandwich - lists in Tcl
Archive - Originally posted on "The Horse's Mouth" - 2004-12-08 01:50:44 - Graham EllisIn Tcl, a list is simply a string that's held in the same format (i.e. with the same delimiters and protection) as a series of parameters to a Tcl command. The split command (which does a great deal in languages such as Perl and PHP) really does little more than change the delimiters if need be, and add protective \ { and } characters - again only if need be.
Here's an example where we're splitting and manipulating the contents of a sandwich.
tcl>set sarnie "cheese, marmite, onion, pickle"
tcl>set d4 [split $sarnie ,]
tcl>set d4
cheese { marmite} { onion} { pickle}
At this point, the braces have been added to protect the space character which is part of the individual ingredient
tcl>foreach ingrid $d4 {
=>puts [string trim $ingrid]
=>}
cheese
marmite
onion
pickle
I used string trim to remove the space before printing each element out
Let's rejoin the ingredients into a string using the word "and" as the glue
tcl>set d5 [join $d4 " and "]
tcl>set d5
cheese and marmite and onion and pickle
or as an alternative, print it out sorted into the order of ingedients with my favourite first ;-)
tcl>lsort $d4
{ marmite} { onion} { pickle} cheese
tcl>