Reputation: 1141
I have a variables with the same prefix. For example:
set prefix1Postfix 89
set prefix2Postfix 56
set prefix3Postfix 56
So is it possible iterate over them by this way:
set l [list prefix1 prefix2 prefix3]
foreach item $l {
puts "item = ${{$l}Postfix}"
}
Upvotes: 1
Views: 318
Reputation: 247192
In this scenario, the general advice is that it's easier to use arrays
set prefixPostfix(1) 89
set prefixPostfix(2) 56
set prefixPostfix(3) 56
foreach key [array names prefixPostfix] {
do something with $prefixPostfix($key)
}
Upvotes: 3
Reputation: 71598
No, Tcl is interpreting the {$l
part as a variable following the first opening and closing brace it encounters:
puts "item = ${{$l}Postfix}"
^---^
And the variable should have been $item
as well ;) The braces also prevent substitution, so that Tcl will look for literal $item
if you use braces.
One workaround you can use is to assign a variable to the suffix:
set prefix1Postfix 89
set prefix2Postfix 56
set prefix3Postfix 56
set l [list prefix1 prefix2 prefix3]
set p "Postfix"
foreach item $l {
puts "item = [set $item$p]"
}
Upvotes: 3