Cecil Westerhof <
Ce...@decebal.nl> wrote:
> I wrote a command-line tcl application to select a tea to brew.
>
> It gets a list with teas. Displays them and let you select one. With
> #q or #r you can exit the selection. Otherwise you have to enter a
> correct value and the corresponding tea and location is returned in a
> list.
>
> Can this be improved?
One small change (not sure it could be classed as an "improvement" per
se.) could be changing this (which looks very C like) to be more Tcl
like:
> for {set i 0} {${i} < ${nrOfTeas}} {incr i} {
> set tea [lindex ${teaList} ${i}]
> puts [format "%d: %-30s %-10s %2s" \
> [expr ${i} + 1] \
> [dict get ${tea} Tea] \
> [dict get ${tea} LastUsed] \
> [dict get ${tea} Location]]
> }
set i 0
foreach tea $teaList {
puts [format "%d: %-30s %-10s %2s" \
[incr i] \
[dict get ${tea} Tea] \
[dict get ${tea} LastUsed] \
[dict get ${tea} Location]]
}
Provided you don't have variable name conflicts from keys in the dicts,
you can further shorten by using "dict with" to expand the dict (dict
with operates /very/ similarly to the "with" statement from Pascal, for
accessing fields of records without needing to attach the record
prefix, only for dicts in Tcl):
set i 0
foreach tea $teaList {
dict with $tea {
puts [format "%d: %-30s %-10s %2s" \
[incr i] $Tea $LastUsed $Location]
}
}
Note that if you /do/ have variable name conflicts with the dict keys,
you can substitute "dict update" for "dict with" and specify which keys
should be expanded, and into what variable names their contents should
be placed. More verbose than the dict with case, but you have more
control on exactly what happens.