I need to access a value in array which has been created in a dynamic way – meaning array’s name is stored in a variable.
To do this I try to use eval command but then get lost with the usage of $.
I do succeed to retrieve a key-value pair because no $ is required in a command like array get but what I need to use is array(key) pattern.
The expected simplified code would look like:
set arr foo;
set val1 v1;
set val2 v2;
eval "array set $arr \{
key1 $val1
key2 $val2
\}";
eval "set x \${$arr(key1)}";
As for the last line which is actually the failure, I’ve tried the following options:
eval "set x \${$arr}(key1)";
or
eval "set x \$$arr(key1)"
and even more weird but with no success.
>Solution :
Remember that $var is shorthand for [set var]. So you could write the command as:
set x [set ${arr}(key1)]
But for these kind of situations, it’s probably easiest to use upvar:
upvar 0 $arr arrvar
set x $arrvar(key1)